diff --git a/src/it/reyboz/bustorino/backend/Stop.java b/src/it/reyboz/bustorino/backend/Stop.java index a3e8277..c68ef2c 100644 --- a/src/it/reyboz/bustorino/backend/Stop.java +++ b/src/it/reyboz/bustorino/backend/Stop.java @@ -1,137 +1,184 @@ /* 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.backend; import android.support.annotation.NonNull; import android.support.annotation.Nullable; +import java.net.URLEncoder; import java.util.List; +import java.util.Locale; public class Stop implements Comparable { // remove "final" in case you need to set these from outside the parser\scrapers\fetchers public final @NonNull String ID; private @Nullable String name; public final @Nullable String location; public final @Nullable Route.Type type; private final @Nullable List routesThatStopHere; + private final @Nullable Double lat; + private final @Nullable Double lon; // leave this non-final private @Nullable String routesThatStopHereString = null; /** * Hey, look, method overloading! */ public Stop(final @Nullable String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List routesThatStopHere) { this.ID = ID; this.name = name; this.location = (location != null && location.length() == 0) ? null : location; this.type = type; this.routesThatStopHere = routesThatStopHere; + this.lat = null; + this.lon = null; } /** * Hey, look, method overloading! */ public Stop(final @NonNull String ID) { this.ID = ID; this.name = null; this.location = null; this.type = null; this.routesThatStopHere = null; + this.lat = null; + this.lon = null; + } + + /** + * Constructor that sets EVERYTHING. + */ + public Stop(@NonNull String ID, @Nullable String name, @Nullable String location, @Nullable Route.Type type, @Nullable List routesThatStopHere, @Nullable Double lat, @Nullable Double lon) { + this.ID = ID; + this.name = name; + this.location = location; + this.type = type; + this.routesThatStopHere = routesThatStopHere; + this.lat = lat; + this.lon = lon; } public @Nullable String routesThatStopHereToString() { // M E M O I Z A T I O N if(this.routesThatStopHereString != null) { return this.routesThatStopHereString; } // no string yet? build it! return buildString(); } private @Nullable String buildString() { // no routes => no string if(this.routesThatStopHere == null || this.routesThatStopHere.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); int i, lenMinusOne = routesThatStopHere.size() - 1; for (i = 0; i < lenMinusOne; i++) { sb.append(routesThatStopHere.get(i)).append(", "); } // last one: sb.append(routesThatStopHere.get(i)); this.routesThatStopHereString = sb.toString(); return this.routesThatStopHereString; } @Override public int compareTo(@NonNull Stop other) { int res; int thisAsInt = networkTools.failsafeParseInt(this.ID); int otherAsInt = networkTools.failsafeParseInt(other.ID); // numeric stop IDs if(thisAsInt != 0 && otherAsInt != 0) { return thisAsInt - otherAsInt; } else { // non-numeric res = this.ID.compareTo(other.ID); if (res != 0) { return res; } } // try with name, then if(this.name != null && other.name != null) { res = this.name.compareTo(other.name); } // and give up return res; } /** * Sets a name. * * @param name stop name as string (not null) */ public final void setStopName(@NonNull String name) { this.name = name; } /** * Returns stop name.
* - empty string means "already searched everywhere, can't find it"
* - null means "didn't search, yet. Maybe you should try."
* - string means "here's the name.", obviously.
* * @return string if known, null if still unknown */ public final @Nullable String getStopName() { return this.name; } + + public final @Nullable String getGeoURL() { + if(this.lat == null || this.lon == null) { + return null; + } + + // Android documentation suggests US for machine readable output (use dot as decimal separator) + return String.format(Locale.US, "geo:%f,%f", this.lon, this.lat); + } + + public final @Nullable String getGeoURLWithAddress() { + String url = getGeoURL(); + + if(url == null) { + return null; + } + + if(this.location != null) { + try { + String addThis = "?q=".concat(URLEncoder.encode(this.location, "utf-8")); + return url.concat(addThis); + } catch (Exception ignored) {} + } + + return url; + } } diff --git a/src/it/reyboz/bustorino/backend/StopsDBInterface.java b/src/it/reyboz/bustorino/backend/StopsDBInterface.java index eb76e7d..2653eb6 100644 --- a/src/it/reyboz/bustorino/backend/StopsDBInterface.java +++ b/src/it/reyboz/bustorino/backend/StopsDBInterface.java @@ -1,44 +1,56 @@ /* 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.backend; +import android.support.annotation.NonNull; +import android.support.annotation.Nullable; + import java.util.List; /** * No reference to SQLite whatsoever, here. * Don't get StopsDB inside the backend, use this interface instead. */ public interface StopsDBInterface { /** * Given a stop ID, get which routes stop there (as strings, there's no sane way to determine their destination\terminus from the database) * * @param stopID stop ID - * @return list of routes or null if none + * @return list of routes or null if none (or database closed) */ - List getRoutesByStop(String stopID); + @Nullable List getRoutesByStop(@NonNull String stopID); /** * Stop ID goes in, stop name comes out. * GTT API doesn't return this useful piece of information, so here we go, get it from the database! * * @param stopID stop ID, in normalized form - * @return stop name or null if not found + * @return stop name or null if not found (or database closed) + */ + @Nullable String getNameFromID(@NonNull String stopID); + + /** + * SELECT * FROM ...
+ * (No, it doesn't really use *) + * + * @param stopID stop ID + * @return Stop with every available piece of data set or null if not found (or database closed) */ - String getNameFromID(String stopID); + @Nullable Stop getAllFromID(@NonNull String stopID); } diff --git a/src/it/reyboz/bustorino/middleware/StopsDB.java b/src/it/reyboz/bustorino/middleware/StopsDB.java index be51fef..94b713c 100644 --- a/src/it/reyboz/bustorino/middleware/StopsDB.java +++ b/src/it/reyboz/bustorino/middleware/StopsDB.java @@ -1,238 +1,290 @@ /* 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(String stopID) { + public List getRoutesByStop(@NonNull String stopID) { String[] uselessArray = {stopID}; int count; Cursor result; - if(db == null) { + if(this.db == null) { return null; } try { - result = db.rawQuery("SELECT route FROM routemap WHERE stop = ?", uselessArray); + 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(String stopID) { + public String getNameFromID(@NonNull String stopID) { String[] uselessArray = {stopID}; int count; String name; Cursor result; - if(db == null) { + if(this.db == null) { return null; } try { - result = db.rawQuery("SELECT name FROM stops WHERE ID = ?", uselessArray); + 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"); + + 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), result.getString(colLocation), 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 12a49b5..4f563b2 100644 --- a/src/it/reyboz/bustorino/middleware/UserDB.java +++ b/src/it/reyboz/bustorino/middleware/UserDB.java @@ -1,217 +1,235 @@ /* 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", "standardname", "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, standardname TEXT, username TEXT)"); + db.execSQL("CREATE TABLE favorites (ID TEXT PRIMARY KEY NOT NULL, username TEXT)"); - if(OldDB.doesItExist(this.c)) { - upgradeFromOldDatabase(); - } + //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++) { - newdb.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, ?)", new String[]{ID.get(i), name.get(i), username.get(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) { + 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 colStandard = c.getColumnIndex("standardname"); int colUser = c.getColumnIndex("username"); - if(c.moveToNext()) { - String name = c.getString(colUser); - if(name == null || name.length() <= 0) { - l.add(new Stop(c.getString(colStandard), c.getString(colID), null, null, null)); + 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 { - l.add(new Stop(name, c.getString(colID), null, null, null)); + if(stopUserName != null && stopUserName.length() > 0) { + s.setStopName(stopUserName); + } + l.add(s); } } c.close(); } catch(SQLiteException ignored) {} return l; } public boolean addOrUpdate(Stop s, SQLiteDatabase db) { - String username; - - username = getStopUserName(db, s.ID); + ContentValues cv = new ContentValues(); + long result = -1; + cv.put("ID", s.ID); + cv.put("username", getStopUserName(db, s.ID)); try { - if(username == null) { - db.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, null)", new String[] {s.ID, s.getStopName()}).close(); - } else { - db.rawQuery("INSERT INTO favorites(ID, standardname, username) VALUES (?, ?, ?)", new String[] {s.ID, s.getStopName(), username}).close(); + result = db.insert("favorites", null, cv); + } catch(SQLiteException ignored) {} + + if(result == -1) { + try { + cv = new ContentValues(); + db.update("favorites", cv, "ID = ?", new String[]{s.ID}); + } catch(SQLiteException e) { + return false; } - // UPSERT. - // standardname is the only field that could have changed... - db.rawQuery("UPDATE favorites SET standardname = ? WHERE ID = ?", new String[]{s.getStopName(), s.ID}).close(); - } catch(SQLiteException e) { - return false; + return true; } return true; } }