diff options
Diffstat (limited to 'main/src/cgeo/geocaching/DataStore.java')
| -rw-r--r-- | main/src/cgeo/geocaching/DataStore.java | 355 |
1 files changed, 182 insertions, 173 deletions
diff --git a/main/src/cgeo/geocaching/DataStore.java b/main/src/cgeo/geocaching/DataStore.java index 32a4b64..bdbb97e 100644 --- a/main/src/cgeo/geocaching/DataStore.java +++ b/main/src/cgeo/geocaching/DataStore.java @@ -16,6 +16,7 @@ import cgeo.geocaching.geopoint.Viewport; import cgeo.geocaching.list.AbstractList; import cgeo.geocaching.list.PseudoList; import cgeo.geocaching.list.StoredList; +import cgeo.geocaching.search.SearchSuggestionCursor; import cgeo.geocaching.settings.Settings; import cgeo.geocaching.ui.dialog.Dialogs; import cgeo.geocaching.utils.FileUtils; @@ -36,7 +37,6 @@ import rx.util.async.Async; import android.app.Activity; import android.app.ProgressDialog; -import android.app.SearchManager; import android.content.ContentValues; import android.content.Context; import android.content.ContextWrapper; @@ -49,7 +49,6 @@ import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; -import android.provider.BaseColumns; import java.io.File; import java.io.FilenameFilter; @@ -57,6 +56,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; @@ -325,7 +325,7 @@ public class DataStore { final DbHelper dbHelper = new DbHelper(new DBContext(CgeoApplication.getInstance())); try { database = dbHelper.getWritableDatabase(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.init: unable to open database for R/W", e); recreateDatabase(dbHelper); } @@ -347,7 +347,7 @@ public class DataStore { } try { database = dbHelper.getWritableDatabase(); - } catch (Exception f) { + } catch (final Exception f) { Log.e("DataStore.init: unable to recreate database and open it for R/W", f); } } @@ -420,14 +420,14 @@ public class DataStore { init(); return true; } - })).subscribe(new Action1<Boolean>() { + })).subscribeOn(Schedulers.io()).subscribe(new Action1<Boolean>() { @Override public void call(final Boolean success) { dialog.dismiss(); final String message = success ? fromActivity.getString(R.string.init_dbmove_success) : fromActivity.getString(R.string.init_dbmove_failed); Dialogs.message(fromActivity, R.string.init_dbmove_dbmove, message); } - }, Schedulers.io()); + }); } private static File databasePath(final boolean internal) { @@ -464,7 +464,7 @@ public class DataStore { private static class DBContext extends ContextWrapper { - public DBContext(Context base) { + public DBContext(final Context base) { super(base); } @@ -473,8 +473,8 @@ public class DataStore { * causes issues on other devices too. */ @Override - public SQLiteDatabase openOrCreateDatabase(String name, int mode, - CursorFactory factory) { + public SQLiteDatabase openOrCreateDatabase(final String name, final int mode, + final CursorFactory factory) { final File file = new File(name); FileUtils.mkdirs(file.getParentFile()); return SQLiteDatabase.openOrCreateDatabase(file, factory); @@ -486,12 +486,12 @@ public class DataStore { private static boolean firstRun = true; - DbHelper(Context context) { + DbHelper(final Context context) { super(context, databasePath().getPath(), null, dbVersion); } @Override - public void onCreate(SQLiteDatabase db) { + public void onCreate(final SQLiteDatabase db) { newlyCreatedDatabase = true; db.execSQL(dbCreateCaches); db.execSQL(dbCreateLists); @@ -528,7 +528,7 @@ public class DataStore { } @Override - public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { + public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) { Log.i("Upgrade database from ver. " + oldVersion + " to ver. " + newVersion + ": start"); try { @@ -553,7 +553,7 @@ public class DataStore { db.execSQL(dbCreateSearchDestinationHistory); Log.i("Added table " + dbTableSearchDestionationHistory + "."); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 52", e); } } @@ -563,7 +563,7 @@ public class DataStore { db.execSQL("alter table " + dbTableCaches + " add column onWatchlist integer"); Log.i("Column onWatchlist added to " + dbTableCaches + "."); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 53", e); } } @@ -571,7 +571,7 @@ public class DataStore { if (oldVersion < 54) { // update to 54 try { db.execSQL(dbCreateLogImages); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 54", e); } @@ -580,7 +580,7 @@ public class DataStore { if (oldVersion < 55) { // update to 55 try { db.execSQL("alter table " + dbTableCaches + " add column personal_note text"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 55", e); } } @@ -592,7 +592,7 @@ public class DataStore { db.execSQL("update " + dbTableAttributes + " set attribute = " + "lower(attribute) where attribute like \"%_yes\" " + "or attribute like \"%_no\""); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 56", e); } } @@ -607,7 +607,7 @@ public class DataStore { db.execSQL("drop index in_e"); db.execSQL("drop index in_f"); createIndices(db); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 57", e); } } @@ -696,7 +696,7 @@ public class DataStore { db.setTransactionSuccessful(); Log.i("Removed latitude_string and longitude_string columns"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 58", e); } finally { db.endTransaction(); @@ -708,7 +708,7 @@ public class DataStore { // Add new indices and remove obsolete cache files createIndices(db); removeObsoleteCacheDirectories(db); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 59", e); } } @@ -716,7 +716,7 @@ public class DataStore { if (oldVersion < 60) { try { removeSecEmptyDirs(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 60", e); } } @@ -724,7 +724,7 @@ public class DataStore { try { db.execSQL("alter table " + dbTableLogs + " add column friend integer"); db.execSQL("alter table " + dbTableCaches + " add column coordsChanged integer default 0"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 61", e); } @@ -735,7 +735,7 @@ public class DataStore { db.execSQL("alter table " + dbTableCaches + " add column finalDefined integer default 0"); db.execSQL("alter table " + dbTableWaypoints + " add column own integer default 0"); db.execSQL("update " + dbTableWaypoints + " set own = 1 where type = 'own'"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 62", e); } @@ -743,7 +743,7 @@ public class DataStore { if (oldVersion < 63) { try { removeDoubleUnderscoreMapFiles(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 63", e); } @@ -755,7 +755,7 @@ public class DataStore { // rather than symbolic ones because the fix must be applied with the values at the time // of the problem. The problem was introduced in release 2012.06.01. db.execSQL("update " + dbTableCaches + " set reason=1 where reason=2"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 64", e); } } @@ -764,7 +764,7 @@ public class DataStore { try { // Set all waypoints where name is Original coordinates to type ORIGINAL db.execSQL("update " + dbTableWaypoints + " set type='original', own=0 where name='Original Coordinates'"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 65:", e); } } @@ -772,7 +772,7 @@ public class DataStore { if (oldVersion < 66) { try { db.execSQL("alter table " + dbTableWaypoints + " add column visited integer default 0"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 66", e); } @@ -782,7 +782,7 @@ public class DataStore { try { db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_yes' where geocode like 'OC%' and attribute = 'climbing_yes'"); db.execSQL("update " + dbTableAttributes + " set attribute = 'easy_climbing_no' where geocode like 'OC%' and attribute = 'climbing_no'"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 67", e); } @@ -791,7 +791,7 @@ public class DataStore { if (oldVersion < 68) { try { db.execSQL("alter table " + dbTableCaches + " add column logPasswordRequired integer default 0"); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Failed to upgrade to ver. 68", e); } @@ -838,7 +838,7 @@ public class DataStore { if (ArrayUtils.isNotEmpty(geocodeDirs)) { final FilenameFilter filter = new FilenameFilter() { @Override - public boolean accept(File dir, String filename) { + public boolean accept(final File dir, final String filename) { return filename.startsWith("map_") && filename.contains("__"); } }; @@ -914,7 +914,7 @@ public class DataStore { } } - private static void dropDatabase(SQLiteDatabase db) { + private static void dropDatabase(final SQLiteDatabase db) { db.execSQL("drop table if exists " + dbTableCaches); db.execSQL("drop table if exists " + dbTableAttributes); db.execSQL("drop table if exists " + dbTableWaypoints); @@ -925,7 +925,7 @@ public class DataStore { db.execSQL("drop table if exists " + dbTableTrackables); } - public static boolean isThere(String geocode, String guid, boolean detailed, boolean checkTime) { + public static boolean isThere(final String geocode, final String guid, final boolean detailed, final boolean checkTime) { init(); long dataUpdated = 0; @@ -990,7 +990,7 @@ public class DataStore { } /** is cache stored in one of the lists (not only temporary) */ - public static boolean isOffline(String geocode, String guid) { + public static boolean isOffline(final String geocode, final String guid) { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { return false; } @@ -1011,16 +1011,16 @@ public class DataStore { listId.bindString(1, value); return listId.simpleQueryForLong() != StoredList.TEMPORARY_LIST_ID; } - } catch (SQLiteDoneException e) { + } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.isOffline", e); } return false; } - public static String getGeocodeForGuid(String guid) { + public static String getGeocodeForGuid(final String guid) { if (StringUtils.isBlank(guid)) { return null; } @@ -1032,16 +1032,16 @@ public class DataStore { description.bindString(1, guid); return description.simpleQueryForString(); } - } catch (SQLiteDoneException e) { + } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.getGeocodeForGuid", e); } return null; } - public static String getCacheidForGeocode(String geocode) { + public static String getCacheidForGeocode(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } @@ -1053,9 +1053,9 @@ public class DataStore { description.bindString(1, geocode); return description.simpleQueryForString(); } - } catch (SQLiteDoneException e) { + } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.getCacheidForGeocode", e); } @@ -1070,7 +1070,7 @@ public class DataStore { * @param saveFlags * */ - public static void saveCache(Geocache cache, EnumSet<LoadFlags.SaveFlag> saveFlags) { + public static void saveCache(final Geocache cache, final EnumSet<LoadFlags.SaveFlag> saveFlags) { saveCaches(Collections.singletonList(cache), saveFlags); } @@ -1082,7 +1082,7 @@ public class DataStore { * @param saveFlags * */ - public static void saveCaches(Collection<Geocache> caches, EnumSet<LoadFlags.SaveFlag> saveFlags) { + public static void saveCaches(final Collection<Geocache> caches, final EnumSet<LoadFlags.SaveFlag> saveFlags) { if (CollectionUtils.isEmpty(caches)) { return; } @@ -1090,7 +1090,7 @@ public class DataStore { final HashMap<String, Geocache> existingCaches = new HashMap<String, Geocache>(); // first check which caches are in the memory cache - for (Geocache cache : caches) { + for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache cacheFromCache = cacheCache.getCacheFromCache(geocode); if (cacheFromCache == null) { @@ -1102,7 +1102,7 @@ public class DataStore { } // then load all remaining caches from the database in one step - for (Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) { + for (final Geocache cacheFromDatabase : loadCaches(cachesFromDatabase, LoadFlags.LOAD_ALL_DB_ONLY)) { existingCaches.put(cacheFromDatabase.getGeocode(), cacheFromDatabase); } @@ -1113,7 +1113,7 @@ public class DataStore { // (as it may be more recent than the version in the database), or if the // version coming from the database is different than the version we are entering // into the cache (that includes absence from the database). - for (Geocache cache : caches) { + for (final Geocache cache : caches) { final String geocode = cache.getGeocode(); final Geocache existingCache = existingCaches.get(geocode); final boolean dbUpdateRequired = !cache.gatherMissingFrom(existingCache) || cacheCache.getCacheFromCache(geocode) != null; @@ -1127,7 +1127,7 @@ public class DataStore { } } - for (Geocache geocache : toBeStored) { + for (final Geocache geocache : toBeStored) { storeIntoDatabase(geocache); } } @@ -1137,7 +1137,7 @@ public class DataStore { cacheCache.putCacheInCache(cache); Log.d("Saving " + cache.toString() + " (" + cache.getListId() + ") to DB"); - ContentValues values = new ContentValues(); + final ContentValues values = new ContentValues(); if (cache.getUpdated() == 0) { values.put("updated", System.currentTimeMillis()); @@ -1200,7 +1200,7 @@ public class DataStore { saveLogCountsWithoutTransaction(cache); saveInventoryWithoutTransaction(cache.getGeocode(), cache.getInventory()); - int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); + final int rows = database.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); if (rows == 0) { // cache is not in the DB, insert it /* long id = */ @@ -1208,7 +1208,7 @@ public class DataStore { } database.setTransactionSuccessful(); return true; - } catch (Exception e) { + } catch (final Exception e) { Log.e("SaveCache", e); } finally { database.endTransaction(); @@ -1228,7 +1228,7 @@ public class DataStore { if (attributes.isEmpty()) { return; } - SQLiteStatement statement = PreparedStatements.getInsertAttribute(); + final SQLiteStatement statement = PreparedStatements.getInsertAttribute(); final long timestamp = System.currentTimeMillis(); for (final String attribute : attributes) { statement.bindString(1, geocode); @@ -1251,10 +1251,10 @@ public class DataStore { database.beginTransaction(); try { - SQLiteStatement insertDestination = PreparedStatements.getInsertSearchDestination(destination); + final SQLiteStatement insertDestination = PreparedStatements.getInsertSearchDestination(destination); insertDestination.executeInsert(); database.setTransactionSuccessful(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("Updating searchedDestinations db failed", e); } finally { database.endTransaction(); @@ -1269,7 +1269,7 @@ public class DataStore { saveWaypointsWithoutTransaction(cache); database.setTransactionSuccessful(); return true; - } catch (Exception e) { + } catch (final Exception e) { Log.e("saveWaypoints", e); } finally { database.endTransaction(); @@ -1278,14 +1278,14 @@ public class DataStore { } private static void saveWaypointsWithoutTransaction(final Geocache cache) { - String geocode = cache.getGeocode(); + final String geocode = cache.getGeocode(); - List<Waypoint> waypoints = cache.getWaypoints(); + final List<Waypoint> waypoints = cache.getWaypoints(); if (CollectionUtils.isNotEmpty(waypoints)) { final ArrayList<String> currentWaypointIds = new ArrayList<String>(); - ContentValues values = new ContentValues(); - long timeStamp = System.currentTimeMillis(); - for (Waypoint oneWaypoint : waypoints) { + final ContentValues values = new ContentValues(); + final long timeStamp = System.currentTimeMillis(); + for (final Waypoint oneWaypoint : waypoints) { values.clear(); values.put("geocode", geocode); @@ -1356,7 +1356,7 @@ public class DataStore { return new Geopoint(cursor.getDouble(indexLat), cursor.getDouble(indexLon)); } - private static boolean saveWaypointInternal(int id, String geocode, Waypoint waypoint) { + private static boolean saveWaypointInternal(final int id, final String geocode, final Waypoint waypoint) { if ((StringUtils.isBlank(geocode) && id <= 0) || waypoint == null) { return false; } @@ -1366,7 +1366,7 @@ public class DataStore { database.beginTransaction(); boolean ok = false; try { - ContentValues values = new ContentValues(); + final ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); @@ -1394,7 +1394,7 @@ public class DataStore { return ok; } - public static boolean deleteWaypoint(int id) { + public static boolean deleteWaypoint(final int id) { if (id == 0) { return false; } @@ -1405,14 +1405,14 @@ public class DataStore { } private static void saveSpoilersWithoutTransaction(final Geocache cache) { - String geocode = cache.getGeocode(); + final String geocode = cache.getGeocode(); database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode}); - List<Image> spoilers = cache.getSpoilers(); + final List<Image> spoilers = cache.getSpoilers(); if (CollectionUtils.isNotEmpty(spoilers)) { - SQLiteStatement insertSpoiler = PreparedStatements.getInsertSpoiler(); + final SQLiteStatement insertSpoiler = PreparedStatements.getInsertSpoiler(); final long timestamp = System.currentTimeMillis(); - for (Image spoiler : spoilers) { + for (final Image spoiler : spoilers) { insertSpoiler.bindString(1, geocode); insertSpoiler.bindLong(2, timestamp); insertSpoiler.bindString(3, spoiler.getUrl()); @@ -1429,17 +1429,13 @@ public class DataStore { } } - public static void saveLogsWithoutTransaction(final String geocode, final List<LogEntry> logs) { + public static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) { // TODO delete logimages referring these logs database.delete(dbTableLogs, "geocode = ?", new String[]{geocode}); - if (logs.isEmpty()) { - return; - } - - SQLiteStatement insertLog = PreparedStatements.getInsertLog(); + final SQLiteStatement insertLog = PreparedStatements.getInsertLog(); final long timestamp = System.currentTimeMillis(); - for (LogEntry log : logs) { + for (final LogEntry log : logs) { insertLog.bindString(1, geocode); insertLog.bindLong(2, timestamp); insertLog.bindLong(3, log.type.id); @@ -1448,10 +1444,10 @@ public class DataStore { insertLog.bindLong(6, log.date); insertLog.bindLong(7, log.found); insertLog.bindLong(8, log.friend ? 1 : 0); - long logId = insertLog.executeInsert(); + final long logId = insertLog.executeInsert(); if (log.hasLogImages()) { - SQLiteStatement insertImage = PreparedStatements.getInsertLogImage(); - for (Image img : log.getLogImages()) { + final SQLiteStatement insertImage = PreparedStatements.getInsertLogImage(); + for (final Image img : log.getLogImages()) { insertImage.bindLong(1, logId); insertImage.bindString(2, img.getTitle()); insertImage.bindString(3, img.getUrl()); @@ -1462,15 +1458,15 @@ public class DataStore { } private static void saveLogCountsWithoutTransaction(final Geocache cache) { - String geocode = cache.getGeocode(); + final String geocode = cache.getGeocode(); database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode}); - Map<LogType, Integer> logCounts = cache.getLogCounts(); + final Map<LogType, Integer> logCounts = cache.getLogCounts(); if (MapUtils.isNotEmpty(logCounts)) { - Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); - SQLiteStatement insertLogCounts = PreparedStatements.getInsertLogCounts(); + final Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); + final SQLiteStatement insertLogCounts = PreparedStatements.getInsertLogCounts(); final long timestamp = System.currentTimeMillis(); - for (Entry<LogType, Integer> pair : logCountsItems) { + for (final Entry<LogType, Integer> pair : logCountsItems) { insertLogCounts.bindString(1, geocode); insertLogCounts.bindLong(2, timestamp); insertLogCounts.bindLong(3, pair.getKey().id); @@ -1499,9 +1495,9 @@ public class DataStore { } if (CollectionUtils.isNotEmpty(trackables)) { - ContentValues values = new ContentValues(); - long timeStamp = System.currentTimeMillis(); - for (Trackable trackable : trackables) { + final ContentValues values = new ContentValues(); + final long timeStamp = System.currentTimeMillis(); + for (final Trackable trackable : trackables) { final String tbCode = trackable.getGeocode(); if (StringUtils.isNotBlank(tbCode)) { database.delete(dbTableTrackables, "tbcode = ?", new String[] { tbCode }); @@ -1566,12 +1562,12 @@ public class DataStore { return new HashSet<Geocache>(); } - Set<Geocache> result = new HashSet<Geocache>(); - Set<String> remaining = new HashSet<String>(geocodes); + final Set<Geocache> result = new HashSet<Geocache>(); + final Set<String> remaining = new HashSet<String>(geocodes); if (loadFlags.contains(LoadFlag.LOAD_CACHE_BEFORE)) { - for (String geocode : new HashSet<String>(remaining)) { - Geocache cache = cacheCache.getCacheFromCache(geocode); + for (final String geocode : new HashSet<String>(remaining)) { + final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); @@ -1595,8 +1591,8 @@ public class DataStore { } if (loadFlags.contains(LoadFlag.LOAD_CACHE_AFTER)) { - for (String geocode : new HashSet<String>(remaining)) { - Geocache cache = cacheCache.getCacheFromCache(geocode); + for (final String geocode : new HashSet<String>(remaining)) { + final Geocache cache = cacheCache.getCacheFromCache(geocode); if (cache != null) { result.add(cache); remaining.remove(cache.getGeocode()); @@ -1638,13 +1634,13 @@ public class DataStore { query.append(" WHERE ").append(dbTableCaches).append('.'); query.append(DataStore.whereGeocodeIn(geocodes)); - Cursor cursor = database.rawQuery(query.toString(), null); + final Cursor cursor = database.rawQuery(query.toString(), null); try { final Set<Geocache> caches = new HashSet<Geocache>(); int logIndex = -1; while (cursor.moveToNext()) { - Geocache cache = DataStore.createCacheFromDatabaseContent(cursor); + final Geocache cache = DataStore.createCacheFromDatabaseContent(cursor); if (loadFlags.contains(LoadFlag.LOAD_ATTRIBUTES)) { cache.setAttributes(loadAttributes(cache.getGeocode())); @@ -1718,8 +1714,8 @@ public class DataStore { * @param cursor * @return Cache from DB */ - private static Geocache createCacheFromDatabaseContent(Cursor cursor) { - Geocache cache = new Geocache(); + private static Geocache createCacheFromDatabaseContent(final Cursor cursor) { + final Geocache cache = new Geocache(); cache.setUpdated(cursor.getLong(0)); cache.setListId(cursor.getInt(1)); @@ -1733,7 +1729,7 @@ public class DataStore { cache.setName(cursor.getString(9)); cache.setOwnerDisplayName(cursor.getString(10)); cache.setOwnerUserId(cursor.getString(11)); - long dateValue = cursor.getLong(12); + final long dateValue = cursor.getLong(12); if (dateValue != 0) { cache.setHidden(new Date(dateValue)); } @@ -1779,7 +1775,7 @@ public class DataStore { return cache; } - public static List<String> loadAttributes(String geocode) { + public static List<String> loadAttributes(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } @@ -1796,7 +1792,7 @@ public class DataStore { GET_STRING_0); } - public static Waypoint loadWaypoint(int id) { + public static Waypoint loadWaypoint(final int id) { if (id == 0) { return null; } @@ -1915,7 +1911,7 @@ public class DataStore { database.delete(dbTableSearchDestionationHistory, null, null); database.setTransactionSuccessful(); return true; - } catch (Exception e) { + } catch (final Exception e) { Log.e("Unable to clear searched destinations", e); } finally { database.endTransaction(); @@ -1929,8 +1925,8 @@ public class DataStore { * @return an immutable, non null list of logs */ @NonNull - public static List<LogEntry> loadLogs(String geocode) { - List<LogEntry> logs = new ArrayList<LogEntry>(); + public static List<LogEntry> loadLogs(final String geocode) { + final List<LogEntry> logs = new ArrayList<LogEntry>(); if (StringUtils.isBlank(geocode)) { return logs; @@ -1967,7 +1963,7 @@ public class DataStore { return Collections.unmodifiableList(logs); } - public static Map<LogType, Integer> loadLogCounts(String geocode) { + public static Map<LogType, Integer> loadLogCounts(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } @@ -1995,7 +1991,7 @@ public class DataStore { return logCounts; } - private static List<Trackable> loadInventory(String geocode) { + private static List<Trackable> loadInventory(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } @@ -2056,7 +2052,7 @@ public class DataStore { final String released = cursor.getString(cursor.getColumnIndex("released")); if (released != null) { try { - long releaseMilliSeconds = Long.parseLong(released); + final long releaseMilliSeconds = Long.parseLong(released); trackable.setReleased(new Date(releaseMilliSeconds)); } catch (final NumberFormatException e) { Log.e("createTrackableFromDatabaseContent", e); @@ -2085,7 +2081,7 @@ public class DataStore { init(); try { - StringBuilder sql = new StringBuilder("select count(_id) from " + dbTableCaches + " where detailed = 1"); + final StringBuilder sql = new StringBuilder("select count(_id) from " + dbTableCaches + " where detailed = 1"); String typeKey; int reasonIndex; if (cacheType != CacheType.ALL) { @@ -2106,9 +2102,9 @@ public class DataStore { listKey = "list"; } - String key = "CountCaches_" + typeKey + "_" + listKey; + final String key = "CountCaches_" + typeKey + "_" + listKey; - SQLiteStatement compiledStmnt = PreparedStatements.getStatement(key, sql.toString()); + final SQLiteStatement compiledStmnt = PreparedStatements.getStatement(key, sql.toString()); if (cacheType != CacheType.ALL) { compiledStmnt.bindString(1, cacheType.id); } @@ -2116,7 +2112,7 @@ public class DataStore { compiledStmnt.bindLong(reasonIndex, list); } return (int) compiledStmnt.simpleQueryForLong(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.loadAllStoredCachesCount", e); } @@ -2128,7 +2124,7 @@ public class DataStore { try { return (int) PreparedStatements.getCountHistoryCaches().simpleQueryForLong(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.getAllHistoricCachesCount", e); } @@ -2239,7 +2235,7 @@ public class DataStore { null, new HashSet<String>(), GET_STRING_0); - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.loadBatchOfHistoricGeocodes", e); } @@ -2399,7 +2395,7 @@ public class DataStore { cacheCache.removeAllFromCache(); } - public static void removeCache(final String geocode, EnumSet<LoadFlags.RemoveFlag> removeFlags) { + public static void removeCache(final String geocode, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { removeCaches(Collections.singleton(geocode), removeFlags); } @@ -2409,7 +2405,7 @@ public class DataStore { * @param geocodes * list of geocodes to drop from cache */ - public static void removeCaches(final Set<String> geocodes, EnumSet<LoadFlags.RemoveFlag> removeFlags) { + public static void removeCaches(final Set<String> geocodes, final EnumSet<LoadFlags.RemoveFlag> removeFlags) { if (CollectionUtils.isEmpty(geocodes)) { return; } @@ -2457,7 +2453,7 @@ public class DataStore { } } - public static boolean saveLogOffline(String geocode, Date date, LogType type, String log) { + public static boolean saveLogOffline(final String geocode, final Date date, final LogType type, final String log) { if (StringUtils.isBlank(geocode)) { Log.e("DataStore.saveLogOffline: cannot log a blank geocode"); return false; @@ -2484,7 +2480,7 @@ public class DataStore { return id != -1; } - public static LogEntry loadLogOffline(String geocode) { + public static LogEntry loadLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return null; } @@ -2515,7 +2511,7 @@ public class DataStore { return log; } - public static void clearLogOffline(String geocode) { + public static void clearLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return; } @@ -2525,15 +2521,15 @@ public class DataStore { database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode}); } - public static void clearLogsOffline(List<Geocache> caches) { + public static void clearLogsOffline(final List<Geocache> caches) { if (CollectionUtils.isEmpty(caches)) { return; } init(); - Set<String> geocodes = new HashSet<String>(caches.size()); - for (Geocache cache : caches) { + final Set<String> geocodes = new HashSet<String>(caches.size()); + for (final Geocache cache : caches) { geocodes.add(cache.getGeocode()); cache.setLogOffline(false); } @@ -2553,14 +2549,14 @@ public class DataStore { logCount.bindString(1, geocode); return logCount.simpleQueryForLong() > 0; } - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.hasLogOffline", e); } return false; } - private static void setVisitDate(List<String> geocodes, long visitedDate) { + private static void setVisitDate(final List<String> geocodes, final long visitedDate) { if (geocodes.isEmpty()) { return; } @@ -2569,9 +2565,9 @@ public class DataStore { database.beginTransaction(); try { - SQLiteStatement setVisit = PreparedStatements.getUpdateVisitDate(); + final SQLiteStatement setVisit = PreparedStatements.getUpdateVisitDate(); - for (String geocode : geocodes) { + for (final String geocode : geocodes) { setVisit.bindLong(1, visitedDate); setVisit.bindString(2, geocode); setVisit.execute(); @@ -2617,10 +2613,10 @@ public class DataStore { }); } - public static StoredList getList(int id) { + public static StoredList getList(final int id) { init(); if (id >= customListIdOffset) { - Cursor cursor = database.query( + final Cursor cursor = database.query( dbTableLists, new String[]{"_id", "title"}, "_id = ? ", @@ -2628,13 +2624,13 @@ public class DataStore { null, null, null); - ArrayList<StoredList> lists = getListsFromCursor(cursor); + final ArrayList<StoredList> lists = getListsFromCursor(cursor); if (!lists.isEmpty()) { return lists.get(0); } } - Resources res = CgeoApplication.getInstance().getResources(); + final Resources res = CgeoApplication.getInstance().getResources(); if (id == PseudoList.ALL_LIST.id) { return new StoredList(PseudoList.ALL_LIST.id, res.getString(R.string.list_all_lists), getAllCachesCount()); } @@ -2658,7 +2654,7 @@ public class DataStore { * Name * @return new listId */ - public static int createList(String name) { + public static int createList(final String name) { int id = -1; if (StringUtils.isBlank(name)) { return id; @@ -2668,7 +2664,7 @@ public class DataStore { database.beginTransaction(); try { - ContentValues values = new ContentValues(); + final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); @@ -2698,7 +2694,7 @@ public class DataStore { database.beginTransaction(); int count = 0; try { - ContentValues values = new ContentValues(); + final ContentValues values = new ContentValues(); values.put("title", name); values.put("updated", System.currentTimeMillis()); @@ -2717,7 +2713,7 @@ public class DataStore { * @param listId * @return true if the list got deleted, false else */ - public static boolean removeList(int listId) { + public static boolean removeList(final int listId) { if (listId < customListIdOffset) { return false; } @@ -2727,11 +2723,11 @@ public class DataStore { database.beginTransaction(); boolean status = false; try { - int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); + final int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); if (cnt > 0) { // move caches from deleted list to standard list - SQLiteStatement moveToStandard = PreparedStatements.getMoveToStandardList(); + final SQLiteStatement moveToStandard = PreparedStatements.getMoveToStandardList(); moveToStandard.bindLong(1, listId); moveToStandard.execute(); @@ -2763,11 +2759,11 @@ public class DataStore { } init(); - SQLiteStatement move = PreparedStatements.getMoveToList(); + final SQLiteStatement move = PreparedStatements.getMoveToList(); database.beginTransaction(); try { - for (Geocache cache : caches) { + for (final Geocache cache : caches) { move.bindLong(1, listId); move.bindString(2, cache.getGeocode()); move.execute(); @@ -2783,7 +2779,7 @@ public class DataStore { return database != null; } - public static boolean removeSearchedDestination(Destination destination) { + public static boolean removeSearchedDestination(final Destination destination) { if (destination == null) { return false; } @@ -2794,7 +2790,7 @@ public class DataStore { database.delete(dbTableSearchDestionationHistory, "_id = " + destination.getId(), null); database.setTransactionSuccessful(); return true; - } catch (Exception e) { + } catch (final Exception e) { Log.e("Unable to remove searched destination", e); } finally { database.endTransaction(); @@ -2839,9 +2835,9 @@ public class DataStore { } cursor.close(); - } catch (SQLiteDoneException e) { + } catch (final SQLiteDoneException e) { // Do nothing, it only means we have no information on the cache - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.getCacheDescription", e); } @@ -2888,13 +2884,14 @@ public class DataStore { * @return */ - public static Set<Waypoint> loadWaypoints(final Viewport viewport, boolean excludeMine, boolean excludeDisabled, CacheType type) { + public static Set<Waypoint> loadWaypoints(final Viewport viewport, final boolean excludeMine, final boolean excludeDisabled, final CacheType type) { final StringBuilder where = buildCoordinateWhere(dbTableWaypoints, viewport); if (excludeMine) { where.append(" and ").append(dbTableCaches).append(".found == 0"); } if (excludeDisabled) { where.append(" and ").append(dbTableCaches).append(".disabled == 0"); + where.append(" and ").append(dbTableCaches).append(".archived == 0"); } if (type != CacheType.ALL) { where.append(" and ").append(dbTableCaches).append(".type == '").append(type.id).append('\''); @@ -2916,7 +2913,7 @@ public class DataStore { }); } - public static void saveChangedCache(Geocache cache) { + public static void saveChangedCache(final Geocache cache) { DataStore.saveCache(cache, cache.getStorageLocation().contains(StorageLocation.DATABASE) ? LoadFlags.SAVE_ALL : EnumSet.of(SaveFlag.SAVE_CACHE)); } @@ -2948,7 +2945,7 @@ public class DataStore { return getStatement("InsertSpoiler", "INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"); } - public static SQLiteStatement getInsertSearchDestination(Destination destination) { + public static SQLiteStatement getInsertSearchDestination(final Destination destination) { final SQLiteStatement statement = getStatement("InsertSearch", "INSERT INTO " + dbTableSearchDestionationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"); statement.bindLong(1, destination.getDate()); final Geopoint coords = destination.getCoords(); @@ -2958,7 +2955,7 @@ public class DataStore { } private static void clearPreparedStatements() { - for (SQLiteStatement statement : statements.values()) { + for (final SQLiteStatement statement : statements.values()) { statement.close(); } statements.clear(); @@ -3020,11 +3017,11 @@ public class DataStore { setVisitDate(Collections.singletonList(geocode), System.currentTimeMillis()); } - public static void markDropped(List<Geocache> caches) { + public static void markDropped(final List<Geocache> caches) { moveToList(caches, StoredList.TEMPORARY_LIST_ID); } - public static Viewport getBounds(String geocode) { + public static Viewport getBounds(final String geocode) { if (geocode == null) { return null; } @@ -3032,21 +3029,21 @@ public class DataStore { return DataStore.getBounds(Collections.singleton(geocode)); } - public static void clearVisitDate(String[] selected) { + public static void clearVisitDate(final String[] selected) { setVisitDate(Arrays.asList(selected), 0); } - public static SearchResult getBatchOfStoredCaches(Geopoint coords, CacheType cacheType, int listId) { + public static SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) { final Set<String> geocodes = DataStore.loadBatchOfStoredGeocodes(coords, cacheType, listId); return new SearchResult(geocodes, DataStore.getAllStoredCachesCount(cacheType, listId)); } - public static SearchResult getHistoryOfCaches(boolean detailedOnly, CacheType cacheType) { + public static SearchResult getHistoryOfCaches(final boolean detailedOnly, final CacheType cacheType) { final Set<String> geocodes = DataStore.loadBatchOfHistoricGeocodes(detailedOnly, cacheType); return new SearchResult(geocodes, DataStore.getAllHistoryCachesCount()); } - public static boolean saveWaypoint(int id, String geocode, Waypoint waypoint) { + public static boolean saveWaypoint(final int id, final String geocode, final Waypoint waypoint) { if (DataStore.saveWaypointInternal(id, geocode, waypoint)) { DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.REMOVE_CACHE)); return true; @@ -3090,13 +3087,7 @@ public class DataStore { return null; } init(); - final MatrixCursor resultCursor = new MatrixCursor(new String[] { - BaseColumns._ID, - SearchManager.SUGGEST_COLUMN_TEXT_1, - SearchManager.SUGGEST_COLUMN_TEXT_2, - SearchManager.SUGGEST_COLUMN_INTENT_ACTION, - SearchManager.SUGGEST_COLUMN_QUERY - }); + final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor(); try { final String selectionArg = getSuggestionArgument(searchTerm); findCaches(resultCursor, selectionArg); @@ -3107,10 +3098,10 @@ public class DataStore { return resultCursor; } - private static void findCaches(final MatrixCursor resultCursor, final String selectionArg) { - Cursor cursor = database.query( + private static void findCaches(final SearchSuggestionCursor resultCursor, final String selectionArg) { + final Cursor cursor = database.query( dbTableCaches, - new String[] { "geocode", "name" }, + new String[] { "geocode", "name", "type" }, "geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)", new String[] { selectionArg, selectionArg, selectionArg }, null, @@ -3118,23 +3109,19 @@ public class DataStore { "name"); while (cursor.moveToNext()) { final String geocode = cursor.getString(0); - resultCursor.addRow(new String[] { - String.valueOf(resultCursor.getCount()), - cursor.getString(1), - geocode, - Intents.ACTION_GEOCACHE, - geocode - }); + final String cacheName = cursor.getString(1); + final String type = cursor.getString(2); + resultCursor.addCache(geocode, cacheName, type); } cursor.close(); } - private static String getSuggestionArgument(String input) { + private static String getSuggestionArgument(final String input) { return "%" + StringUtils.trim(input) + "%"; } private static void findTrackables(final MatrixCursor resultCursor, final String selectionArg) { - Cursor cursor = database.query( + final Cursor cursor = database.query( dbTableTrackables, new String[] { "tbcode", "title" }, "tbcode IS NOT NULL AND tbcode != '' AND (tbcode LIKE ? OR title LIKE ?)", @@ -3156,31 +3143,53 @@ public class DataStore { } public static String[] getSuggestions(final String table, final String column, final String input) { - Cursor cursor = database.rawQuery("SELECT DISTINCT " + column + final Cursor cursor = database.rawQuery("SELECT DISTINCT " + column + " FROM " + table + " WHERE " + column + " LIKE ?" + " ORDER BY " + column + " COLLATE NOCASE ASC;", new String[] { getSuggestionArgument(input) }); return cursorToColl(cursor, new LinkedList<String>(), GET_STRING_0).toArray(new String[cursor.getCount()]); } - public static String[] getSuggestionsOwnerName(String input) { - return getSuggestions(dbTableCaches, "owner", input); + public static String[] getSuggestionsOwnerName(final String input) { + return getSuggestions(dbTableCaches, "owner_real", input); } - public static String[] getSuggestionsTrackableCode(String input) { + public static String[] getSuggestionsTrackableCode(final String input) { return getSuggestions(dbTableTrackables, "tbcode", input); } - public static String[] getSuggestionsFinderName(String input) { + public static String[] getSuggestionsFinderName(final String input) { return getSuggestions(dbTableLogs, "author", input); } - public static String[] getSuggestionsGeocode(String input) { + public static String[] getSuggestionsGeocode(final String input) { return getSuggestions(dbTableCaches, "geocode", input); } - public static String[] getSuggestionsKeyword(String input) { + public static String[] getSuggestionsKeyword(final String input) { return getSuggestions(dbTableCaches, "name", input); } + /** + * + * @return list of last caches opened in the details view, ordered by most recent first + */ + public static ArrayList<Geocache> getLastOpenedCaches() { + final List<String> geocodes = Settings.getLastOpenedCaches(); + final Set<Geocache> cachesSet = DataStore.loadCaches(geocodes, LoadFlags.LOAD_CACHE_OR_DB); + + // order result set by time again + final ArrayList<Geocache> caches = new ArrayList<Geocache>(cachesSet); + Collections.sort(caches, new Comparator<Geocache>() { + + @Override + public int compare(final Geocache lhs, final Geocache rhs) { + final int lhsIndex = geocodes.indexOf(lhs.getGeocode()); + final int rhsIndex = geocodes.indexOf(rhs.getGeocode()); + return lhsIndex < rhsIndex ? -1 : (lhsIndex == rhsIndex ? 0 : 1); + } + }); + return caches; + } + } |
