diff --git a/res/values-it/strings.xml b/res/values-it/strings.xml index b1068e1..94c8230 100644 --- a/res/values-it/strings.xml +++ b/res/values-it/strings.xml @@ -1,83 +1,84 @@ Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy. Cerca QR Code Numero fermata Nome fermata Inserisci il numero della fermata Inserisci il nome della fermata Alcuni caratteri non sono stati riconosciuti Verifica l\'accesso ad Internet! Nessun arrivo previsto per questa fermata Sembra che nessuna fermata abbia questo nome Errore di lettura del sito 5T/GTT (dannato sito!) Fermata: %1$s Linee: %1$s Scegli la fermata… Nessun passaggio Nessun QR code Preferiti Aiuto Informazioni Più informazioni News Invia bug Codice sorgente Licenza Incontra l\'autore Fermata aggiunta ai preferiti + Impossibile aggiungere ai preferiti (memoria piena o database corrotto?)! Preferiti Tocca il nome di una fermata per aggiungerla in questa lista Rimuovi Rinomina Rinomina fermata Reset Informazioni Tocca il nome della fermata per aggiungerla ai preferiti\n\nCome leggere gli orari:\n   12:56* Orario in tempo reale\n   12:56   Orario programmato\n\nTrascina giù per aggiornare l\'orario. OK ! Benvenuto!

Grazie per aver scelto BusTO, un\'app \"politicamente\" indipendente da GTT/5T, per spostarsi a Torino attraverso software libero:

-

Perchè usare BusTO?

+

Perché usare BusTO?

- Non sei monitorato
- Non ci sono pubblicità
- La tua privacy è al sicuro
- Inoltre l\'app è molto leggera!

Come Funziona?

Quest\'app ottiene i passaggi dei bus in tempo reale filtrando i dati forniti pubblicamente sul sito www.5t.torino.it «per uso personale».

Ingredienti:
- Valerio Bozzolan sviluppatore principale.
- Marco Gagino intenso collaboratore, creatore dell\'icona, responsabile della grafica.
- Paolo Alloatti per l\'idea dell\'icona.
- JSoup libreria per "web scaping".
- makovkastar bottone fluttuante.
- Google icone Material Design.
- Tutti i contributori!

Licenze

L\'app e il relativo codice sorgente sono distribuiti sotto la licenza GNU General Public License v3+. Ciò significa che puoi usare, studiare, migliorare e ricondividere quest\'app con qualunque mezzo e per qualsiasi scopo: a patto di mantenere sempre questi diritti a tua volta e di dare credito a Valerio Bozzolan.

Note

Quest\'applicazione è rilasciata nella speranza che sia utile a tutti ma senza NESSUNA garanzia.

Buon utilizzo! :)

]]>
Nome troppo corto, digita più caratteri e riprova %1$s verso %2$s %s (destinazione sconosciuta) - Errore interno inaspettato che non dovrebbe mai accadere! + Errore interno inaspettato, impossibile estrarre dati dal sito GTT\5T
diff --git a/res/values/strings.xml b/res/values/strings.xml index bf1d6da..254233d 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,82 +1,83 @@ BusTO Stai utilizzando l\'ultimo ritrovato in materia di rispetto della tua privacy. Search Scan QR Code Bus stop number Bus stop name Insert bus stop number Insert bus stop name %1$s towards %2$s %s (unknown destination) Sorry but you are using not allowed characters Verify the state of your Internet connection! No bus is supposed to arrive at this stop Seems that no bus stop have this name Error parsing the 5T/GTT website (damn site!) Name too short, type more characters and retry Arrivals at: %1$s Choose the bus stop… Lines: %1$s No passages No QR code - Unexpected internal error that should never happen! - Favorites + Unexpected internal error, cannot extract data from GTT\5T website Help About More about News releases Bug submission Source code Licence Meet the author Bus stop is now in your favorites + Favorites Favorites Press on a bus stop name to populate this list Delete Rename Rename the bus stop Reset About Tap the bus stop name to add it to the favourites\n\nHow to read timelines:\n   12:56* Real time arrival\n   12:56   Scheduled time of arrival\n\nPull down to refresh the timetable GOT IT! Welcome!

Thanks for using BusTO, a "politically" independent app useful to move around Torino using a Free/Libre software.

Why using this app?

- You\'ll never be tracked
- You\'ll never see boring ads
- We\'ll always respect your privacy
- Moreover, it\'s lightweight!

How does it work?

This app will show you the timetable of the buses using the information published on the site www.5t.torino.it.

Who worked on BusTO:
- Valerio Bozzolan main developer.
- Marco Gagino main contributor and icon creator.
- Paolo Alloatti original concept of the icon.
- JSoup web scraper library.
- makovkastar floating buttons.
- Google Material Design icons.
- All the contributors!

Licenses

The app and the related source code are released by Valerio Bozzolan under the terms of the GNU General Public License v3+). So everyone is allowed to use, to study, to improve and to share this app by any kind of means and for any purpose: under the conditions of maintaining this rights and of attributing the original work to Valerio Bozzolan.

Notes

This app has been developed hoping to be useful to everyone but without ANY warranty.

This translation is kindly provided by Riccardo Caniato and Marco Gagino.

