diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 041d6f1..c7c5cbe 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,88 +1,88 @@ + android:versionCode="21" + android:versionName="1.8.6"> diff --git a/assets/busto.sqlite b/assets/busto.sqlite deleted file mode 100644 index 18e073a..0000000 Binary files a/assets/busto.sqlite and /dev/null differ diff --git a/assets/databases/stops.sqlite b/assets/databases/stops.sqlite new file mode 100644 index 0000000..2164ba9 Binary files /dev/null and b/assets/databases/stops.sqlite differ diff --git a/build.gradle b/build.gradle index b8530f8..b371216 100644 --- a/build.gradle +++ b/build.gradle @@ -1,51 +1,52 @@ buildscript { repositories { mavenCentral() - jcenter() + jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.2.1' } } apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion '23.0.3' compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } sourceSets { main { manifest.srcFile 'AndroidManifest.xml' java.srcDirs = ['src'] resources.srcDirs = ['src'] aidl.srcDirs = ['src'] renderscript.srcDirs = ['src'] res.srcDirs = ['res'] assets.srcDirs = ['assets'] } } lintOptions { abortOnError false } repositories { mavenCentral() mavenLocal() } dependencies { compile 'com.android.support:support-v4:23.4.0' compile 'com.android.support:appcompat-v7:23.4.0' compile 'com.melnykov:floatingactionbutton:1.2.0' compile 'org.jsoup:jsoup:1.7.3' + compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' } } dependencies { } diff --git a/src/it/reyboz/bustorino/middleware/StopsDB.java b/src/it/reyboz/bustorino/middleware/StopsDB.java index f69d9f5..9262bc8 100644 --- a/src/it/reyboz/bustorino/middleware/StopsDB.java +++ b/src/it/reyboz/bustorino/middleware/StopsDB.java @@ -1,295 +1,195 @@ /* 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 com.readystatesoftware.sqliteasset.SQLiteAssetHelper; + 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"; + +public class StopsDB extends SQLiteAssetHelper implements StopsDBInterface { + private static String QUERY_TABLE_stops = "stops"; + private static String QUERY_WHERE_ID = "ID = ?"; + private static String[] QUERY_COLUMN_name = {"name"}; + private static String[] QUERY_COLUMN_location = {"location"}; + private static String[] QUERY_COLUMN_route = {"route"}; + private static String[] QUERY_COLUMN_everything = {"name", "location", "type", "lat", "lon"}; + + private static String DB_NAME = "stops.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(); - } + // WARNING: do not remove the following line, do not save anything in this database, it will be overwritten on every update! + setForcedUpgrade(); } /** * 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); - } + this.db = getReadableDatabase(); 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); + result = this.db.query("routemap", QUERY_COLUMN_route, "stop = ?", uselessArray, null, null, null); } 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); + result = this.db.query(QUERY_TABLE_stops, QUERY_COLUMN_name, QUERY_WHERE_ID, uselessArray, null, null, null); } 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"); + result = this.db.query(QUERY_TABLE_stops, QUERY_COLUMN_everything, QUERY_WHERE_ID, new String[] {stopID}, null, null, null); int colName = result.getColumnIndex("name"); int colLocation = result.getColumnIndex("location"); int colType = result.getColumnIndex("type"); int colLat = 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; } 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; } }