diff --git a/src/it/reyboz/bustorino/ActivityFavorites.java b/src/it/reyboz/bustorino/ActivityFavorites.java
index 70f109b..ccbe3b6 100644
--- a/src/it/reyboz/bustorino/ActivityFavorites.java
+++ b/src/it/reyboz/bustorino/ActivityFavorites.java
@@ -1,253 +1,254 @@
/*
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:
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.FLAG_ACTIVITY_CLEAR_TASK isn't supported in API < 11 and we're targeting API 7...
intent.setFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
startActivity(intent);
finish();
}
});
registerForContextMenu(favoriteListView);
}
}
}
diff --git a/src/it/reyboz/bustorino/middleware/StopAdapter.java b/src/it/reyboz/bustorino/middleware/StopAdapter.java
index 31aa18f..536e0c6 100644
--- a/src/it/reyboz/bustorino/middleware/StopAdapter.java
+++ b/src/it/reyboz/bustorino/middleware/StopAdapter.java
@@ -1,114 +1,114 @@
/*
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.backend.Stop;
/**
* @see PalinaAdapter
*/
public class StopAdapter extends ArrayAdapter {
private LayoutInflater li;
private static int row_layout = R.layout.entry_bus_stop;
private static final int busIcon = R.drawable.bus;
private static final int trainIcon = R.drawable.subway;
private static final int tramIcon = R.drawable.tram;
private static final int cityIcon = R.drawable.city;
static class ViewHolder {
TextView busStopIDTextView;
TextView busStopNameTextView;
//TextView busLineVehicleIcon;
TextView busStopLinesTextView;
TextView busStopLocaLityTextView;
}
public StopAdapter(Context context, List stops) {
super(context, row_layout, stops);
li = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView == null) {
convertView = li.inflate(row_layout, null);
vh = new ViewHolder();
vh.busStopIDTextView = (TextView) convertView.findViewById(R.id.busStopID);
vh.busStopNameTextView = (TextView) convertView.findViewById(R.id.busStopName);
vh.busStopLinesTextView = (TextView) convertView.findViewById(R.id.routesThatStopHere);
vh.busStopLocaLityTextView = (TextView) convertView.findViewById(R.id.busStopLocality);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
Stop stop = getItem(position);
vh.busStopIDTextView.setText(stop.ID);
- // NOTE: intentionally ignoring stop username: if it's in the favorites, why are you searching for it?
+ // NOTE: intentionally ignoring stop username in search results: if it's in the favorites, why are you searching for it?
vh.busStopNameTextView.setText(stop.getStopDisplayName());
String whatStopsHere = stop.routesThatStopHereToString();
if(whatStopsHere == null) {
vh.busStopLinesTextView.setVisibility(View.GONE);
} else {
vh.busStopLinesTextView.setText(whatStopsHere);
}
if(stop.type == null) {
vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0);
} else {
switch(stop.type) {
case BUS:
default:
vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(busIcon, 0, 0, 0);
break;
case METRO:
case RAILWAY:
vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(trainIcon, 0, 0, 0);
break;
case TRAM:
vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(tramIcon, 0, 0, 0);
break;
case LONG_DISTANCE_BUS:
// è l'opposto della città ma va beh, dettagli.
vh.busStopLinesTextView.setCompoundDrawablesWithIntrinsicBounds(cityIcon, 0, 0, 0);
}
}
if (stop.location == null) {
vh.busStopLocaLityTextView.setVisibility(View.GONE);
} else {
vh.busStopLocaLityTextView.setText(stop.location);
}
return convertView;
}
}
diff --git a/src/it/reyboz/bustorino/middleware/StopsDB.java b/src/it/reyboz/bustorino/middleware/StopsDB.java
index 52dab08..f69d9f5 100644
--- a/src/it/reyboz/bustorino/middleware/StopsDB.java
+++ b/src/it/reyboz/bustorino/middleware/StopsDB.java
@@ -1,290 +1,295 @@
/*
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.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import it.reyboz.bustorino.backend.Route;
import it.reyboz.bustorino.backend.Stop;
import it.reyboz.bustorino.backend.StopsDBInterface;
/**
* There's just one single difference between this and SQLiteAssetHelper: this implementation works,
* instead of crashing the app without any error message or exception whatsoever as soon as you try
* to open the database.
*
* @see http://blog.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
*/
public class StopsDB extends SQLiteOpenHelper implements StopsDBInterface {
private final Context c;
private static String DB_NAME = "busto.sqlite";
private static int DB_VERSION = 1;
private final File filename;
private SQLiteDatabase db;
private AtomicInteger openCounter = new AtomicInteger();
public StopsDB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.c = context;
this.filename = new File(this.c.getFilesDir(), DB_NAME);
}
private void createDb() {
//this.getReadableDatabase();
InputStream is;
OutputStream os;
try {
is = c.getAssets().open(DB_NAME);
} catch(IOException e) {
/* in case an upgrade is failing, nuke everything rather than leaving an old database
* in place (should save us lots of headaches related to absurd non-reproducible bugs)
*/
//noinspection ResultOfMethodCallIgnored
filename.delete();
return;
}
try {
os = new FileOutputStream(filename);
} catch(FileNotFoundException e) {
//noinspection ResultOfMethodCallIgnored
filename.delete();
return;
}
byte[] buffer = new byte[1024];
int length;
try {
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
os.flush();
os.close();
is.close();
} catch(IOException e) {
//noinspection ResultOfMethodCallIgnored
filename.delete();
}
}
/**
* Through the magic of an atomic counter, the database gets opened and closed without race
* conditions between threads (HOPEFULLY).
*
* @return database or null if cannot be opened
*/
@Nullable
public synchronized SQLiteDatabase openIfNeeded() {
openCounter.incrementAndGet();
if(this.db == null) {
this.db = openRecursive(false);
}
return this.db;
}
/**
* Making this function recursive is just a pointless exercise in style, since it calls itself exactly once.
*
* @param retrying set to true during recursion
* @return SQLiteDatabase or null
*/
@Nullable
private SQLiteDatabase openRecursive(boolean retrying) {
try {
/* I have no idea why it worked without NO_LOCALIZED_COLLATORS, since it's mandatory
* unless you place some Android-specific metadata tables that aren't that well documented...
* Also, apparently there's no openDatabase() method that takes a File.
*/
return SQLiteDatabase.openDatabase(this.filename.getPath(), null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
} catch(SQLiteException e) {
if(retrying) {
// failed a 2nd time, give up
return null;
} else {
// create it
createDb();
return openRecursive(true);
}
}
}
/**
* Through the magic of an atomic counter, the database gets really closed only when no thread
* is using it anymore (HOPEFULLY).
*/
public synchronized void closeIfNeeded() {
// is anybody still using the database or can we close it?
if(openCounter.decrementAndGet() <= 0) {
if (this.db != null && this.db.isOpen()) {
this.db.close();
}
super.close();
this.db = null;
}
}
@Override
public void onCreate(SQLiteDatabase db) {
// copy database (new install)
createDb();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// destroy old database, replace with new
createDb();
}
@Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// destroy new database, replace with old
createDb();
}
@Override
public List getRoutesByStop(@NonNull String stopID) {
String[] uselessArray = {stopID};
int count;
Cursor result;
if(this.db == null) {
return null;
}
try {
result = this.db.rawQuery("SELECT route FROM routemap WHERE stop = ?", uselessArray);
} catch(SQLiteException e) {
return null;
}
count = result.getCount();
if(count == 0) {
return null;
}
List routes = new ArrayList<>(count);
while(result.moveToNext()) {
routes.add(result.getString(0));
}
result.close();
return routes;
}
@Override
public String getNameFromID(@NonNull String stopID) {
String[] uselessArray = {stopID};
int count;
String name;
Cursor result;
if(this.db == null) {
return null;
}
try {
result = this.db.rawQuery("SELECT name FROM stops WHERE ID = ?", uselessArray);
} catch(SQLiteException e) {
return null;
}
count = result.getCount();
if(count == 0) {
return null;
}
result.moveToNext();
name = result.getString(0);
result.close();
return name;
}
@Override
public Stop getAllFromID(@NonNull String stopID) {
Cursor result;
int count;
Stop s;
if(this.db == null) {
return null;
}
try {
result = this.db.query("stops", new String[] {"name", "location", "type", "lat", "lon"}, "ID = ?", new String[] {stopID}, null, null, null, "1");
int colName = result.getColumnIndex("name");
int colLocation = result.getColumnIndex("location");
int colType = result.getColumnIndex("type");
int colLat = result.getColumnIndex("lat");
- int colLon = result.getColumnIndex("lat");
+ int colLon = result.getColumnIndex("lon");
count = result.getCount();
if(count == 0) {
return null;
}
result.moveToNext();
Route.Type type;
switch(result.getString(colType)) {
case "B":
default:
type = Route.Type.BUS;
break;
case "M":
type = Route.Type.METRO;
break;
case "T":
type = Route.Type.RAILWAY;
break;
}
- s = new Stop(stopID, result.getString(colName), null, result.getString(colLocation), type, getRoutesByStop(stopID), result.getDouble(colLat), result.getDouble(colLon));
+ String locationWhichSometimesIsAnEmptyString = result.getString(colLocation);
+ if(locationWhichSometimesIsAnEmptyString.length() <= 0) {
+ locationWhichSometimesIsAnEmptyString = null;
+ }
+
+ s = new Stop(stopID, result.getString(colName), null, locationWhichSometimesIsAnEmptyString, type, getRoutesByStop(stopID), result.getDouble(colLat), result.getDouble(colLon));
} catch(SQLiteException e) {
return null;
}
result.close();
return s;
}
}
diff --git a/src/it/reyboz/bustorino/middleware/UserDB.java b/src/it/reyboz/bustorino/middleware/UserDB.java
index bf2def9..8c6e97f 100644
--- a/src/it/reyboz/bustorino/middleware/UserDB.java
+++ b/src/it/reyboz/bustorino/middleware/UserDB.java
@@ -1,244 +1,248 @@
/*
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.Collections;
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 static final String TABLE_NAME = "favorites";
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(db);
}
}
private void upgradeFromOldDatabase(SQLiteDatabase newdb) {
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.
*
* Edit: Android runs getOldVersion() then, after a while, onUpgrade(). Just to make it
* more complicated. Workaround added in OldDB.
*/
if(ver >= 8) {
ArrayList ID = new ArrayList<>();
ArrayList username = new ArrayList<>();
int len;
int len2;
try {
Cursor c = old.getReadableDatabase().rawQuery("SELECT busstop_ID, 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_username");
while(c.moveToNext()) {
try {
ID.add(c.getString(zero));
} catch(Exception e) {
// no ID = can't add this
continue;
}
if(c.getString(one) == null || c.getString(one).length() <= 0) {
username.add(null);
} else {
username.add(c.getString(one));
}
}
c.close();
old.close();
} catch(Exception ignored) {
// there's no hope, go ahead and nuke old database.
}
len = ID.size();
len2 = username.size();
if(len2 < len) {
len = len2;
}
if (len > 0) {
try {
Stop stopStopStopStopStop;
for (int i = 0; i < len; i++) {
stopStopStopStopStop = new Stop(ID.get(i));
stopStopStopStopStop.setStopUserName(username.get(i));
addOrUpdateStop(stopStopStopStopStop, newdb);
}
} catch(Exception ignored) {
// partial data is better than no data at all, no transactions here
}
}
}
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(TABLE_NAME, 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(TABLE_NAME, 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) {}
+ // comparison rules are too complicated to let SQLite do this (e.g. it outputs: 3234, 34, 576, 67, 8222) and stop name is in another database
+ Collections.sort(l);
+
return l;
}
public static boolean addOrUpdateStop(Stop s, SQLiteDatabase db) {
ContentValues cv = new ContentValues();
long result = -1;
String un = s.getStopUserName();
cv.put("ID", s.ID);
// is there an username?
if(un == null) {
// no: see if it's in the database
cv.put("username", getStopUserName(db, s.ID));
} else {
// yes: use it
cv.put("username", un);
}
try {
result = db.insert(TABLE_NAME, 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(TABLE_NAME, cv, "ID = ?", new String[]{s.ID});
return true;
} catch(SQLiteException e) {
return false;
}
}
public static boolean deleteStop(Stop s, SQLiteDatabase db) {
try {
db.delete(TABLE_NAME, "ID = ?", new String[]{s.ID});
return true;
} catch(SQLiteException e) {
return false;
}
}
}