Get involved! :)

]]>
+ Cannot add to favorites (no more space or corrupted database?)!
diff --git a/src/it/reyboz/bustorino/ActivityFavorites.java b/src/it/reyboz/bustorino/ActivityFavorites.java index 3cc6ca0..70f109b 100644 --- a/src/it/reyboz/bustorino/ActivityFavorites.java +++ b/src/it/reyboz/bustorino/ActivityFavorites.java @@ -1,252 +1,253 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.middleware.StopAdapter; import it.reyboz.bustorino.middleware.StopsDB; import it.reyboz.bustorino.middleware.UserDB; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.os.AsyncTask; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import java.util.List; public class ActivityFavorites extends AppCompatActivity { private ListView favoriteListView; private SQLiteDatabase userDB; private EditText bus_stop_name; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_favorites); // this should be done in onStarted and closed in onStop, but apparently onStarted is never run. this.userDB = new UserDB(getApplicationContext()).getWritableDatabase(); ActionBar ab = getSupportActionBar(); assert ab != null; ab.setIcon(R.drawable.ic_launcher); ab.setDisplayHomeAsUpEnabled(true); // Back button favoriteListView = (ListView) findViewById(R.id.favoriteListView); createFavoriteList(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (v.getId() == R.id.favoriteListView) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu_favourites_entry, menu); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Respond to the action bar's Up/Home button case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; } return super.onOptionsItemSelected(item); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Stop busStop = (Stop) favoriteListView.getItemAtPosition(info.position); switch (item.getItemId()) { case R.id.action_favourite_entry_delete: - // TODO: implement - //busStop.setIsFavorite(false); - //UserDB.DBBusStop.addBusStop(db, busStop); + UserDB.deleteStop(busStop, this.userDB); createFavoriteList(); return true; case R.id.action_rename_bus_stop_username: showBusStopUsernameInputDialog(busStop); return true; default: return super.onContextItemSelected(item); } } void createFavoriteList() { // TODO: memoize default list, query only user names every time? new AsyncGetFavorites(getApplicationContext(), this.userDB).execute(); } public void showBusStopUsernameInputDialog(final Stop busStop) { AlertDialog.Builder builder = new AlertDialog.Builder(this); LayoutInflater inflater = this.getLayoutInflater(); View renameDialogLayout = inflater.inflate(R.layout.rename_dialog, null); bus_stop_name = (EditText) renameDialogLayout.findViewById(R.id.rename_dialog_bus_stop_name); bus_stop_name.setText(busStop.getStopDisplayName()); bus_stop_name.setHint(busStop.getStopDefaultName()); builder.setTitle(getString(R.string.dialog_rename_bus_stop_username_title)); builder.setView(renameDialogLayout); builder.setPositiveButton(getString(android.R.string.ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { String busStopUsername = bus_stop_name.getText().toString(); String oldUserName = busStop.getStopUserName(); // changed to none if(busStopUsername.length() == 0) { // unless it was already empty, set new if(oldUserName != null) { busStop.setStopUserName(null); UserDB.updateStop(busStop, userDB); createFavoriteList(); } } else { // changed to something // something different? if(oldUserName == null || !busStopUsername.equals(oldUserName)) { busStop.setStopUserName(busStopUsername); UserDB.updateStop(busStop, userDB); createFavoriteList(); } } } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.setNeutralButton(R.string.dialog_rename_bus_stop_username_reset_button, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // delete user name from database busStop.setStopUserName(null); UserDB.updateStop(busStop, userDB); createFavoriteList(); } }); builder.show(); } /** * This one runs. onStart instead gets ignored for no reason whatsoever. * * @see Android Activity Lifecycle */ @Override protected void onStop() { super.onStop(); this.userDB.close(); } private class AsyncGetFavorites extends AsyncTask> { private Context c; private SQLiteDatabase userDB; AsyncGetFavorites(Context c, SQLiteDatabase userDB) { this.c = c; this.userDB = userDB; } @Override protected List doInBackground(Void... voids) { StopsDB stopsDB = new StopsDB(c); stopsDB.openIfNeeded(); List busStops = UserDB.getFavorites(this.userDB, stopsDB); stopsDB.closeIfNeeded(); return busStops; } @Override protected void onPostExecute(List busStops) { // If no data is found show a friendly message if (busStops.size() == 0) { favoriteListView.setVisibility(View.INVISIBLE); TextView favoriteTipTextView = (TextView) findViewById(R.id.favoriteTipTextView); assert favoriteTipTextView != null; favoriteTipTextView.setVisibility(View.VISIBLE); } /* There's a nice method called notifyDataSetChanged() to avoid building the ListView * all over again. This method exists in a billion answers on Stack Overflow, but * it's nowhere to be seen around here, Android Studio can't find it no matter what. * Anyway, it only works from Android 2.3 onward (which is why it refuses to appear, I * guess) and requires to modify the list with .add() and .clear() and some other * methods, so to update a single stop we need to completely rebuild the list for no * reason. It would probably end up as "slow" as throwing away the old ListView and * redrwaing everything. */ // Show results favoriteListView.setAdapter(new StopAdapter(this.c, busStops)); favoriteListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView parent, View view, int position, long id) { /** * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener */ Stop busStop = (Stop) parent.getItemAtPosition(position); Intent intent = new Intent(ActivityFavorites.this, ActivityMain.class); Bundle b = new Bundle(); + // TODO: is passing a serialized object a good idea? Or rather, is it reasonably fast? + //b.putSerializable("bus-stop-serialized", busStop); b.putString("bus-stop-ID", busStop.ID); + b.putString("bus-stop-display-name", busStop.getStopDisplayName()); intent.putExtras(b); //intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP); startActivity(intent); finish(); } }); registerForContextMenu(favoriteListView); } } } diff --git a/src/it/reyboz/bustorino/ActivityMain.java b/src/it/reyboz/bustorino/ActivityMain.java index 34d469d..56713ac 100644 --- a/src/it/reyboz/bustorino/ActivityMain.java +++ b/src/it/reyboz/bustorino/ActivityMain.java @@ -1,846 +1,852 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.sqlite.SQLiteDatabase; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.NavUtils; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import com.melnykov.fab.FloatingActionButton; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import it.reyboz.bustorino.backend.ArrivalsFetcher; import it.reyboz.bustorino.backend.Fetcher; import it.reyboz.bustorino.backend.FiveTNormalizer; import it.reyboz.bustorino.backend.FiveTScraperFetcher; import it.reyboz.bustorino.backend.FiveTStopsFetcher; import it.reyboz.bustorino.backend.GTTJSONFetcher; import it.reyboz.bustorino.backend.GTTStopsFetcher; import it.reyboz.bustorino.backend.Palina; import it.reyboz.bustorino.backend.Route; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.backend.StopsFinderByName; import it.reyboz.bustorino.middleware.UserDB; import it.reyboz.bustorino.middleware.AsyncWget; import it.reyboz.bustorino.middleware.PalinaAdapter; import it.reyboz.bustorino.middleware.RecursionHelper; import it.reyboz.bustorino.middleware.StopAdapter; import it.reyboz.bustorino.middleware.StopsDB; public class ActivityMain extends AppCompatActivity { /* * Layout elements */ private EditText busStopSearchByIDEditText; private EditText busStopSearchByNameEditText; private TextView busStopNameTextView; private ProgressBar progressBar; private TextView howDoesItWorkTextView; private Button hideHintButton; private MenuItem actionHelpMenuItem; private SwipeRefreshLayout swipeRefreshLayout; private ListView resultsListView; private FloatingActionButton floatingActionButton; /* * Serach mode */ private static final int SEARCH_BY_NAME = 0; private static final int SEARCH_BY_ID = 1; private static final int SEARCH_BY_ROUTE = 2; // TODO: implement this (bug #1512948) private int searchMode; /* * Options */ private final String OPTION_SHOW_LEGEND = "show_legend"; /** * Last successfully searched bus stop ID */ private @Nullable Stop lastSuccessfullySearchedBusStop = null; /* // useful for testing: public class MockFetcher implements ArrivalsFetcher { @Override public Palina ReadArrivalTimesAll(String routeID, AtomicReference res) { SystemClock.sleep(5000); res.set(result.SERVER_ERROR); return new Palina(); } } private ArrivalsFetcher[] ArrivalFetchers = {new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher(), new MockFetcher()};*/ private RecursionHelper ArrivalFetchersRecursionHelper = new RecursionHelper<>(new ArrivalsFetcher[] {new GTTJSONFetcher(), new FiveTScraperFetcher()}); private RecursionHelper StopsFindersByNameRecursionHelper = new RecursionHelper<>(new StopsFinderByName[] {new GTTStopsFetcher(), new FiveTStopsFetcher()}); private StopsDB stopsDB; private UserDB userDB; ///////////////////////////////// EVENT HANDLERS /////////////////////////////////////////////// /* * @see swipeRefreshLayout */ private Handler handler = new Handler(); private final Runnable refreshing = new Runnable() { public void run() { if (lastSuccessfullySearchedBusStop == null) { Toast.makeText(getApplicationContext(), R.string.query_too_short, Toast.LENGTH_SHORT).show(); } else { new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.stopsDB = new StopsDB(getApplicationContext()); this.userDB = new UserDB(getApplicationContext()); setContentView(R.layout.activity_main); busStopSearchByIDEditText = (EditText) findViewById(R.id.busStopSearchByIDEditText); busStopSearchByNameEditText = (EditText) findViewById(R.id.busStopSearchByNameEditText); busStopNameTextView = (TextView) findViewById(R.id.busStopNameTextView); progressBar = (ProgressBar) findViewById(R.id.progressBar); howDoesItWorkTextView = (TextView) findViewById(R.id.howDoesItWorkTextView); hideHintButton = (Button) findViewById(R.id.hideHintButton); resultsListView = (ListView) findViewById(R.id.resultsListView); swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout); floatingActionButton = (FloatingActionButton) findViewById(R.id.floatingActionButton); if (floatingActionButton != null) { floatingActionButton.attachToListView(resultsListView); } busStopSearchByIDEditText.setSelectAllOnFocus(true); busStopSearchByIDEditText .setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; } }); busStopSearchByNameEditText .setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { // IME_ACTION_SEARCH alphabetical option if (actionId == EditorInfo.IME_ACTION_SEARCH) { onSearchClick(v); return true; } return false; } }); // Called when the layout is pulled down swipeRefreshLayout .setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { handler.post(refreshing); } }); /** * @author Marco Gagino!!! */ swipeRefreshLayout.setColorSchemeColors(R.color.blue_500, R.color.orange_500); // setColorScheme is deprecated, setColorSchemeColors isn't setSearchModeBusStopID(); //---------------------------- START INTENT CHECK QUEUE ------------------------------------ // Intercept calls from URL intent boolean tryedFromIntent = false; String busStopID = null; + String busStopDisplayName = null; Uri data = getIntent().getData(); if (data != null) { busStopID = getBusStopIDFromUri(data); tryedFromIntent = true; } // Intercept calls from other activities if (!tryedFromIntent) { Bundle b = getIntent().getExtras(); if (b != null) { busStopID = b.getString("bus-stop-ID"); + busStopDisplayName = b.getString("bus-stop-display-name"); /** * I'm not very sure if you are coming from an Intent. * Some launchers work in strange ways. */ tryedFromIntent = busStopID != null; } } //---------------------------- END INTENT CHECK QUEUE -------------------------------------- if (busStopID == null) { // Show keyboard if can't start from intent showKeyboard(); // You haven't obtained anything... from an intent? if (tryedFromIntent) { // This shows a luser warning - // TODO: did I accidentally remove the warning? ArrivalFetchersRecursionHelper.reset(); + Toast.makeText(getApplicationContext(), + R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); } } else { // If you are here an intent has worked successfully setBusStopSearchByIDEditText(busStopID); + this.lastSuccessfullySearchedBusStop = new Stop(busStopID); + // forcing it as user name even though it could be standard name, it doesn't really matter + this.lastSuccessfullySearchedBusStop.setStopUserName(busStopDisplayName); new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } Log.d("MainActivity", "Created"); } /** * Reload bus stop timetable when it's fulled resumed from background. */ @Override protected void onPostResume() { super.onPostResume(); Log.d("ActivityMain", "onPostResume fired. Last successfully bus stop ID: " + lastSuccessfullySearchedBusStop); if (searchMode == SEARCH_BY_ID && lastSuccessfullySearchedBusStop != null) { setBusStopSearchByIDEditText(lastSuccessfullySearchedBusStop.ID); new asyncWgetBusStopFromBusStopID(lastSuccessfullySearchedBusStop.ID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); actionHelpMenuItem = menu.findItem(R.id.action_help); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. switch (item.getItemId()) { case android.R.id.home: // Respond to the action bar's Up/Home button NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_help: showHints(); return true; case R.id.action_favorites: startActivity(new Intent(ActivityMain.this, ActivityFavorites.class)); return true; case R.id.action_about: startActivity(new Intent(ActivityMain.this, ActivityAbout.class)); return true; case R.id.action_news: openIceweasel("http://blog.reyboz.it/tag/busto/"); return true; case R.id.action_bugs: openIceweasel("https://bugs.launchpad.net/bus-torino"); return true; case R.id.action_source: openIceweasel("https://code.launchpad.net/bus-torino"); return true; case R.id.action_licence: openIceweasel("http://www.gnu.org/licenses/gpl-3.0.html"); return true; case R.id.action_author: openIceweasel("http://boz.reyboz.it?lovebusto"); return true; } return super.onOptionsItemSelected(item); } /** * OK this is pure shit * * @param v View clicked */ public void onSearchClick(View v) { if (searchMode == SEARCH_BY_ID) { String busStopID = busStopSearchByIDEditText.getText().toString(); new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } else { // searchMode == SEARCH_BY_NAME String query = busStopSearchByNameEditText.getText().toString(); new asyncWgetBusStopSuggestions(query, stopsDB, StopsFindersByNameRecursionHelper); } } /** * QR scan button clicked * * @param v View QRButton clicked */ public void onQRButtonClick(View v) { IntentIntegrator integrator = new IntentIntegrator(this); integrator.initiateScan(); } /** * Receive the Barcode Scanner Intent * */ public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); Uri uri; try { uri = Uri.parse(scanResult != null ? scanResult.getContents() : null); // this apparently prevents NullPointerException. Somehow. } catch (NullPointerException e) { Toast.makeText(getApplicationContext(), R.string.no_qrcode, Toast.LENGTH_SHORT).show(); return; } String busStopID = getBusStopIDFromUri(uri); busStopSearchByIDEditText.setText(busStopID); new asyncWgetBusStopFromBusStopID(busStopID, ArrivalFetchersRecursionHelper, lastSuccessfullySearchedBusStop); } public void onHideHint(View v) { hideHints(); setOption(OPTION_SHOW_LEGEND, false); } public void onToggleKeyboardLayout(View v) { if (searchMode == SEARCH_BY_NAME) { setSearchModeBusStopID(); if (busStopSearchByIDEditText.requestFocus()) { showKeyboard(); } } else { // searchMode == SEARCH_BY_ID setSearchModeBusStopName(); if (busStopSearchByNameEditText.requestFocus()) { showKeyboard(); } } } ///////////////////////////////// STOPS FINDER BY NAME ///////////////////////////////////////// private class asyncWgetBusStopSuggestions extends AsyncWget { private final String query; private AtomicReference res; private List s; private StopsDB db; public asyncWgetBusStopSuggestions(@Nullable String query, @NonNull StopsDB sdb, @NonNull RecursionHelper r) { super(getApplicationContext(), r); toggleSpinner(true); this.query = query; this.res = new AtomicReference<>(); this.db = sdb; r.reset(); if(query == null || query.length() <= 0) { Toast.makeText(this.c, R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show(); toggleSpinner(false); } else { this.execute(); } } @Override protected boolean tryFetcher(StopsFinderByName f) { // gets opened multiple times, whatever. this.db.openIfNeeded(); this.s = f.FindByName(this.query, this.db, this.res); this.db.closeIfNeeded(); switch (this.res.get()) { case CLIENT_OFFLINE: publishProgress(R.string.network_error); return false; case SERVER_ERROR: if (isConnected()) { publishProgress(R.string.parsing_error); } else { publishProgress(R.string.network_error); } return false; case PARSER_ERROR: default: publishProgress(R.string.internal_error); return false; case QUERY_TOO_SHORT: publishProgress(R.string.query_too_short); return false; case EMPTY_RESULT_SET: publishProgress(R.string.no_bus_stop_have_this_name); return false; case OK: return true; } } @Override protected void onPostExecute(Void useless) { // something really bad happened if(this.isCancelled() || !this.terminated || this.s == null) { toggleSpinner(false); this.onCancelled(); return; } // no results if(this.failedAll) { toggleSpinner(false); // TODO: an error message would be a good idea, here return; } hideKeyboard(); busStopNameTextView.setVisibility(View.GONE); prepareGUIForBusStops(); resultsListView.setAdapter(new StopAdapter(this.c, this.s)); resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { /** * Casting because of Javamerda * @url http://stackoverflow.com/questions/30549485/androids-list-view-parameterized-type-in-adapterview-onitemclicklistener */ Stop busStop = (Stop) parent.getItemAtPosition(position); Intent intent = new Intent(ActivityMain.this, ActivityMain.class); Bundle b = new Bundle(); b.putString("bus-stop-ID", busStop.ID); intent.putExtras(b); startActivity(intent); } }); toggleSpinner(false); } @Override protected void onCancelled() { toggleSpinner(false); } } ///////////////////////////////// ARRIVALS FETCHER ///////////////////////////////////////////// private class asyncWgetBusStopFromBusStopID extends AsyncWget { private final String stopID; private AtomicReference res; private Palina p; /** * Begins its life as a copy of lastSuccessfullySearchedBusStop, ends as null if it needs * replacing or stays the same if it stayed the same */ private Stop lastSearchedBusStop; asyncWgetBusStopFromBusStopID(@Nullable String stopID, @NonNull RecursionHelper r, @Nullable Stop lastSearchedBusStop) { super(getApplicationContext(), r); toggleSpinner(true); this.stopID = stopID; this.lastSearchedBusStop = lastSearchedBusStop; this.res = new AtomicReference<>(); if(stopID == null || stopID.length() <= 0) { // we're still in UI thread, no need to mess with Progress Toast.makeText(this.c, R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); toggleSpinner(false); } else { this.execute(); } } @Override protected boolean tryFetcher(ArrivalsFetcher f) { this.p = f.ReadArrivalTimesAll(this.stopID, this.res); switch(this.res.get()) { case CLIENT_OFFLINE: publishProgress(R.string.network_error); return false; case SERVER_ERROR: if(isConnected()) { publishProgress(R.string.parsing_error); } else { publishProgress(R.string.network_error); } return false; case QUERY_TOO_SHORT: // should never happen here, but to err on the side of caution... publishProgress(R.string.query_too_short); return false; case PARSER_ERROR: default: // there are no other cases but Android Studio is still complaining... publishProgress(R.string.internal_error); return false; case EMPTY_RESULT_SET: publishProgress(R.string.no_passages); return false; case OK: // WARNING: lots of branches ahead. // did we search for anything? if(this.lastSearchedBusStop != null) { // different stop? if(!this.lastSearchedBusStop.ID.equals(p.ID)) { // remove it, get new name this.lastSearchedBusStop = null; getNameOrGetRekt(); } else { // searched and it's the same String sn = lastSearchedBusStop.getStopDisplayName(); if(sn == null) { // something really bad happened, start from scratch this.lastSearchedBusStop = null; getNameOrGetRekt(); } else { // "merge" Stop over Palina and we're good to go this.p.mergeNameFrom(lastSearchedBusStop); } } } else { // not searched yet getNameOrGetRekt(); } return true; } } /** * Run this in a background thread.
* Sets a stop name for this.p, guaranteed not to be null! */ private void getNameOrGetRekt() { String nameMaybe; // TODO: search favorites, get (user)name if set, set what's needed, return // does it already have a name (for fetchers that support it)? nameMaybe = this.p.getStopDisplayName(); if(nameMaybe != null && nameMaybe.length() > 0) { return; } // let's try StopsDB StopsDB db = new StopsDB(this.c); db.openIfNeeded(); nameMaybe = db.getNameFromID(this.p.ID); db.closeIfNeeded(); if(nameMaybe != null && nameMaybe.length() > 0) { this.p.setStopName(nameMaybe); return; } // no name to be found anywhere, don't bother searching it next time this.p.setStopName(""); } @Override protected void onPostExecute(Void useless) { // something really bad happened if(this.isCancelled() || !this.terminated || this.p == null) { toggleSpinner(false); this.onCancelled(); return; } // no results if(this.failedAll) { toggleSpinner(false); // TODO: an error message would be a good idea, here return; } hideKeyboard(); if(this.lastSearchedBusStop == null) { // did we gather any new information about this Stop? Then update it (casting from Palina) lastSuccessfullySearchedBusStop = this.p; } String displayName = p.getStopDisplayName(); String displayStuff; if (displayName != null && displayName.length() > 0) { displayStuff = p.ID.concat(" - ").concat(displayName); } else { displayStuff = p.ID; } busStopNameTextView.setText(String.format( getString(R.string.passages), displayStuff)); // Shows hints if (getOption(OPTION_SHOW_LEGEND, true)) { showHints(); } //else { // hideHints(); //} prepareGUIForBusLines(); resultsListView.setAdapter(new PalinaAdapter(this.c, p)); resultsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { String routeName; Route r = (Route) parent.getItemAtPosition(position); routeName = FiveTNormalizer.routeInternalToDisplay(r.name); if (routeName == null) { routeName = r.name; } if (r.destinazione == null || r.destinazione.length() == 0) { Toast.makeText(getApplicationContext(), getString(R.string.route_towards_unknown, routeName), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), getString(R.string.route_towards_destination, routeName, r.destinazione), Toast.LENGTH_SHORT).show(); } } }); toggleSpinner(false); } @Override protected void onCancelled() { toggleSpinner(false); } } ///////////////////////////////// OTHER STUFF ////////////////////////////////////////////////// private boolean isConnected() { ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } public void addInFavorites(View v) { boolean result; if(lastSuccessfullySearchedBusStop != null) { // TODO: move to background thread SQLiteDatabase db = userDB.getWritableDatabase(); result = UserDB.addOrUpdateStop(lastSuccessfullySearchedBusStop, db); db.close(); if(result) { Toast.makeText(getApplicationContext(), R.string.added_in_favorites, Toast.LENGTH_SHORT).show(); } else { // TODO: error message - Toast.makeText(getApplicationContext(), "NON VA, DANNAZIONE!", Toast.LENGTH_SHORT).show(); + Toast.makeText(getApplicationContext(), R.string.cant_add_to_favorites, Toast.LENGTH_SHORT).show(); } } } // TODO: try to move these 2 methods to a separate class private void setOption(String optionName, boolean value) { SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); editor.putBoolean(optionName, value); editor.commit(); } private boolean getOption(String optionName, boolean optDefault) { SharedPreferences preferences = getPreferences(MODE_PRIVATE); return preferences.getBoolean(optionName, optDefault); } ////////////////////////////////////// GUI HELPERS ///////////////////////////////////////////// private void showKeyboard() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); View view = searchMode == SEARCH_BY_ID ? busStopSearchByIDEditText : busStopSearchByNameEditText; imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); } private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) .hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } private void setSearchModeBusStopID() { searchMode = SEARCH_BY_ID; busStopSearchByNameEditText.setVisibility(View.GONE); busStopSearchByNameEditText.setText(""); busStopSearchByIDEditText.setVisibility(View.VISIBLE); floatingActionButton.setImageResource(R.drawable.alphabetical); } private void setSearchModeBusStopName() { searchMode = SEARCH_BY_NAME; busStopSearchByIDEditText.setVisibility(View.GONE); busStopSearchByIDEditText.setText(""); busStopSearchByNameEditText.setVisibility(View.VISIBLE); floatingActionButton.setImageResource(R.drawable.numeric); } /** * Having that cursor at the left of the edit text makes me cancer. * @param busStopID bus stop ID */ private void setBusStopSearchByIDEditText(String busStopID) { busStopSearchByIDEditText.setText(busStopID); busStopSearchByIDEditText.setSelection(busStopID.length()); } private void showHints() { howDoesItWorkTextView.setVisibility(View.VISIBLE); hideHintButton.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(false); } private void hideHints() { howDoesItWorkTextView.setVisibility(View.GONE); hideHintButton.setVisibility(View.GONE); actionHelpMenuItem.setVisible(true); } private void toggleSpinner(boolean enable) { if (enable) { //already set by the RefreshListener when needed //swipeRefreshLayout.setRefreshing(true); progressBar.setVisibility(View.VISIBLE); } else { swipeRefreshLayout.setRefreshing(false); progressBar.setVisibility(View.GONE); } } private void prepareGUIForBusLines() { busStopNameTextView.setVisibility(View.VISIBLE); busStopNameTextView.setClickable(true); swipeRefreshLayout.setEnabled(true); swipeRefreshLayout.setVisibility(View.VISIBLE); resultsListView.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(true); } private void prepareGUIForBusStops() { busStopNameTextView.setText(getString(R.string.results)); busStopNameTextView.setClickable(false); busStopNameTextView.setVisibility(View.VISIBLE); swipeRefreshLayout.setEnabled(false); swipeRefreshLayout.setVisibility(View.VISIBLE); resultsListView.setVisibility(View.VISIBLE); actionHelpMenuItem.setVisible(false); } /** * Open an URL in the default browser. * * @param url URL */ public void openIceweasel(String url) { Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent1); } ///////////////////// INTENT HELPER //////////////////////////////////////////////////////////// /** * Try to extract the bus stop ID from a URi * * @param uri The URL * @return bus stop ID or null */ public static String getBusStopIDFromUri(Uri uri) { String busStopID; switch (uri.getHost()) { case "m.gtt.to.it": // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 busStopID = uri.getQueryParameter("n"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?n from: " + uri); } break; case "www.gtt.to.it": case "gtt.to.it": // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 busStopID = uri.getQueryParameter("palina"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?palina from: " + uri); } break; default: Log.e("ActivityMain", "Unexpected intent URL: " + uri); busStopID = null; } return busStopID; } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/backend/networkTools.java b/src/it/reyboz/bustorino/backend/networkTools.java index 59fa3b6..1cc552d 100644 --- a/src/it/reyboz/bustorino/backend/networkTools.java +++ b/src/it/reyboz/bustorino/backend/networkTools.java @@ -1,126 +1,126 @@ /* BusTO - Arrival times for Turin public transports. Copyright (C) 2014 Valerio Bozzolan This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.support.annotation.Nullable; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Scanner; import java.util.concurrent.atomic.AtomicReference; public abstract class networkTools { static String getDOM(final URL url, final AtomicReference res) { //Log.d("asyncwget", "Catching URL in background: " + uri[0]); HttpURLConnection urlConnection; StringBuilder result = null; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { - res.set(Fetcher.result.CLIENT_OFFLINE); + res.set(Fetcher.result.SERVER_ERROR); return null; } try { InputStream in = new BufferedInputStream( urlConnection.getInputStream()); BufferedReader reader = new BufferedReader( new InputStreamReader(in)); result = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { result.append(line); } } catch (Exception e) { //Log.e("asyncwget", e.getMessage()); } finally { if (urlConnection != null) { urlConnection.disconnect(); } } if (result == null) { - res.set(Fetcher.result.PARSER_ERROR); + res.set(Fetcher.result.SERVER_ERROR); return null; } - res.set(Fetcher.result.SERVER_ERROR); // will be set to "OK" later, this is a safety net in case StringBuilder returns null, the website returns an HTTP 204 or something like that. + res.set(Fetcher.result.PARSER_ERROR); // will be set to "OK" later, this is a safety net in case StringBuilder returns null, the website returns an HTTP 204 or something like that. return result.toString(); } @Nullable static String queryURL(URL url, AtomicReference res) { HttpURLConnection urlConnection; InputStream in; String s; try { urlConnection = (HttpURLConnection) url.openConnection(); } catch(IOException e) { - res.set(Fetcher.result.SERVER_ERROR); // TODO: can we assume this is CLIENT_OFFLINE? + res.set(Fetcher.result.SERVER_ERROR); // even when offline, urlConnection works fine. WHY. return null; } // TODO: make this configurable? urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(10000); - res.set(Fetcher.result.PARSER_ERROR); // will be set to OK later + res.set(Fetcher.result.SERVER_ERROR); // will be set to OK later try { in = urlConnection.getInputStream(); } catch (Exception e) { return null; } s = streamToString(in); try { in.close(); } catch(Exception ignored) {} try { urlConnection.disconnect(); } catch(Exception ignored) {} if(s.length() == 0) { return null; } else { return s; } } // https://stackoverflow.com/a/5445161 static String streamToString(InputStream is) { Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } static int failsafeParseInt(String str) { try { return Integer.parseInt(str); } catch(NumberFormatException e) { return 0; } } } diff --git a/src/it/reyboz/bustorino/middleware/AsyncWget.java b/src/it/reyboz/bustorino/middleware/AsyncWget.java index bbb82bd..e57ace9 100644 --- a/src/it/reyboz/bustorino/middleware/AsyncWget.java +++ b/src/it/reyboz/bustorino/middleware/AsyncWget.java @@ -1,99 +1,97 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.middleware; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; -import it.reyboz.bustorino.R; - /** * Call this.execute() right after the constructor. Or in the constructor itself, if you're * overriding it (also call super() constructor in that case). */ public abstract class AsyncWget extends AsyncTask { protected RecursionHelper r; /** * True: every fetcher failed in some way * False: at least one fetcher succeeded and loop was terminated */ protected boolean failedAll = false; /** * True: recursion\loop has terminated naturally * False: task has been cancelled */ protected boolean terminated = false; protected final Context c; /** * Try every fetcher until you get something usable.
*/ public AsyncWget(Context c, RecursionHelper r) { r.reset(); this.r = r; this.c = c; } @Override protected Void doInBackground(Void... useless) { while(r.valid()) { if(this.isCancelled()) { return null; } if(this.tryFetcher(r.getAndMoveForward())) { this.terminated = true; break; } } // everything failed? if(!this.terminated) { // well, natural termination was reached, so set "terminated" to true... this.terminated = true; this.failedAll = true; } return null; } /** * Override this! * * @param f fetcher * @return true if succeeded and want to terminate, false if failed and want to try next fetcher */ abstract protected boolean tryFetcher(FetcherKind f); /** - * Shows a toast. + * Shows a toast. Or more than one toast. * * @param toastz resources from R, containing a message */ @Override protected void onProgressUpdate(Integer... toastz) { for(int i: toastz) { Toast.makeText(this.c, i, Toast.LENGTH_SHORT).show(); } } } \ No newline at end of file diff --git a/src/it/reyboz/bustorino/middleware/UserDB.java b/src/it/reyboz/bustorino/middleware/UserDB.java index 4e774d0..691f0cb 100644 --- a/src/it/reyboz/bustorino/middleware/UserDB.java +++ b/src/it/reyboz/bustorino/middleware/UserDB.java @@ -1,235 +1,244 @@ /* BusTO ("backend" components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.middleware; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; import android.util.Log; import java.util.ArrayList; import java.util.List; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.backend.StopsDBInterface; public class UserDB extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "user.db"; private final Context c; // needed during upgrade private static String[] usernameColumnNameAsArray = {"username"}; private static String[] getFavoritesColumnNamesAsArray = {"ID", "username"}; public UserDB(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); this.c = context; } @Override public void onCreate(SQLiteDatabase db) { // exception intentionally left unhandled db.execSQL("CREATE TABLE favorites (ID TEXT PRIMARY KEY NOT NULL, username TEXT)"); //if(OldDB.doesItExist(this.c)) { upgradeFromOldDatabase(); //} } private void upgradeFromOldDatabase() { OldDB old; try { old = new OldDB(this.c); } catch(IllegalStateException e) { // can't create database => it doesn't really exist, no matter what doesItExist() says return; } int ver = old.getOldVersion(); /* version 8 was the previous version, OldDB "upgrades" itself to 1337 but unless the app * has crashed midway through the upgrade and the user is retrying, that should never show * up here. And if it does, try to recover favorites anyway. * Versions < 8 already got dropped during the update process, so let's do the same. */ if(ver >= 8) { ArrayList ID = new ArrayList<>(); ArrayList name = new ArrayList<>(); ArrayList username = new ArrayList<>(); int len; int len2; try { Cursor c = old.getReadableDatabase().rawQuery("SELECT busstop_ID, busstop_name, busstop_username FROM busstop WHERE busstop_isfavorite = 1 ORDER BY busstop_name ASC", new String[] {}); int zero = c.getColumnIndex("busstop_ID"); int one = c.getColumnIndex("busstop_name"); int two = c.getColumnIndex("busstop_username"); while(c.moveToNext()) { ID.add(c.getString(zero)); if(c.getString(one).length() <= 0) { name.add(null); } else { name.add(c.getString(one)); } if(c.getString(two).length() <= 0) { username.add(null); } else { username.add(c.getString(two)); } } c.close(); old.close(); } catch(Exception ignored) { // there's no hope, go ahead and nuke old database. } len = ID.size(); len2 = name.size(); if(len2 < len) { len = len2; } len2 = username.size(); if(len2 < len) { len = len2; } if (len > 0) { SQLiteDatabase newdb = this.getWritableDatabase(); newdb.beginTransaction(); try { ContentValues cv; for (int i = 0; i < len; i++) { cv = new ContentValues(); cv.put("username", username.get(i)); cv.put("ID", ID.get(i)); newdb.insert("favorites", null, cv); } newdb.setTransactionSuccessful(); } finally { newdb.endTransaction(); } newdb.close(); } } if(!OldDB.destroy(this.c)) { // TODO: notify user somehow? Log.e("UserDB", "Failed to delete old database, you should really uninstall and reinstall the app. Unfortunately I have no way to tell the user."); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // nothing to do yet } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // nothing to do yet } /** * Gets stop name set by the user. * * @param db readable database * @param stopID stop ID * @return name set by user, or null if not set\not found */ public static String getStopUserName(SQLiteDatabase db, String stopID) { String username = null; try { Cursor c = db.query("favorites", usernameColumnNameAsArray, "ID = ?", new String[] {stopID}, null, null, null, null); if(c.moveToNext()) { username = c.getString(c.getColumnIndex("username")); } c.close(); } catch(SQLiteException ignored) {} return username; } public static List getFavorites(SQLiteDatabase db, StopsDBInterface dbi) { List l = new ArrayList<>(); Stop s; String stopID, stopUserName; try { Cursor c = db.query("favorites", getFavoritesColumnNamesAsArray, null, null, null, null, null, null); int colID = c.getColumnIndex("ID"); int colUser = c.getColumnIndex("username"); while(c.moveToNext()) { stopUserName = c.getString(colUser); stopID = c.getString(colID); s = dbi.getAllFromID(stopID); if(s == null) { // can't find it in database l.add(new Stop(stopUserName, stopID, null, null, null)); } else { // setStopName() already does sanity checks s.setStopUserName(stopUserName); l.add(s); } } c.close(); } catch(SQLiteException ignored) {} return l; } public static boolean addOrUpdateStop(Stop s, SQLiteDatabase db) { ContentValues cv = new ContentValues(); long result = -1; cv.put("ID", s.ID); cv.put("username", getStopUserName(db, s.ID)); try { result = db.insert("favorites", null, cv); } catch (SQLiteException ignored) {} // Android Studio suggested this unreadable replacement: return true if insert succeeded (!= -1), or try to update and return return (result != -1) || updateStop(s, db); } public static boolean updateStop(Stop s, SQLiteDatabase db) { try { ContentValues cv = new ContentValues(); cv.put("username", s.getStopUserName()); db.update("favorites", cv, "ID = ?", new String[]{s.ID}); return true; } catch(SQLiteException e) { return false; } } + + public static boolean deleteStop(Stop s, SQLiteDatabase db) { + try { + db.delete("favorites", "ID = ?", new String[]{s.ID}); + return true; + } catch(SQLiteException e) { + return false; + } + } }