diff options
| author | Bananeweizen <bananeweizen@gmx.de> | 2014-06-01 14:58:43 +0200 |
|---|---|---|
| committer | Bananeweizen <bananeweizen@gmx.de> | 2014-06-01 15:00:14 +0200 |
| commit | fc73a0edc9d7488660fdb34fefc9cc9f1c5a5d69 (patch) | |
| tree | 4c2b8e6d21f43fad496b4d5a45f455dcb492997e /main/src/cgeo | |
| parent | ced55f4138eb2c583142bf821e328a452ee0a717 (diff) | |
| download | cgeo-fc73a0edc9d7488660fdb34fefc9cc9f1c5a5d69.zip cgeo-fc73a0edc9d7488660fdb34fefc9cc9f1c5a5d69.tar.gz cgeo-fc73a0edc9d7488660fdb34fefc9cc9f1c5a5d69.tar.bz2 | |
new: show recently opened caches in global search
Without any search term given, the search suggestions now contain the
most recent caches.
We should probably add a more explicit UI on the main screen for that,
too, as discussed before.
Diffstat (limited to 'main/src/cgeo')
| -rw-r--r-- | main/src/cgeo/geocaching/CacheDetailActivity.java | 2 | ||||
| -rw-r--r-- | main/src/cgeo/geocaching/DataStore.java | 329 | ||||
| -rw-r--r-- | main/src/cgeo/geocaching/search/AutoCompleteAdapter.java | 17 | ||||
| -rw-r--r-- | main/src/cgeo/geocaching/search/SearchSuggestionCursor.java | 42 | ||||
| -rw-r--r-- | main/src/cgeo/geocaching/search/SuggestionProvider.java | 16 | ||||
| -rw-r--r-- | main/src/cgeo/geocaching/settings/Settings.java | 66 |
6 files changed, 275 insertions, 197 deletions
diff --git a/main/src/cgeo/geocaching/CacheDetailActivity.java b/main/src/cgeo/geocaching/CacheDetailActivity.java index e1955d6..cf3b850 100644 --- a/main/src/cgeo/geocaching/CacheDetailActivity.java +++ b/main/src/cgeo/geocaching/CacheDetailActivity.java @@ -589,6 +589,8 @@ public class CacheDetailActivity extends AbstractViewPagerActivity<CacheDetailAc // rendering done! remove progress popup if any there invalidateOptionsMenuCompatible(); progress.dismiss(); + + Settings.addCacheToHistory(cache.getGeocode()); } diff --git a/main/src/cgeo/geocaching/DataStore.java b/main/src/cgeo/geocaching/DataStore.java index 350bc6b..103c356 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); } } @@ -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()); @@ -1458,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); @@ -1495,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 }); @@ -1562,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()); @@ -1591,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()); @@ -1634,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())); @@ -1714,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)); @@ -1729,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)); } @@ -1775,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; } @@ -1792,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; } @@ -1911,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(); @@ -1925,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; @@ -1963,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; } @@ -1991,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; } @@ -2052,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); @@ -2081,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) { @@ -2102,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); } @@ -2112,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); } @@ -2124,7 +2124,7 @@ public class DataStore { try { return (int) PreparedStatements.getCountHistoryCaches().simpleQueryForLong(); - } catch (Exception e) { + } catch (final Exception e) { Log.e("DataStore.getAllHistoricCachesCount", e); } @@ -2235,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); } @@ -2395,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); } @@ -2405,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; } @@ -2453,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; @@ -2480,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; } @@ -2511,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; } @@ -2521,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); } @@ -2549,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; } @@ -2565,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(); @@ -2613,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 = ? ", @@ -2624,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()); } @@ -2654,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; @@ -2664,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()); @@ -2694,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()); @@ -2713,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; } @@ -2723,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(); @@ -2759,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(); @@ -2779,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; } @@ -2790,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(); @@ -2835,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); } @@ -2884,7 +2884,7 @@ 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"); @@ -2913,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)); } @@ -2945,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(); @@ -2955,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(); @@ -3017,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; } @@ -3029,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; @@ -3087,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); @@ -3104,8 +3098,8 @@ 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" }, "geocode IS NOT NULL AND geocode != '' AND (geocode LIKE ? OR name LIKE ? OR owner LIKE ?)", @@ -3115,23 +3109,18 @@ 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); + resultCursor.addCache(geocode, cacheName); } 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 ?)", @@ -3153,31 +3142,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) { + 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; + } + } diff --git a/main/src/cgeo/geocaching/search/AutoCompleteAdapter.java b/main/src/cgeo/geocaching/search/AutoCompleteAdapter.java index 45559f4..21cf089 100644 --- a/main/src/cgeo/geocaching/search/AutoCompleteAdapter.java +++ b/main/src/cgeo/geocaching/search/AutoCompleteAdapter.java @@ -1,6 +1,7 @@ package cgeo.geocaching.search; import org.apache.commons.lang3.StringUtils; + import rx.functions.Func1; import android.content.Context; @@ -14,11 +15,11 @@ import android.widget.Filter; */ public class AutoCompleteAdapter extends ArrayAdapter<String> { - private final String[] EMPTY = new String[0]; + private final static String[] EMPTY = new String[0]; private String[] suggestions = EMPTY; private final Func1<String, String[]> suggestionFunction; - public AutoCompleteAdapter(Context context, int textViewResourceId, final Func1<String, String[]> suggestionFunction) { + public AutoCompleteAdapter(final Context context, final int textViewResourceId, final Func1<String, String[]> suggestionFunction) { super(context, textViewResourceId); this.suggestionFunction = suggestionFunction; } @@ -29,7 +30,7 @@ public class AutoCompleteAdapter extends ArrayAdapter<String> { } @Override - public String getItem(int index) { + public String getItem(final int index) { return suggestions[index]; } @@ -38,14 +39,14 @@ public class AutoCompleteAdapter extends ArrayAdapter<String> { return new Filter() { @Override - protected FilterResults performFiltering(CharSequence constraint) { - FilterResults filterResults = new FilterResults(); + protected FilterResults performFiltering(final CharSequence constraint) { + final FilterResults filterResults = new FilterResults(); if (constraint == null) { return filterResults; } - String trimmed = StringUtils.trim(constraint.toString()); + final String trimmed = StringUtils.trim(constraint.toString()); if (StringUtils.length(trimmed) >= 2) { - String[] newResults = suggestionFunction.call(trimmed); + final String[] newResults = suggestionFunction.call(trimmed); // Assign the data to the FilterResults, but do not yet store in the global member. // Otherwise we might invalidate the adapter and cause an IllegalStateException. @@ -56,7 +57,7 @@ public class AutoCompleteAdapter extends ArrayAdapter<String> { } @Override - protected void publishResults(CharSequence constraint, FilterResults filterResults) { + protected void publishResults(final CharSequence constraint, final FilterResults filterResults) { if (filterResults != null && filterResults.count > 0) { suggestions = (String[]) filterResults.values; notifyDataSetChanged(); diff --git a/main/src/cgeo/geocaching/search/SearchSuggestionCursor.java b/main/src/cgeo/geocaching/search/SearchSuggestionCursor.java new file mode 100644 index 0000000..f058c1d --- /dev/null +++ b/main/src/cgeo/geocaching/search/SearchSuggestionCursor.java @@ -0,0 +1,42 @@ +package cgeo.geocaching.search; + +import cgeo.geocaching.Intents; + +import org.eclipse.jdt.annotation.NonNull; + +import android.app.SearchManager; +import android.database.MatrixCursor; +import android.provider.BaseColumns; + +/** + * Fixed fields cursor holding the necessary data for the search provider of the global search bar. + * + */ +public class SearchSuggestionCursor extends MatrixCursor { + + /** + * id of the row for callbacks after selection + */ + private int rowId = 0; + + public SearchSuggestionCursor() { + super(new String[] { + BaseColumns._ID, + SearchManager.SUGGEST_COLUMN_TEXT_1, + SearchManager.SUGGEST_COLUMN_TEXT_2, + SearchManager.SUGGEST_COLUMN_INTENT_ACTION, + SearchManager.SUGGEST_COLUMN_QUERY }); + } + + public void addCache(@NonNull final String geocode, @NonNull final String name) { + addRow(new String[] { + String.valueOf(rowId), + name, + geocode, + Intents.ACTION_GEOCACHE, + geocode + }); + rowId++; + } + +} diff --git a/main/src/cgeo/geocaching/search/SuggestionProvider.java b/main/src/cgeo/geocaching/search/SuggestionProvider.java index c0a7728..d8f95b6 100644 --- a/main/src/cgeo/geocaching/search/SuggestionProvider.java +++ b/main/src/cgeo/geocaching/search/SuggestionProvider.java @@ -1,6 +1,7 @@ package cgeo.geocaching.search; import cgeo.geocaching.DataStore; +import cgeo.geocaching.Geocache; import org.apache.commons.lang3.StringUtils; @@ -12,8 +13,6 @@ import android.net.Uri; public class SuggestionProvider extends ContentProvider { - private static Cursor lastCursor; - @Override public boolean onCreate() { return true; @@ -29,14 +28,21 @@ public class SuggestionProvider extends ContentProvider { final String searchTerm = uri.getLastPathSegment(); // can be empty when deleting the query if (StringUtils.equals(searchTerm, SearchManager.SUGGEST_URI_PATH_QUERY)) { - return lastCursor; + return getLastOpenedCaches(); } return getSuggestions(searchTerm); } + private static Cursor getLastOpenedCaches() { + final SearchSuggestionCursor resultCursor = new SearchSuggestionCursor(); + for (final Geocache geocache : DataStore.getLastOpenedCaches()) { + resultCursor.addCache(geocache.getGeocode(), geocache.getName()); + } + return resultCursor; + } + private static Cursor getSuggestions(final String searchTerm) { - lastCursor = DataStore.findSuggestions(searchTerm); - return lastCursor; + return DataStore.findSuggestions(searchTerm); } @Override diff --git a/main/src/cgeo/geocaching/settings/Settings.java b/main/src/cgeo/geocaching/settings/Settings.java index 9de272b..d4adcbd 100644 --- a/main/src/cgeo/geocaching/settings/Settings.java +++ b/main/src/cgeo/geocaching/settings/Settings.java @@ -39,6 +39,7 @@ import android.preference.PreferenceManager; import java.io.File; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.util.Locale; @@ -47,6 +48,7 @@ import java.util.Locale; */ public class Settings { + private static final char HISTORY_SEPARATOR = ','; public static final int SHOW_WP_THRESHOLD_DEFAULT = 10; public static final int SHOW_WP_THRESHOLD_MAX = 50; private static final int MAP_SOURCE_DEFAULT = GoogleMapProvider.GOOGLE_MAP_ID.hashCode(); @@ -63,7 +65,7 @@ public class Settings { Min, Sec; - public static CoordInputFormatEnum fromInt(int id) { + public static CoordInputFormatEnum fromInt(final int id) { final CoordInputFormatEnum[] values = CoordInputFormatEnum.values(); if (id < 0 || id >= values.length) { return Min; @@ -91,7 +93,7 @@ public class Settings { private static void migrateSettings() { // migrate from non standard file location and integer based boolean types - int oldVersion = getInt(R.string.pref_settingsversion, 0); + final int oldVersion = getInt(R.string.pref_settingsversion, 0); if (oldVersion < 1) { final String oldPreferencesName = "cgeo.pref"; final SharedPreferences old = CgeoApplication.getInstance().getSharedPreferences(oldPreferencesName, Context.MODE_PRIVATE); @@ -173,13 +175,13 @@ public class Settings { e.putInt(getKey(R.string.pref_showwaypointsthreshold), wpThreshold); // KEY_MAP_SOURCE must be string, because it is the key for a ListPreference now - int ms = sharedPrefs.getInt(getKey(R.string.pref_mapsource), MAP_SOURCE_DEFAULT); + final int ms = sharedPrefs.getInt(getKey(R.string.pref_mapsource), MAP_SOURCE_DEFAULT); e.remove(getKey(R.string.pref_mapsource)); e.putString(getKey(R.string.pref_mapsource), String.valueOf(ms)); // navigation tool ids must be string, because ListPreference uses strings as keys - int dnt1 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool), NavigationAppsEnum.COMPASS.id); - int dnt2 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool2), NavigationAppsEnum.INTERNAL_MAP.id); + final int dnt1 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool), NavigationAppsEnum.COMPASS.id); + final int dnt2 = sharedPrefs.getInt(getKey(R.string.pref_defaultNavigationTool2), NavigationAppsEnum.INTERNAL_MAP.id); e.remove(getKey(R.string.pref_defaultNavigationTool)); e.remove(getKey(R.string.pref_defaultNavigationTool2)); e.putString(getKey(R.string.pref_defaultNavigationTool), String.valueOf(dnt1)); @@ -258,7 +260,7 @@ public class Settings { return sharedPrefs.contains(getKey(prefKeyId)); } - public static void setLanguage(boolean useEnglish) { + public static void setLanguage(final boolean useEnglish) { final Configuration config = new Configuration(); config.locale = useEnglish ? Locale.ENGLISH : Locale.getDefault(); final Resources resources = CgeoApplication.getInstance().getResources(); @@ -346,11 +348,11 @@ public class Settings { } } - public static boolean isOCConnectorActive(int isActivePrefKeyId) { + public static boolean isOCConnectorActive(final int isActivePrefKeyId) { return getBoolean(isActivePrefKeyId, false); } - public static boolean hasOCAuthorization(int tokenPublicPrefKeyId, int tokenSecretPrefKeyId) { + public static boolean hasOCAuthorization(final int tokenPublicPrefKeyId, final int tokenSecretPrefKeyId) { return StringUtils.isNotBlank(getString(tokenPublicPrefKeyId, "")) && StringUtils.isNotBlank(getString(tokenSecretPrefKeyId, "")); } @@ -424,7 +426,7 @@ public class Settings { } public static boolean setMapFile(final String mapFile) { - boolean result = putString(R.string.pref_mapfile, mapFile); + final boolean result = putString(R.string.pref_mapfile, mapFile); if (mapFile != null) { setMapFileDirectory(new File(mapFile).getParent()); } @@ -444,7 +446,7 @@ public class Settings { } public static boolean setMapFileDirectory(final String mapFileDirectory) { - boolean result = putString(R.string.pref_mapDirectory, mapFileDirectory); + final boolean result = putString(R.string.pref_mapDirectory, mapFileDirectory); MapsforgeMapProvider.getInstance().updateOfflineMaps(); return result; } @@ -628,6 +630,7 @@ public class Settings { private final static int MAPNIK = 1; private final static int CYCLEMAP = 3; private final static int OFFLINE = 4; + private static final int HISTORY_SIZE = 10; /** * convert old preference ids for maps (based on constant values) into new hash based ids @@ -680,8 +683,8 @@ public class Settings { public static Geopoint getAnyCoordinates() { if (contains(R.string.pref_anylatitude) && contains(R.string.pref_anylongitude)) { - float lat = getFloat(R.string.pref_anylatitude, 0); - float lon = getFloat(R.string.pref_anylongitude, 0); + final float lat = getFloat(R.string.pref_anylatitude, 0); + final float lon = getFloat(R.string.pref_anylongitude, 0); return new Geopoint(lat, lon); } return null; @@ -764,7 +767,7 @@ public class Settings { } public static void setTwitterTokens(@Nullable final String tokenPublic, - @Nullable final String tokenSecret, boolean enableTwitter) { + @Nullable final String tokenSecret, final boolean enableTwitter) { putString(R.string.pref_twitter_token_public, tokenPublic); putString(R.string.pref_twitter_token_secret, tokenSecret); if (tokenPublic != null) { @@ -781,8 +784,8 @@ public class Settings { } public static ImmutablePair<String, String> getTempToken() { - String tokenPublic = getString(R.string.pref_temp_twitter_token_public, null); - String tokenSecret = getString(R.string.pref_temp_twitter_token_secret, null); + final String tokenPublic = getString(R.string.pref_temp_twitter_token_public, null); + final String tokenSecret = getString(R.string.pref_temp_twitter_token_secret, null); return new ImmutablePair<String, String>(tokenPublic, tokenSecret); } @@ -893,8 +896,8 @@ public class Settings { } public static File[] getMapThemeFiles() { - File directory = new File(Settings.getCustomRenderThemeBaseFolder()); - List<File> result = new ArrayList<File>(); + final File directory = new File(Settings.getCustomRenderThemeBaseFolder()); + final List<File> result = new ArrayList<File>(); FileUtils.listDir(result, directory, new ExtensionsBasedFileSelector(new String[] { "xml" }), null); return result.toArray(new File[result.size()]); @@ -902,13 +905,13 @@ public class Settings { private static class ExtensionsBasedFileSelector extends FileSelector { private final String[] extensions; - public ExtensionsBasedFileSelector(String[] extensions) { + public ExtensionsBasedFileSelector(final String[] extensions) { this.extensions = extensions; } @Override - public boolean isSelected(File file) { - String filename = file.getName(); - for (String ext : extensions) { + public boolean isSelected(final File file) { + final String filename = file.getName(); + for (final String ext : extensions) { if (StringUtils.endsWithIgnoreCase(filename, ext)) { return true; } @@ -974,7 +977,7 @@ public class Settings { putLong(R.string.pref_fieldNoteExportDate, date); } - public static boolean isUseNavigationApp(NavigationAppsEnum navApp) { + public static boolean isUseNavigationApp(final NavigationAppsEnum navApp) { return getBoolean(navApp.preferenceKey, true); } @@ -983,7 +986,7 @@ public class Settings { * * @param upload */ - public static void setFieldNoteExportUpload(boolean upload) { + public static void setFieldNoteExportUpload(final boolean upload) { putBoolean(R.string.pref_fieldNoteExportUpload, upload); } @@ -996,7 +999,7 @@ public class Settings { * * @param onlyNew */ - public static void setFieldNoteExportOnlyNew(boolean onlyNew) { + public static void setFieldNoteExportOnlyNew(final boolean onlyNew) { putBoolean(R.string.pref_fieldNoteExportOnlyNew, onlyNew); } @@ -1013,7 +1016,20 @@ public class Settings { return getInt(R.string.pref_changelog_last_version, 0); } - public static void setLastChangelogVersion(int version) { + public static void setLastChangelogVersion(final int version) { putInt(R.string.pref_changelog_last_version, version); } + + public static List<String> getLastOpenedCaches() { + final List<String> history = Arrays.asList(StringUtils.split(getString(R.string.pref_caches_history, StringUtils.EMPTY), HISTORY_SEPARATOR)); + return history.subList(0, Math.min(HISTORY_SIZE, history.size())); + } + + public static void addCacheToHistory(@NonNull final String geocode) { + final ArrayList<String> history = new ArrayList<String>(getLastOpenedCaches()); + // bring entry to front, if it already existed + history.remove(geocode); + history.add(0, geocode); + putString(R.string.pref_caches_history, StringUtils.join(history, HISTORY_SEPARATOR)); + } } |
