diff --git a/src/it/reyboz/bustorino/ActivityFavorites.java b/src/it/reyboz/bustorino/ActivityFavorites.java
index 16b5c6f..4690c61 100644
--- a/src/it/reyboz/bustorino/ActivityFavorites.java
+++ b/src/it/reyboz/bustorino/ActivityFavorites.java
@@ -1,241 +1,241 @@
/*
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);
createFavoriteList();
return true;
case R.id.action_rename_bus_stop_username:
showBusStopUsernameInputDialog(busStop);
return true;
default:
return super.onContextItemSelected(item);
}
}
void createFavoriteList() {
new AsyncGetFavorites(getApplicationContext(), this.userDB).execute();
}
private class BusStopUsernameOnClickListener implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}
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.getStopName());
bus_stop_name.setHint(busStop.getStopName()); // TODO: store default name somewhere just for this purpose?
builder.setTitle(getString(R.string.dialog_rename_bus_stop_username_title));
builder.setView(renameDialogLayout);
builder.setPositiveButton(getString(android.R.string.ok), new BusStopUsernameOnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String busStopUsername = bus_stop_name.getText().toString();
if (busStopUsername.length() == 0) {
// is this a closure?
// TODO: do something.
busStop.setStopName("DELETED TEST TEST");
} else {
busStop.setStopName(busStopUsername);
}
- UserDB.addOrUpdate(busStop, userDB);
+ 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 BusStopUsernameOnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO: do something.
busStop.setStopName("DEFAULT TEST TEST");
- UserDB.addOrUpdate(busStop, userDB);
+ 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);
}
// 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();
b.putString("bus-stop-ID", busStop.ID);
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 8e89000..da1a9c2 100644
--- a/src/it/reyboz/bustorino/ActivityMain.java
+++ b/src/it/reyboz/bustorino/ActivityMain.java
@@ -1,845 +1,845 @@
/*
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;
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");
/**
* 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();
}
} else {
// If you are here an intent has worked successfully
setBusStopSearchByIDEditText(busStopID);
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.getStopName();
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.setStopName(sn);
}
}
} 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.getStopName();
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.getStopName();
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.addOrUpdate(lastSuccessfullySearchedBusStop, db);
+ 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();
}
}
}
// 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/middleware/UserDB.java b/src/it/reyboz/bustorino/middleware/UserDB.java
index a3d7102..dfb3e46 100644
--- a/src/it/reyboz/bustorino/middleware/UserDB.java
+++ b/src/it/reyboz/bustorino/middleware/UserDB.java
@@ -1,236 +1,237 @@
/*
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()) {
String userName = c.getString(colUser);
stopID = c.getString(colID);
stopUserName = c.getString(colUser);
s = dbi.getAllFromID(stopID);
if(s == null) {
// can't find it in database
l.add(new Stop(userName, stopID, null, null, null));
} else {
if(stopUserName != null && stopUserName.length() > 0) {
s.setStopName(stopUserName);
}
l.add(s);
}
}
c.close();
} catch(SQLiteException ignored) {}
return l;
}
- public static boolean addOrUpdate(Stop s, SQLiteDatabase db) {
+ 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) {}
+ } catch (SQLiteException ignored) {}
- if(result == -1) {
- try {
- cv = new ContentValues();
- cv.put("username", getStopUserName(db, s.ID));
- db.update("favorites", cv, "ID = ?", new String[]{s.ID});
- } catch(SQLiteException e) {
- return false;
- }
+ // 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.getStopName());
+ db.update("favorites", cv, "ID = ?", new String[]{s.ID});
return true;
+ } catch(SQLiteException e) {
+ return false;
}
-
- return true;
}
}