diff options
111 files changed, 2675 insertions, 1739 deletions
diff --git a/main/res/drawable-hdpi/image_not_loaded.png b/main/res/drawable-hdpi/image_not_loaded.png Binary files differdeleted file mode 100644 index f37377c..0000000 --- a/main/res/drawable-hdpi/image_not_loaded.png +++ /dev/null diff --git a/main/res/drawable-hdpi/my_location.png b/main/res/drawable-hdpi/my_location.png Binary files differdeleted file mode 100644 index cdb58c7..0000000 --- a/main/res/drawable-hdpi/my_location.png +++ /dev/null diff --git a/main/res/drawable-hdpi/my_location_arrow.png b/main/res/drawable-hdpi/my_location_arrow.png Binary files differdeleted file mode 100644 index c8401d2..0000000 --- a/main/res/drawable-hdpi/my_location_arrow.png +++ /dev/null diff --git a/main/res/drawable/image_not_loaded.png b/main/res/drawable/image_not_loaded.png Binary files differindex f37377c..ce7c6d8 100644 --- a/main/res/drawable/image_not_loaded.png +++ b/main/res/drawable/image_not_loaded.png diff --git a/main/res/layout/init.xml b/main/res/layout/init.xml index 40ba0ce..910db5b 100644 --- a/main/res/layout/init.xml +++ b/main/res/layout/init.xml @@ -218,6 +218,77 @@ android:textColor="?text_color" android:text="@string/init_sigautoinsert" /> </LinearLayout> + <RelativeLayout style="@style/separator_horizontal_layout" > + <View style="@style/separator_horizontal" /> + <TextView style="@style/separator_horizontal_headline" + android:text="@string/init_details" /> + </RelativeLayout> + <LinearLayout + android:layout_margin="3dip" android:padding="3dip" android:layout_width="fill_parent" android:orientation="vertical" android:layout_height="fill_parent"> + <LinearLayout + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" > + <CheckBox android:id="@+id/autoload" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentLeft="true" + android:layout_gravity="left" + android:padding="1px" + android:gravity="center" /> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:gravity="left" + android:paddingRight="3dip" + android:textSize="14dip" + android:textColor="?text_color" + android:text="@string/init_autoload" /> + </LinearLayout> + <LinearLayout + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" > + <CheckBox android:id="@+id/ratingwanted" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentLeft="true" + android:layout_gravity="left" + android:padding="1px" + android:gravity="center" /> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:gravity="left" + android:paddingRight="3dip" + android:textSize="14dip" + android:textColor="?text_color" + android:text="@string/init_ratingwanted" /> + </LinearLayout> + <LinearLayout + android:layout_width="fill_parent" + android:layout_height="wrap_content" + android:orientation="horizontal" > + <CheckBox android:id="@+id/elevationwanted" + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_alignParentLeft="true" + android:layout_gravity="left" + android:padding="1px" + android:gravity="center" /> + <TextView + android:layout_width="wrap_content" + android:layout_height="wrap_content" + android:layout_gravity="center_vertical" + android:gravity="left" + android:paddingRight="3dip" + android:textSize="14dip" + android:textColor="?text_color" + android:text="@string/init_elevationwanted" /> + </LinearLayout> + </LinearLayout> <!-- ** --> <RelativeLayout style="@style/separator_horizontal_layout" > <View style="@style/separator_horizontal" /> @@ -486,27 +557,6 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > - <CheckBox android:id="@+id/autoload" - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_alignParentLeft="true" - android:layout_gravity="left" - android:padding="1px" - android:gravity="center" /> - <TextView - android:layout_width="wrap_content" - android:layout_height="wrap_content" - android:layout_gravity="center_vertical" - android:gravity="left" - android:paddingRight="3dip" - android:textSize="14dip" - android:textColor="?text_color" - android:text="@string/init_autoload" /> - </LinearLayout> - <LinearLayout - android:layout_width="fill_parent" - android:layout_height="wrap_content" - android:orientation="horizontal" > <CheckBox android:id="@+id/livelist" android:layout_width="wrap_content" android:layout_height="wrap_content" diff --git a/main/res/values-de/strings.xml b/main/res/values-de/strings.xml index 9fe2466..ea0ab0c 100644 --- a/main/res/values-de/strings.xml +++ b/main/res/values-de/strings.xml @@ -234,7 +234,7 @@ <string name="menu_settings">Einstellungen</string> <string name="menu_history">Verlauf</string> <string name="menu_filter">Filter</string> - <string name="menu_scan">QR-Code scannen</string> + <string name="menu_scan_geo">Geocode scannen</string> <!-- main screen --> <string name="live_map_button">Live-Karte</string> @@ -362,6 +362,8 @@ <string name="init_signature_template_datetime">Datum & Zeit</string> <string name="init_signature_template_user">Benutzer</string> <string name="init_signature_template_number">Nummer</string> + <string name="init_details">Cache Details</string> + <string name="init_autoload">Ausführliche Beschreibung automatisch laden</string> <string name="init_other">Weitere Optionen</string> <string name="init_skin">Helle Oberfläche (Neustart erforderlich)</string> <string name="init_address">Position am Startbildschirm anzeigen</string> @@ -375,7 +377,6 @@ <string name="init_save_log_img">Logbilder abspeichern</string> <string name="init_units">Imperiale Einheiten (Meilen/Fuß)</string> <string name="init_nav">Google Navigation verwenden</string> - <string name="init_autoload">Ausführliche Beschreibung automatisch laden</string> <string name="init_livelist">Richtung zum Cache in der Cache-Liste anzeigen</string> <string name="init_log_offline">Offline loggen (Dialog für Online-Log nicht anzeigen)</string> <string name="init_browser">c:geo als normalen Internet-Browser tarnen</string> diff --git a/main/res/values-fr/strings.xml b/main/res/values-fr/strings.xml index 40b9b7d..962d21a 100644 --- a/main/res/values-fr/strings.xml +++ b/main/res/values-fr/strings.xml @@ -236,7 +236,6 @@ <string name="menu_settings">Paramètres</string> <string name="menu_history">Historique</string> <string name="menu_filter">Filtre</string> - <string name="menu_scan">QR code</string> <!-- main screen --> <string name="live_map_button">Carte</string> @@ -364,6 +363,10 @@ <string name="init_signature_template_datetime">Date & Heure</string> <string name="init_signature_template_user">Utilisateur</string> <string name="init_signature_template_number">Nombre</string> + <string name="init_details">Détails des caches</string> + <string name="init_ratingwanted">Charger la note depuis GCvote.com</string> + <string name="init_elevationwanted">Charger l\'altitude de la cache</string> + <string name="init_autoload">Afficher automatiquement les descriptions longues</string> <string name="init_other">Autres options</string> <string name="init_skin">Aspect sobre (nécessite le redémarrage de c:geo)</string> <string name="init_address">Afficher l\'adresse sur l\'accueil</string> @@ -377,7 +380,6 @@ <string name="init_save_log_img">Sauver les images des visites</string> <string name="init_units">Utiliser des unités de distance impériales</string> <string name="init_nav">Utiliser Google Navigation</string> - <string name="init_autoload">Chargement automatique des descriptions longues</string> <string name="init_log_offline">Toujours utiliser le mode hors-ligne, même si connecté.</string> <string name="init_livelist">Afficher la direction des caches dans les listes</string> <string name="init_browser">Identifier c:geo comme navigateur standard</string> diff --git a/main/res/values-hu/strings.xml b/main/res/values-hu/strings.xml index 47f8694..76d17f9 100644 --- a/main/res/values-hu/strings.xml +++ b/main/res/values-hu/strings.xml @@ -232,7 +232,6 @@ <string name="menu_settings">Beállítások</string> <string name="menu_history">Előzmények</string> <string name="menu_filter">Szűrő</string> - <string name="menu_scan">Vonalkód beolvasása</string> <!-- main screen --> <string name="live_map_button">Élő térkép</string> diff --git a/main/res/values-nl/strings.xml b/main/res/values-nl/strings.xml index ec5d023..ec41687 100644 --- a/main/res/values-nl/strings.xml +++ b/main/res/values-nl/strings.xml @@ -235,7 +235,6 @@ <string name="menu_settings">Instellingen</string> <string name="menu_history">Geschiedenis</string> <string name="menu_filter">Filter</string> - <string name="menu_scan">Scan QR code</string> <!-- main screen --> <string name="live_map_button">Live map</string> diff --git a/main/res/values-sk/strings.xml b/main/res/values-sk/strings.xml index 96f10fa..e45f293 100644 --- a/main/res/values-sk/strings.xml +++ b/main/res/values-sk/strings.xml @@ -236,7 +236,6 @@ <string name="menu_settings">Nastavenia</string> <string name="menu_history">História</string> <string name="menu_filter">Filter</string> - <string name="menu_scan">Snímať QR kód</string> <!-- main screen --> <string name="live_map_button">Aktívna mapa</string> diff --git a/main/res/values-sv/strings.xml b/main/res/values-sv/strings.xml index 2b992b4..90a0d39 100644 --- a/main/res/values-sv/strings.xml +++ b/main/res/values-sv/strings.xml @@ -235,7 +235,6 @@ <string name="menu_settings">Inställningar</string> <string name="menu_history">Loggade cacher</string> <string name="menu_filter">Filter</string> - <string name="menu_scan">Scanna QR kod</string> <!-- main screen --> <string name="live_map_button">Live karta</string> diff --git a/main/res/values/strings.xml b/main/res/values/strings.xml index f283702..007825b 100644 --- a/main/res/values/strings.xml +++ b/main/res/values/strings.xml @@ -236,7 +236,7 @@ <string name="menu_settings">Settings</string> <string name="menu_history">History</string> <string name="menu_filter">Filter</string> - <string name="menu_scan">Scan QR code</string> + <string name="menu_scan_geo">Scan geo code</string> <!-- main screen --> <string name="live_map_button">Live map</string> @@ -248,9 +248,10 @@ <!-- caches --> <string name="caches_no_cache">There is no cache</string> - <string name="caches_more_caches">Not enough? Get more caches!</string> - <string name="caches_more_caches_no">That\'s all. No more caches.</string> + <string name="caches_more_caches">Load more caches</string> + <string name="caches_more_caches_no">No more caches</string> <string name="caches_more_caches_loading">Loading caches…</string> + <string name="caches_more_caches_currently">currently</string> <string name="caches_downloading">Downloading caches…\nETA: </string> <string name="caches_eta_ltm">Less than a minute</string> <string name="caches_eta_mins"> minutes</string> @@ -364,6 +365,10 @@ <string name="init_signature_template_datetime">Date & Time</string> <string name="init_signature_template_user">User</string> <string name="init_signature_template_number">Number</string> + <string name="init_details">Cache details</string> + <string name="init_ratingwanted">Load cache rating from GCvote.com</string> + <string name="init_elevationwanted">Load cache elevation data</string> + <string name="init_autoload">Auto-loading long description</string> <string name="init_other">Other options</string> <string name="init_skin">Light skin\n(needs restart of c:geo)</string> <string name="init_address">Show address on mainscreen</string> @@ -377,7 +382,6 @@ <string name="init_save_log_img">Save Images from Logs</string> <string name="init_units">Use miles/feet\n(imperial units)</string> <string name="init_nav">Use Google Navigation</string> - <string name="init_autoload">Auto-loading long description</string> <string name="init_log_offline">When logging, always log offline (don\'t show online log screen when logging, don\'t send the log online)</string> <string name="init_livelist">Show direction to caches in its list</string> <string name="init_browser">Identify c:geo as standard browser</string> @@ -926,6 +930,8 @@ <!-- changelog --> <string name="changelog">\n + <b>New release</b>\n + \n\n <b>31.10.2011</b>\n · fix: Store for offline from Live map\n \n\n diff --git a/main/src/cgeo/geocaching/GCVote.java b/main/src/cgeo/geocaching/GCVote.java index ae23087..f136aa9 100644 --- a/main/src/cgeo/geocaching/GCVote.java +++ b/main/src/cgeo/geocaching/GCVote.java @@ -161,7 +161,7 @@ public final class GCVote { if (!cache.supportsGCVote()) { return false; } - String guid = cache.guid; + String guid = cache.getGuid(); if (StringUtils.isBlank(guid)) { return false; } diff --git a/main/src/cgeo/geocaching/IBasicCache.java b/main/src/cgeo/geocaching/IBasicCache.java new file mode 100644 index 0000000..88b78ca --- /dev/null +++ b/main/src/cgeo/geocaching/IBasicCache.java @@ -0,0 +1,51 @@ +/** + * + */ +package cgeo.geocaching; + +import cgeo.geocaching.enumerations.CacheSize; +import cgeo.geocaching.enumerations.CacheType; + + +/** + * @author blafoo + * + */ +public interface IBasicCache extends ILogable { + + public abstract String getGuid(); + + /** + * @return Tradi, multi etc. + */ + public abstract CacheType getCacheType(); + + /** + * @return Micro, small etc. + */ + public abstract CacheSize getSize(); + + /** + * @return true if the user already found the cache + * + */ + public abstract boolean isFound(); + + /** + * @return true if the cache is disabled, false else + */ + public abstract boolean isDisabled(); + + /** + * @return Difficulty assessment + */ + public abstract Float getDifficulty(); + + /** + * @return Terrain assessment + */ + public abstract Float getTerrain(); + + + +} diff --git a/main/src/cgeo/geocaching/ICache.java b/main/src/cgeo/geocaching/ICache.java index f1f94e5..6f87dc4 100644 --- a/main/src/cgeo/geocaching/ICache.java +++ b/main/src/cgeo/geocaching/ICache.java @@ -3,8 +3,6 @@ */ package cgeo.geocaching; -import cgeo.geocaching.enumerations.CacheSize; - import java.util.Date; import java.util.List; import java.util.Map; @@ -15,17 +13,7 @@ import java.util.Map; * @author blafoo * */ -public interface ICache { - - /** - * @return Geocode like GCxxxx - */ - public String getGeocode(); - - /** - * @return Tradi, multi etc. - */ - public String getType(); +public interface ICache extends IBasicCache { /** * @return Displayed owner, might differ from the real owner @@ -38,21 +26,6 @@ public interface ICache { public String getOwnerReal(); /** - * @return Micro, small etc. - */ - public CacheSize getSize(); - - /** - * @return Difficulty assessment - */ - public Float getDifficulty(); - - /** - * @return Terrain assessment - */ - public Float getTerrain(); - - /** * @return Latitude, e.g. N 52° 12.345 */ public String getLatitude(); @@ -63,11 +36,6 @@ public interface ICache { public String getLongitude(); /** - * @return true if the cache is disabled, false else - */ - public boolean isDisabled(); - - /** * @return true if the user is the owner of the cache, false else */ public boolean isOwn(); @@ -97,10 +65,6 @@ public interface ICache { */ public String getShortDescription(); - /** - * @return Name - */ - public String getName(); /** * @return Id @@ -122,11 +86,6 @@ public interface ICache { */ public String getPersonalNote(); - /** - * @return true if the user already found the cache - * - */ - public boolean isFound(); /** * @return true if the user gave a favorite point to the cache @@ -174,7 +133,7 @@ public interface ICache { /** * get the name for lexicographical sorting. - * + * * @return normalized, cached name which sort also correct for numerical parts in the name */ public String getNameForSorting(); diff --git a/main/src/cgeo/geocaching/ILogable.java b/main/src/cgeo/geocaching/ILogable.java new file mode 100644 index 0000000..6c793fc --- /dev/null +++ b/main/src/cgeo/geocaching/ILogable.java @@ -0,0 +1,23 @@ +/** + * + */ +package cgeo.geocaching; + + +/** + * @author blafoo + * + */ +public interface ILogable { + + /** + * @return Geocode like GCxxxx + */ + public abstract String getGeocode(); + + /** + * @return Name + */ + public abstract String getName(); + +} diff --git a/main/src/cgeo/geocaching/IWaypoint.java b/main/src/cgeo/geocaching/IWaypoint.java new file mode 100644 index 0000000..5fbbfb4 --- /dev/null +++ b/main/src/cgeo/geocaching/IWaypoint.java @@ -0,0 +1,21 @@ +/** + * + */ +package cgeo.geocaching; + +import cgeo.geocaching.enumerations.WaypointType; +import cgeo.geocaching.geopoint.Geopoint; + +/** + * @author blafoo + * + */ +public interface IWaypoint extends ILogable { + + public abstract Integer getId(); + + public abstract Geopoint getCoords(); + + public abstract WaypointType getWaypointType(); + +} diff --git a/main/src/cgeo/geocaching/Settings.java b/main/src/cgeo/geocaching/Settings.java index 2b377de..4da2314 100644 --- a/main/src/cgeo/geocaching/Settings.java +++ b/main/src/cgeo/geocaching/Settings.java @@ -45,6 +45,8 @@ public final class Settings { private static final String KEY_TWITTER_TOKEN_PUBLIC = "tokenpublic"; private static final String KEY_VERSION = "version"; private static final String KEY_LOAD_DESCRIPTION = "autoloaddesc"; + private static final String KEY_RATING_WANTED = "ratingwanted"; + private static final String KEY_ELEVATION_WANTED = "elevationwanted"; private static final String KEY_USE_ENGLISH = "useenglish"; private static final String KEY_AS_BROWSER = "asbrowser"; private static final String KEY_USE_COMPASS = "usecompass"; @@ -137,13 +139,9 @@ public final class Settings { // this class is not to be instantiated; } - static void setLanguage(boolean useEnglish) { - Locale locale = Locale.getDefault(); - if (useEnglish) { - locale = new Locale("en"); - } + public static void setLanguage(boolean useEnglish) { final Configuration config = new Configuration(); - config.locale = locale; + config.locale = useEnglish ? new Locale("en") : Locale.getDefault(); final Resources resources = cgeoapplication.getInstance().getResources(); resources.updateConfiguration(config, resources.getDisplayMetrics()); } @@ -572,6 +570,34 @@ public final class Settings { }); } + public static boolean isRatingWanted() { + return sharedPrefs.getBoolean(KEY_RATING_WANTED, true); + } + + public static void setRatingWanted(final boolean ratingWanted) { + editSharedSettings(new PrefRunnable() { + + @Override + public void edit(Editor edit) { + edit.putBoolean(KEY_RATING_WANTED, ratingWanted); + } + }); + } + + public static boolean isElevationWanted() { + return sharedPrefs.getBoolean(KEY_ELEVATION_WANTED, true); + } + + public static void setElevationWanted(final boolean elevationWanted) { + editSharedSettings(new PrefRunnable() { + + @Override + public void edit(Editor edit) { + edit.putBoolean(KEY_ELEVATION_WANTED, elevationWanted); + } + }); + } + public static boolean isLiveList() { return 0 != sharedPrefs.getInt(KEY_LIVE_LIST, 1); } diff --git a/main/src/cgeo/geocaching/StaticMapsProvider.java b/main/src/cgeo/geocaching/StaticMapsProvider.java index 96d7222..5a968c2 100644 --- a/main/src/cgeo/geocaching/StaticMapsProvider.java +++ b/main/src/cgeo/geocaching/StaticMapsProvider.java @@ -39,7 +39,7 @@ public class StaticMapsProvider { final String url = mapUrl + "&zoom=" + zoom + "&size=" + edge + "x" + edge + "&maptype=" + mapType + "&markers=icon%3A" + markerUrl + "%7C" + latlonMap + waypoints + "&sensor=false"; - final File file = getMapFile(cache.geocode, level); + final File file = getMapFile(cache.getGeocode(), level); final HttpResponse httpResponse = cgBase.request(url, null, false); if (httpResponse != null) { @@ -54,12 +54,12 @@ public class StaticMapsProvider { } public static void downloadMaps(cgCache cache, Activity activity) { - if (!Settings.isStoreOfflineMaps() || cache.coords == null || StringUtils.isBlank(cache.geocode)) { + if (!Settings.isStoreOfflineMaps() || cache.getCoords() == null || StringUtils.isBlank(cache.getGeocode())) { return; } - final String latlonMap = String.format((Locale) null, "%.6f", cache.coords.getLatitude()) + "," + - String.format((Locale) null, "%.6f", cache.coords.getLongitude()); + final String latlonMap = String.format((Locale) null, "%.6f", cache.getCoords().getLatitude()) + "," + + String.format((Locale) null, "%.6f", cache.getCoords().getLongitude()); final Display display = ((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; @@ -71,20 +71,20 @@ public class StaticMapsProvider { } final StringBuilder waypoints = new StringBuilder(); - if (CollectionUtils.isNotEmpty(cache.waypoints)) { - for (cgWaypoint waypoint : cache.waypoints) { - if (waypoint.coords == null) { + if (CollectionUtils.isNotEmpty(cache.getWaypoints())) { + for (cgWaypoint waypoint : cache.getWaypoints()) { + if (waypoint.getCoords() == null) { continue; } waypoints.append("&markers=icon%3A"); waypoints.append(MARKERS_URL); waypoints.append("marker_waypoint_"); - waypoints.append(waypoint.type != null ? waypoint.type.id : null); + waypoints.append(waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); waypoints.append(".png%7C"); - waypoints.append(String.format((Locale) null, "%.6f", waypoint.coords.getLatitude())); + waypoints.append(String.format((Locale) null, "%.6f", waypoint.getCoords().getLatitude())); waypoints.append(','); - waypoints.append(String.format((Locale) null, "%.6f", waypoint.coords.getLongitude())); + waypoints.append(String.format((Locale) null, "%.6f", waypoint.getCoords().getLongitude())); } } @@ -106,12 +106,12 @@ public class StaticMapsProvider { private static String getMarkerUrl(final cgCache cache) { String type; - if (cache.found) { - type = cache.type + "_found"; - } else if (cache.disabled) { - type = cache.type + "_disabled"; + if (cache.isFound()) { + type = cache.getType() + "_found"; + } else if (cache.isDisabled()) { + type = cache.getType() + "_disabled"; } else { - type = cache.type; + type = cache.getType(); } return cgBase.urlencode_rfc3986(MARKERS_URL + "marker_cache_" + type + ".png"); diff --git a/main/src/cgeo/geocaching/activity/Progress.java b/main/src/cgeo/geocaching/activity/Progress.java index ddb98b2..6edf23e 100644 --- a/main/src/cgeo/geocaching/activity/Progress.java +++ b/main/src/cgeo/geocaching/activity/Progress.java @@ -2,6 +2,7 @@ package cgeo.geocaching.activity; import android.app.ProgressDialog; import android.content.Context; +import android.os.Message; /** * progress dialog wrapper for easier management of resources @@ -17,9 +18,12 @@ public class Progress { dialog = null; } - public synchronized void show(Context context, String title, String message, boolean indeterminate, boolean cancelable) { + public synchronized void show(final Context context, final String title, final String message, final boolean indeterminate, final Message cancelMessage) { if (dialog == null) { - dialog = ProgressDialog.show(context, title, message, indeterminate, cancelable); + dialog = ProgressDialog.show(context, title, message, indeterminate, cancelMessage != null); + if (cancelMessage != null) { + dialog.setCancelMessage(cancelMessage); + } } } diff --git a/main/src/cgeo/geocaching/apps/AbstractLocusApp.java b/main/src/cgeo/geocaching/apps/AbstractLocusApp.java index 96808b0..d1dda2a 100644 --- a/main/src/cgeo/geocaching/apps/AbstractLocusApp.java +++ b/main/src/cgeo/geocaching/apps/AbstractLocusApp.java @@ -100,60 +100,60 @@ public abstract class AbstractLocusApp extends AbstractApp { * @author koem */ private static Point getPoint(cgCache cache, boolean withWaypoints) { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { return null; } // create one simple point with location Location loc = new Location(Settings.tag); - loc.setLatitude(cache.coords.getLatitude()); - loc.setLongitude(cache.coords.getLongitude()); + loc.setLatitude(cache.getCoords().getLatitude()); + loc.setLongitude(cache.getCoords().getLongitude()); - Point p = new Point(cache.name, loc); + Point p = new Point(cache.getName(), loc); PointGeocachingData pg = new PointGeocachingData(); p.setGeocachingData(pg); // set data in Locus' cache - pg.cacheID = cache.geocode; - pg.available = !cache.disabled; - pg.archived = cache.archived; - pg.premiumOnly = cache.members; - pg.name = cache.name; - pg.placedBy = cache.owner; - if (cache.hidden != null) { - pg.hidden = ISO8601DATE.format(cache.hidden.getTime()); + pg.cacheID = cache.getGeocode(); + pg.available = !cache.isDisabled(); + pg.archived = cache.isArchived(); + pg.premiumOnly = cache.isMembers(); + pg.name = cache.getName(); + pg.placedBy = cache.getOwner(); + if (cache.getHidden() != null) { + pg.hidden = ISO8601DATE.format(cache.getHidden().getTime()); } - int locusId = toLocusId(CacheType.FIND_BY_ID.get(cache.type)); + int locusId = toLocusId(cache.getCacheType()); if (locusId != NO_LOCUS_ID) { pg.type = locusId; } - locusId = toLocusId(cache.size); + locusId = toLocusId(cache.getSize()); if (locusId != NO_LOCUS_ID) { pg.container = locusId; } - if (cache.difficulty != null) { - pg.difficulty = cache.difficulty; + if (cache.getDifficulty() != null) { + pg.difficulty = cache.getDifficulty(); } - if (cache.terrain != null) { - pg.terrain = cache.terrain; + if (cache.getTerrain() != null) { + pg.terrain = cache.getTerrain(); } - pg.found = cache.found; + pg.found = cache.isFound(); - if (withWaypoints && cache.waypoints != null) { + if (withWaypoints && cache.getWaypoints() != null) { pg.waypoints = new ArrayList<PointGeocachingDataWaypoint>(); - for (cgWaypoint waypoint : cache.waypoints) { - if (waypoint == null || waypoint.coords == null) { + for (cgWaypoint waypoint : cache.getWaypoints()) { + if (waypoint == null || waypoint.getCoords() == null) { continue; } PointGeocachingDataWaypoint wp = new PointGeocachingDataWaypoint(); - wp.code = waypoint.geocode; - wp.name = waypoint.name; - String locusWpId = toLocusId(waypoint.type); + wp.code = waypoint.getGeocode(); + wp.name = waypoint.getName(); + String locusWpId = toLocusId(waypoint.getWaypointType()); if (locusWpId != null) { wp.type = locusWpId; } - wp.lat = waypoint.coords.getLatitude(); - wp.lon = waypoint.coords.getLongitude(); + wp.lat = waypoint.getCoords().getLatitude(); + wp.lon = waypoint.getCoords().getLongitude(); pg.waypoints.add(wp); } } @@ -163,7 +163,7 @@ public abstract class AbstractLocusApp extends AbstractApp { // Examination necessary when to display and when not. E. g.: > 200 caches: don't display // these properties. - //pg.shortDescription = cache.shortdesc; + //pg.getShortdesc()ription = cache.getShortdesc(); //pg.longDescription = cache.description; //pg.encodedHints = cache.hint; @@ -178,18 +178,18 @@ public abstract class AbstractLocusApp extends AbstractApp { * @author koem */ private static Point getPoint(cgWaypoint waypoint) { - if (waypoint == null || waypoint.coords == null) { + if (waypoint == null || waypoint.getCoords() == null) { return null; } // create one simple point with location Location loc = new Location(Settings.tag); - loc.setLatitude(waypoint.coords.getLatitude()); - loc.setLongitude(waypoint.coords.getLongitude()); + loc.setLatitude(waypoint.getCoords().getLatitude()); + loc.setLongitude(waypoint.getCoords().getLongitude()); - Point p = new Point(waypoint.name, loc); + Point p = new Point(waypoint.getName(), loc); p.setDescription("<a href=\"" + waypoint.getUrl() + "\">" - + waypoint.geocode + "</a>"); + + waypoint.getGeocode() + "</a>"); return p; } diff --git a/main/src/cgeo/geocaching/apps/cache/WhereYouGoApp.java b/main/src/cgeo/geocaching/apps/cache/WhereYouGoApp.java index d006571..8a4b02e 100644 --- a/main/src/cgeo/geocaching/apps/cache/WhereYouGoApp.java +++ b/main/src/cgeo/geocaching/apps/cache/WhereYouGoApp.java @@ -13,6 +13,6 @@ class WhereYouGoApp extends AbstractGeneralApp implements GeneralApp { @Override public boolean isEnabled(cgCache cache) { - return cache != null && cache.type != null && cache.type.equalsIgnoreCase(CacheType.WHERIGO.id); + return cache != null && cache.getType() != null && cache.getType().equalsIgnoreCase(CacheType.WHERIGO.id); } } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsApp.java index 961773f..30a3b4b 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsApp.java @@ -1,9 +1,10 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; +import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; -import cgeo.geocaching.Settings; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; @@ -15,8 +16,6 @@ import android.content.res.Resources; import android.net.Uri; import android.util.Log; -import java.util.UUID; - class GoogleMapsApp extends AbstractNavigationApp implements NavigationApp { GoogleMapsApp(final Resources res) { @@ -30,16 +29,16 @@ class GoogleMapsApp extends AbstractNavigationApp implements NavigationApp { public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } try { - if (cache != null && cache.coords != null) { - startActivity(activity, cache.coords); - } else if (waypoint != null && waypoint.coords != null) { - startActivity(activity, waypoint.coords); + if (cache != null && cache.getCoords() != null) { + startActivity(activity, cache.getCoords()); + } else if (waypoint != null && waypoint.getCoords() != null) { + startActivity(activity, waypoint.getCoords()); } else if (coords != null) { startActivity(activity, coords); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java index 44a4cbd..ad96be3 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java @@ -1,9 +1,10 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; +import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; -import cgeo.geocaching.Settings; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; @@ -15,8 +16,6 @@ import android.content.res.Resources; import android.net.Uri; import android.util.Log; -import java.util.UUID; - class GoogleNavigationApp extends AbstractNavigationApp implements NavigationApp { @@ -32,7 +31,7 @@ class GoogleNavigationApp extends AbstractNavigationApp implements @Override public boolean invoke(final cgGeo geo, final Activity activity, final Resources res, final cgCache cache, - final UUID searchId, final cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, final cgWaypoint waypoint, final Geopoint coords) { if (activity == null) { return false; } @@ -42,10 +41,10 @@ class GoogleNavigationApp extends AbstractNavigationApp implements navigationResult = navigateToCoordinates(geo, activity, coords); } else if (waypoint != null) { - navigationResult = navigateToCoordinates(geo, activity, waypoint.coords); + navigationResult = navigateToCoordinates(geo, activity, waypoint.getCoords()); } else if (cache != null) { - navigationResult = navigateToCoordinates(geo, activity, cache.coords); + navigationResult = navigateToCoordinates(geo, activity, cache.getCoords()); } if (!navigationResult) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java index 0594558..9192d16 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; @@ -11,8 +12,6 @@ import cgeo.geocaching.maps.CGeoMap; import android.app.Activity; import android.content.res.Resources; -import java.util.UUID; - class InternalMap extends AbstractInternalMap implements NavigationApp { @@ -23,18 +22,18 @@ class InternalMap extends AbstractInternalMap implements @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { - if (searchId != null) { - CGeoMap.startActivitySearch(activity, searchId, cache != null ? cache.geocode : null, true); + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { + if (search != null) { + CGeoMap.startActivitySearch(activity, search, cache != null ? cache.getGeocode() : null, true); } else if (cache != null) { - CGeoMap.startActivityGeoCode(activity, cache.geocode); + CGeoMap.startActivityGeoCode(activity, cache.getGeocode()); } else if (waypoint != null) { - CGeoMap.startActivityCoords(activity, waypoint.coords, waypoint.type); + CGeoMap.startActivityCoords(activity, waypoint.getCoords(), waypoint.getWaypointType(), waypoint.getName()); } else if (coords != null) { - CGeoMap.startActivityCoords(activity, coords, WaypointType.WAYPOINT); + CGeoMap.startActivityCoords(activity, coords, WaypointType.WAYPOINT, null); } return true; diff --git a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java index 305ded2..544ad33 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java @@ -2,6 +2,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.apps.AbstractLocusApp; import cgeo.geocaching.geopoint.Geopoint; @@ -10,7 +11,6 @@ import android.app.Activity; import android.content.res.Resources; import java.util.ArrayList; -import java.util.UUID; class LocusApp extends AbstractLocusApp implements NavigationApp { @@ -27,7 +27,7 @@ class LocusApp extends AbstractLocusApp implements NavigationApp { */ @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; @@ -37,12 +37,12 @@ class LocusApp extends AbstractLocusApp implements NavigationApp { final ArrayList<Object> points = new ArrayList<Object>(); // add cache if present - if (cache != null && cache.coords != null) { + if (cache != null && cache.getCoords() != null) { points.add(cache); } // add waypoint if present - if (waypoint != null && waypoint.coords != null) { + if (waypoint != null && waypoint.getCoords() != null) { points.add(waypoint); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java index ef0a578..f52cc42 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java @@ -2,6 +2,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.apps.App; import cgeo.geocaching.geopoint.Geopoint; @@ -9,12 +10,10 @@ import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; import android.content.res.Resources; -import java.util.UUID; - interface NavigationApp extends App { public boolean invoke(final cgGeo geo, final Activity activity, final Resources res, final cgCache cache, - final UUID searchId, final cgWaypoint waypoint, + final cgSearch search, final cgWaypoint waypoint, final Geopoint coords); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java index 1ee7c23..56bcb5d 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.geopoint.Geopoint; @@ -15,8 +16,6 @@ import android.util.Log; import android.view.Menu; import android.view.MenuItem; -import java.util.UUID; - public final class NavigationAppFactory extends AbstractAppFactory { private static NavigationApp[] apps = new NavigationApp[] {}; @@ -56,12 +55,12 @@ public final class NavigationAppFactory extends AbstractAppFactory { public static boolean onMenuItemSelected(final MenuItem item, final cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint destination) { + final cgSearch search, cgWaypoint waypoint, final Geopoint destination) { NavigationApp app = (NavigationApp) getAppFromMenuItem(item, apps); if (app != null) { try { return app.invoke(geo, activity, res, cache, - searchId, waypoint, destination); + search, waypoint, destination); } catch (Exception e) { Log.e(Settings.tag, "NavigationAppFactory.onMenuItemSelected: " + e.toString()); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/OruxMapsApp.java b/main/src/cgeo/geocaching/apps/cache/navi/OruxMapsApp.java index 71430ae..09bf9e7 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/OruxMapsApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/OruxMapsApp.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; @@ -10,8 +11,6 @@ import android.app.Activity; import android.content.Intent; import android.content.res.Resources; -import java.util.UUID; - class OruxMapsApp extends AbstractNavigationApp implements NavigationApp { private static final String INTENT = "com.oruxmaps.VIEW_MAP_ONLINE"; @@ -23,7 +22,7 @@ class OruxMapsApp extends AbstractNavigationApp implements NavigationApp { @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } @@ -49,10 +48,10 @@ class OruxMapsApp extends AbstractNavigationApp implements NavigationApp { private static Geopoint getCoords(cgCache cache, cgWaypoint waypoint, Geopoint coords) { if (cache != null) { - return cache.coords; + return cache.getCoords(); } else if (waypoint != null) { - return waypoint.coords; + return waypoint.getCoords(); } return coords; } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java index 2d27493..cb0b520 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; @@ -12,9 +13,8 @@ import android.content.res.Resources; import java.util.ArrayList; import java.util.Locale; -import java.util.UUID; -class RMapsApp extends AbstractNavigationApp implements NavigationApp { +class RMapsApp extends AbstractNavigationApp { private static final String INTENT = "com.robert.maps.action.SHOW_POINTS"; @@ -25,7 +25,7 @@ class RMapsApp extends AbstractNavigationApp implements NavigationApp { @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } @@ -33,24 +33,24 @@ class RMapsApp extends AbstractNavigationApp implements NavigationApp { try { if (isInstalled(activity)) { final ArrayList<String> locations = new ArrayList<String>(); - if (cache != null && cache.coords != null) { + if (cache != null && cache.getCoords() != null) { locations.add(String.format((Locale) null, "%.6f", - cache.coords.getLatitude()) + cache.getCoords().getLatitude()) + "," + String.format((Locale) null, "%.6f", - cache.coords.getLongitude()) + cache.getCoords().getLongitude()) + ";" - + cache.geocode - + ";" + cache.name); - } else if (waypoint != null && waypoint.coords != null) { + + cache.getGeocode() + + ";" + cache.getName()); + } else if (waypoint != null && waypoint.getCoords() != null) { locations.add(String.format((Locale) null, "%.6f", - waypoint.coords.getLatitude()) + waypoint.getCoords().getLatitude()) + "," + String.format((Locale) null, "%.6f", - waypoint.coords.getLongitude()) + waypoint.getCoords().getLongitude()) + ";" - + waypoint.lookup - + ";" + waypoint.name); + + waypoint.getLookup() + + ";" + waypoint.getName()); } final Intent intent = new Intent(INTENT); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/RadarApp.java b/main/src/cgeo/geocaching/apps/cache/navi/RadarApp.java index 87e6368..40458d5 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/RadarApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/RadarApp.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; @@ -10,8 +11,6 @@ import android.app.Activity; import android.content.Intent; import android.content.res.Resources; -import java.util.UUID; - class RadarApp extends AbstractNavigationApp implements NavigationApp { private static final String INTENT = "com.google.android.radar.SHOW_RADAR"; @@ -35,12 +34,12 @@ class RadarApp extends AbstractNavigationApp implements NavigationApp { @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache != null) { - return navigateTo(activity, cache.coords); + return navigateTo(activity, cache.getCoords()); } if (waypoint != null) { - return navigateTo(activity, waypoint.coords); + return navigateTo(activity, waypoint.getCoords()); } return navigateTo(activity, coords); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java index 0967925..3de37d4 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeosmaps; import cgeo.geocaching.activity.ActivityMixin; @@ -13,8 +14,6 @@ import android.content.Context; import android.content.Intent; import android.content.res.Resources; -import java.util.UUID; - class StaticMapApp extends AbstractNavigationApp implements NavigationApp { @@ -30,16 +29,16 @@ class StaticMapApp extends AbstractNavigationApp implements @Override public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { - if (cache == null || cache.reason == 0) { + if (cache == null || cache.getReason() == 0) { ActivityMixin.showToast(activity, res.getString(R.string.err_detail_no_map_static)); return true; } - if (cache.geocode != null) { + if (cache.getGeocode() != null) { Intent smapsIntent = new Intent(activity, cgeosmaps.class); - smapsIntent.putExtra("geocode", cache.geocode.toUpperCase()); + smapsIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); activity.startActivity(smapsIntent); return true; } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/StreetviewApp.java b/main/src/cgeo/geocaching/apps/cache/navi/StreetviewApp.java index 8dae3c9..5a5a4f5 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/StreetviewApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/StreetviewApp.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cache.navi; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; @@ -14,8 +15,6 @@ import android.content.Intent; import android.content.res.Resources; import android.net.Uri; -import java.util.UUID; - class StreetviewApp extends AbstractNavigationApp implements NavigationApp { StreetviewApp(final Resources res) { @@ -29,16 +28,16 @@ class StreetviewApp extends AbstractNavigationApp implements NavigationApp { public boolean invoke(cgGeo geo, Activity activity, Resources res, cgCache cache, - final UUID searchId, cgWaypoint waypoint, final Geopoint coords) { + final cgSearch search, cgWaypoint waypoint, final Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } try { - if (cache != null && cache.coords != null) { - startActivity(activity, cache.coords); - } else if (waypoint != null && waypoint.coords != null) { - startActivity(activity, waypoint.coords); + if (cache != null && cache.getCoords() != null) { + startActivity(activity, cache.getCoords()); + } else if (waypoint != null && waypoint.getCoords() != null) { + startActivity(activity, waypoint.getCoords()); } else if (coords != null) { startActivity(activity, coords); } diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java index c4d51d2..2788d2b 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java @@ -2,18 +2,18 @@ package cgeo.geocaching.apps.cachelist; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.apps.App; import android.app.Activity; import android.content.res.Resources; import java.util.List; -import java.util.UUID; interface CacheListApp extends App { boolean invoke(final cgGeo geo, final List<cgCache> caches, final Activity activity, final Resources res, - final UUID searchId); + final cgSearch search); } diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java index 5b3dc9a..46ceb8b 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java @@ -1,9 +1,10 @@ package cgeo.geocaching.apps.cachelist; import cgeo.geocaching.R; +import cgeo.geocaching.Settings; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; -import cgeo.geocaching.Settings; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.apps.AbstractAppFactory; import org.apache.commons.lang3.ArrayUtils; @@ -17,7 +18,6 @@ import android.view.SubMenu; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public final class CacheListAppFactory extends AbstractAppFactory { private static CacheListApp[] apps = new CacheListApp[] {}; @@ -64,11 +64,11 @@ public final class CacheListAppFactory extends AbstractAppFactory { public static boolean onMenuItemSelected(final MenuItem item, final cgGeo geo, final List<cgCache> caches, final Activity activity, final Resources res, - final UUID searchId) { + final cgSearch search) { CacheListApp app = (CacheListApp) getAppFromMenuItem(item, apps); if (app != null) { try { - return app.invoke(geo, caches, activity, res, searchId); + return app.invoke(geo, caches, activity, res, search); } catch (Exception e) { Log.e(Settings.tag, "CacheListAppFactory.onMenuItemSelected: " + e.toString()); } diff --git a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java index 6de5c13..3038872 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java +++ b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java @@ -3,6 +3,7 @@ package cgeo.geocaching.apps.cachelist; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.apps.AbstractApp; import cgeo.geocaching.maps.CGeoMap; @@ -11,7 +12,6 @@ import android.content.Context; import android.content.res.Resources; import java.util.List; -import java.util.UUID; class InternalCacheListMap extends AbstractApp implements CacheListApp { @@ -25,8 +25,8 @@ class InternalCacheListMap extends AbstractApp implements CacheListApp { } @Override - public boolean invoke(cgGeo geo, List<cgCache> caches, Activity activity, Resources res, final UUID searchId) { - CGeoMap.startActivitySearch(activity, searchId, null, false); + public boolean invoke(cgGeo geo, List<cgCache> caches, Activity activity, Resources res, final cgSearch search) { + CGeoMap.startActivitySearch(activity, search, null, false); return true; } } diff --git a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java index 4cce8d7..eddd6ac 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java @@ -2,6 +2,7 @@ package cgeo.geocaching.apps.cachelist; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; +import cgeo.geocaching.cgSearch; import cgeo.geocaching.apps.AbstractLocusApp; import org.apache.commons.collections.CollectionUtils; @@ -10,7 +11,6 @@ import android.app.Activity; import android.content.res.Resources; import java.util.List; -import java.util.UUID; class LocusCacheListApp extends AbstractLocusApp implements CacheListApp { @@ -26,7 +26,7 @@ class LocusCacheListApp extends AbstractLocusApp implements CacheListApp { */ @Override public boolean invoke(cgGeo geo, List<cgCache> cacheList, Activity activity, Resources res, - final UUID searchId) { + final cgSearch search) { if (CollectionUtils.isEmpty(cacheList)) { return false; } diff --git a/main/src/cgeo/geocaching/cgBase.java b/main/src/cgeo/geocaching/cgBase.java index 001b704..053119f 100644 --- a/main/src/cgeo/geocaching/cgBase.java +++ b/main/src/cgeo/geocaching/cgBase.java @@ -11,7 +11,9 @@ import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocParser; import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.network.HtmlImage; import cgeo.geocaching.utils.BaseUtils; +import cgeo.geocaching.utils.CancellableHandler; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.MapUtils; @@ -78,7 +80,6 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -89,6 +90,7 @@ public class cgBase { private static final String passMatch = "(?<=[\\?&])[Pp]ass(w(or)?d)?=[^&#$]+"; + @Deprecated public final static Map<String, String> cacheTypes = new HashMap<String, String>(); public final static Map<String, String> cacheIDs = new HashMap<String, String>(); static { @@ -638,27 +640,19 @@ public class cgBase { if (matcherGuidAndDisabled.groupCount() > 0) { guids.add(matcherGuidAndDisabled.group(1)); - cache.guid = matcherGuidAndDisabled.group(1); + cache.setGuid(matcherGuidAndDisabled.group(1)); if (matcherGuidAndDisabled.group(4) != null) { - cache.name = Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString(); + cache.setName(Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString()); } if (matcherGuidAndDisabled.group(6) != null) { - cache.location = Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString(); + cache.setLocation(Html.fromHtml(matcherGuidAndDisabled.group(6).trim()).toString()); } final String attr = matcherGuidAndDisabled.group(2); if (attr != null) { - if (attr.contains("Strike")) { - cache.disabled = true; - } else { - cache.disabled = false; - } + cache.setDisabled(attr.contains("Strike")); - if (attr.contains("OldWarning")) { - cache.archived = true; - } else { - cache.archived = false; - } + cache.setArchived(attr.contains("OldWarning")); } } } @@ -667,7 +661,7 @@ public class cgBase { Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse GUID and/or Disabled data"); } - if (Settings.isExcludeDisabledCaches() && (cache.disabled || cache.archived)) { + if (Settings.isExcludeDisabledCaches() && (cache.isDisabled() || cache.isArchived())) { // skip disabled and archived caches cache = null; continue; @@ -688,7 +682,7 @@ public class cgBase { // The String constructor is necessary as long as the pattern matching doesn't use the // methods from BaseUtil. Otherwise every geocode holds the complete page in memory // FIXME: Use BaseUtil for parsing - cache.geocode = new String(matcherCode.group(1).toUpperCase().trim()); + cache.setGeocode(new String(matcherCode.group(1).toUpperCase().trim())); } } } catch (Exception e) { @@ -701,7 +695,7 @@ public class cgBase { final Matcher matcherCacheType = patternCacheType.matcher(row); while (matcherCacheType.find()) { if (matcherCacheType.groupCount() > 0) { - cache.type = cacheTypes.get(matcherCacheType.group(1).toLowerCase()); + cache.setCacheType(CacheType.getById(matcherCacheType.group(1))); } } } catch (Exception e) { @@ -716,7 +710,7 @@ public class cgBase { final Matcher matcherDirection = patternDirection.matcher(row); while (matcherDirection.find()) { if (matcherDirection.groupCount() > 0) { - cache.directionImg = URLDecoder.decode(matcherDirection.group(1)); + cache.setDirectionImg(URLDecoder.decode(matcherDirection.group(1))); } } } catch (Exception e) { @@ -730,7 +724,7 @@ public class cgBase { final Matcher matcherTbs = patternTbs.matcher(row); while (matcherTbs.find()) { if (matcherTbs.groupCount() > 0) { - cache.inventoryItems = Integer.parseInt(matcherTbs.group(1)); + cache.setInventoryItems(Integer.parseInt(matcherTbs.group(1))); inventoryPre = matcherTbs.group(2); } } @@ -748,8 +742,8 @@ public class cgBase { if (inventoryItem.equals("premium member only cache")) { continue; } else { - if (cache.inventoryItems <= 0) { - cache.inventoryItems = 1; + if (cache.getInventoryItems() <= 0) { + cache.setInventoryItems(1); } } } @@ -761,21 +755,21 @@ public class cgBase { } // premium cache - cache.members = row.contains("/images/small_profile.gif"); + cache.setMembers(row.contains("/images/small_profile.gif")); // found it - cache.found = row.contains("/images/icons/icon_smile"); + cache.setFound(row.contains("/images/icons/icon_smile")); // own it - cache.own = row.contains("/images/silk/star.png"); + cache.setOwn(row.contains("/images/silk/star.png")); // id try { final Matcher matcherId = patternId.matcher(row); while (matcherId.find()) { if (matcherId.groupCount() > 0) { - cache.cacheId = matcherId.group(1); - cids.add(cache.cacheId); + cache.setCacheId(matcherId.group(1)); + cids.add(cache.getCacheId()); } } } catch (Exception e) { @@ -788,7 +782,7 @@ public class cgBase { final Matcher matcherFavourite = patternFavourite.matcher(row); while (matcherFavourite.find()) { if (matcherFavourite.groupCount() > 0) { - cache.favouriteCnt = Integer.parseInt(matcherFavourite.group(1)); + cache.setFavouriteCnt(Integer.parseInt(matcherFavourite.group(1))); } } } catch (Exception e) { @@ -796,10 +790,10 @@ public class cgBase { Log.w(Settings.tag, "cgeoBase.parseSearch: Failed to parse favourite count"); } - if (cache.nameSp == null) { - cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name); - if (cache.disabled || cache.archived) { // strike - cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + if (cache.getNameSp() == null) { + cache.setNameSp((new Spannable.Factory()).newSpannable(cache.getName())); + if (cache.isDisabled() || cache.isArchived()) { // strike + cache.getNameSp().setSpan(new StrikethroughSpan(), 0, cache.getNameSp().toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } @@ -878,33 +872,35 @@ public class cgBase { if (Settings.getLoadDirImg()) { for (cgCache oneCache : caches.cacheList) { - if (oneCache.coords == null && oneCache.directionImg != null) { - cgDirectionImg.getDrawable(oneCache.geocode, oneCache.directionImg); + if (oneCache.getCoords() == null && oneCache.getDirectionImg() != null) { + cgDirectionImg.getDrawable(oneCache.getGeocode(), oneCache.getDirectionImg()); } } } - // get ratings - if (guids.size() > 0) { - Log.i(Settings.tag, "Trying to get ratings for " + cids.size() + " caches"); + if (Settings.isRatingWanted()) { + // get ratings + if (guids.size() > 0) { + Log.i(Settings.tag, "Trying to get ratings for " + cids.size() + " caches"); - try { - final Map<String, cgRating> ratings = GCVote.getRating(guids, null); + try { + final Map<String, cgRating> ratings = GCVote.getRating(guids, null); - if (MapUtils.isNotEmpty(ratings)) { - // save found cache coordinates - for (cgCache oneCache : caches.cacheList) { - if (ratings.containsKey(oneCache.guid)) { - cgRating thisRating = ratings.get(oneCache.guid); + if (MapUtils.isNotEmpty(ratings)) { + // save found cache coordinates + for (cgCache oneCache : caches.cacheList) { + if (ratings.containsKey(oneCache.getGuid())) { + cgRating thisRating = ratings.get(oneCache.getGuid()); - oneCache.rating = thisRating.rating; - oneCache.votes = thisRating.votes; - oneCache.myVote = thisRating.myVote; + oneCache.setRating(thisRating.rating); + oneCache.setVotes(thisRating.votes); + oneCache.setMyVote(thisRating.myVote); + } } } + } catch (Exception e) { + Log.e(Settings.tag, "cgBase.parseSearch.GCvote: " + e.toString()); } - } catch (Exception e) { - Log.e(Settings.tag, "cgBase.parseSearch.GCvote: " + e.toString()); } } @@ -945,40 +941,40 @@ public class cgBase { } final cgCache cacheToAdd = new cgCache(); - cacheToAdd.reliableLatLon = false; - cacheToAdd.geocode = oneCache.getString("gc"); - cacheToAdd.coords = new Geopoint(oneCache.getDouble("lat"), oneCache.getDouble("lon")); - cacheToAdd.name = oneCache.getString("nn"); - cacheToAdd.found = oneCache.getBoolean("f"); - cacheToAdd.own = oneCache.getBoolean("o"); - cacheToAdd.disabled = !oneCache.getBoolean("ia"); + cacheToAdd.setReliableLatLon(false); + cacheToAdd.setGeocode(oneCache.getString("gc")); + cacheToAdd.setCoords(new Geopoint(oneCache.getDouble("lat"), oneCache.getDouble("lon"))); + cacheToAdd.setName(oneCache.getString("nn")); + cacheToAdd.setFound(oneCache.getBoolean("f")); + cacheToAdd.setOwn(oneCache.getBoolean("o")); + cacheToAdd.setDisabled(!oneCache.getBoolean("ia")); int ctid = oneCache.getInt("ctid"); if (ctid == 2) { - cacheToAdd.type = CacheType.TRADITIONAL.id; + cacheToAdd.setCacheType(CacheType.TRADITIONAL); } else if (ctid == 3) { - cacheToAdd.type = CacheType.MULTI.id; + cacheToAdd.setCacheType(CacheType.MULTI); } else if (ctid == 4) { - cacheToAdd.type = CacheType.VIRTUAL.id; + cacheToAdd.setCacheType(CacheType.VIRTUAL); } else if (ctid == 5) { - cacheToAdd.type = CacheType.LETTERBOX.id; + cacheToAdd.setCacheType(CacheType.LETTERBOX); } else if (ctid == 6) { - cacheToAdd.type = CacheType.EVENT.id; + cacheToAdd.setCacheType(CacheType.EVENT); } else if (ctid == 8) { - cacheToAdd.type = CacheType.MYSTERY.id; + cacheToAdd.setCacheType(CacheType.MYSTERY); } else if (ctid == 11) { - cacheToAdd.type = CacheType.WEBCAM.id; + cacheToAdd.setCacheType(CacheType.WEBCAM); } else if (ctid == 13) { - cacheToAdd.type = CacheType.CITO.id; + cacheToAdd.setCacheType(CacheType.CITO); } else if (ctid == 137) { - cacheToAdd.type = CacheType.EARTH.id; + cacheToAdd.setCacheType(CacheType.EARTH); } else if (ctid == 453) { - cacheToAdd.type = CacheType.MEGA_EVENT.id; + cacheToAdd.setCacheType(CacheType.MEGA_EVENT); } else if (ctid == 1858) { - cacheToAdd.type = CacheType.WHERIGO.id; + cacheToAdd.setCacheType(CacheType.WHERIGO); } else if (ctid == 3653) { - cacheToAdd.type = CacheType.LOSTANDFOUND.id; + cacheToAdd.setCacheType(CacheType.LOSTANDFOUND); } else { - cacheToAdd.type = CacheType.UNKNOWN.id; + cacheToAdd.setCacheType(CacheType.UNKNOWN); } caches.cacheList.add(cacheToAdd); @@ -996,19 +992,22 @@ public class cgBase { return caches; } - public static cgCacheWrap parseCache(final String page, final int reason, final Handler handler) { + public static cgCacheWrap parseCache(final String page, final int reason, final CancellableHandler handler) { final cgCacheWrap caches = parseCacheFromText(page, reason, handler); - if (!caches.cacheList.isEmpty()) { + if (caches != null && !caches.cacheList.isEmpty()) { final cgCache cache = caches.cacheList.get(0); getExtraOnlineInfo(cache, page, handler); - cache.updated = System.currentTimeMillis(); - cache.detailedUpdate = cache.updated; - cache.detailed = true; + cache.setUpdated(System.currentTimeMillis()); + cache.setDetailedUpdate(cache.getUpdated()); + cache.setDetailed(true); + } + if (CancellableHandler.isCancelled(handler)) { + return null; } return caches; } - static cgCacheWrap parseCacheFromText(final String page, final int reason, final Handler handler) { + static cgCacheWrap parseCacheFromText(final String page, final int reason, final CancellableHandler handler) { sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details); if (StringUtils.isBlank(page)) { @@ -1034,34 +1033,34 @@ public class cgBase { return caches; } - cache.disabled = page.contains("<li>This cache is temporarily unavailable."); + cache.setDisabled(page.contains("<li>This cache is temporarily unavailable.")); - cache.archived = page.contains("<li>This cache has been archived,"); + cache.setArchived(page.contains("<li>This cache has been archived,")); - cache.members = BaseUtils.matches(page, GCConstants.PATTERN_MEMBERS); + cache.setMembers(BaseUtils.matches(page, GCConstants.PATTERN_MEMBERS)); - cache.favourite = BaseUtils.matches(page, GCConstants.PATTERN_FAVORITE); + cache.setFavourite(BaseUtils.matches(page, GCConstants.PATTERN_FAVORITE)); - cache.reason = reason; + cache.setReason(reason); // cache geocode - cache.geocode = BaseUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.geocode); + cache.setGeocode(BaseUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode())); // cache id - cache.cacheId = BaseUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.cacheId); + cache.setCacheId(BaseUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId())); // cache guid - cache.guid = BaseUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.guid); + cache.setGuid(BaseUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid())); // name - cache.name = Html.fromHtml(BaseUtils.getMatch(page, GCConstants.PATTERN_NAME, true, cache.name)).toString(); + cache.setName(Html.fromHtml(BaseUtils.getMatch(page, GCConstants.PATTERN_NAME, true, cache.getName())).toString()); // owner real name - cache.ownerReal = URLDecoder.decode(BaseUtils.getMatch(page, GCConstants.PATTERN_OWNERREAL, true, cache.ownerReal)); + cache.setOwnerReal(URLDecoder.decode(BaseUtils.getMatch(page, GCConstants.PATTERN_OWNERREAL, true, cache.getOwnerReal()))); final String username = Settings.getUsername(); - if (cache.ownerReal != null && username != null && cache.ownerReal.equalsIgnoreCase(username)) { - cache.own = true; + if (cache.getOwnerReal() != null && username != null && cache.getOwnerReal().equalsIgnoreCase(username)) { + cache.setOwn(true); } int pos = -1; @@ -1087,29 +1086,29 @@ public class cgBase { // cache terrain String result = BaseUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null); if (result != null) { - cache.terrain = new Float(StringUtils.replaceChars(result, '_', '.')); + cache.setTerrain(new Float(StringUtils.replaceChars(result, '_', '.'))); } // cache difficulty result = BaseUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null); if (result != null) { - cache.difficulty = new Float(StringUtils.replaceChars(result, '_', '.')); + cache.setDifficulty(new Float(StringUtils.replaceChars(result, '_', '.'))); } // owner - cache.owner = Html.fromHtml(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER, true, cache.owner)).toString(); + cache.setOwner(Html.fromHtml(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER, true, cache.getOwner())).toString()); // hidden try { String hiddenString = BaseUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null); if (StringUtils.isNotBlank(hiddenString)) { - cache.hidden = parseGcCustomDate(hiddenString); + cache.setHidden(parseGcCustomDate(hiddenString)); } - if (cache.hidden == null) { + if (cache.getHidden() == null) { // event date hiddenString = BaseUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null); if (StringUtils.isNotBlank(hiddenString)) { - cache.hidden = parseGcCustomDate(hiddenString); + cache.setHidden(parseGcCustomDate(hiddenString)); } } } catch (ParseException e) { @@ -1118,34 +1117,34 @@ public class cgBase { } // favourite - cache.favouriteCnt = Integer.parseInt(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0")); + cache.setFavouriteCnt(Integer.parseInt(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); // cache size - cache.size = CacheSize.FIND_BY_ID.get(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id).toLowerCase()); + cache.setSize(CacheSize.FIND_BY_ID.get(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id).toLowerCase())); } // cache found - cache.found = BaseUtils.matches(page, GCConstants.PATTERN_FOUND) || BaseUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE); + cache.setFound(BaseUtils.matches(page, GCConstants.PATTERN_FOUND) || BaseUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE)); // cache type - cache.type = cacheTypes.get(BaseUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.type).toLowerCase()); + cache.setCacheType(CacheType.getByPattern(BaseUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType()))); // on watchlist - cache.onWatchlist = BaseUtils.matches(page, GCConstants.PATTERN_WATCHLIST); + cache.setOnWatchlist(BaseUtils.matches(page, GCConstants.PATTERN_WATCHLIST)); // latitude and longitude - cache.latlon = BaseUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, cache.latlon); - if (StringUtils.isNotEmpty(cache.latlon)) { + cache.setLatlon(BaseUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, cache.getLatlon())); + if (StringUtils.isNotEmpty(cache.getLatlon())) { try { - cache.coords = new Geopoint(cache.latlon); - cache.reliableLatLon = true; + cache.setCoords(new Geopoint(cache.getLatlon())); + cache.setReliableLatLon(true); } catch (Geopoint.GeopointException e) { Log.w(Settings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates: " + e.toString()); } } // cache location - cache.location = BaseUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, cache.location); + cache.setLocation(BaseUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, cache.getLocation())); // cache hint try { @@ -1154,7 +1153,7 @@ public class cgBase { // replace linebreak and paragraph tags String hint = Pattern.compile("<(br|p)[^>]*>").matcher(matcherHint.group(1)).replaceAll("\n"); if (hint != null) { - cache.hint = hint.replaceAll(Pattern.quote("</p>"), "").trim(); + cache.setHint(hint.replaceAll(Pattern.quote("</p>"), "").trim()); } } } catch (Exception e) { @@ -1165,10 +1164,10 @@ public class cgBase { checkFields(cache); // cache personal note - cache.personalNote = BaseUtils.getMatch(page, GCConstants.PATTERN_PERSONALNOTE, true, cache.personalNote); + cache.setPersonalNote(BaseUtils.getMatch(page, GCConstants.PATTERN_PERSONALNOTE, true, cache.getPersonalNote())); // cache short description - cache.shortdesc = BaseUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, cache.shortdesc); + cache.setShortdesc(BaseUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, cache.getShortdesc())); // cache description cache.setDescription(BaseUtils.getMatch(page, GCConstants.PATTERN_DESC, true, "")); @@ -1181,8 +1180,8 @@ public class cgBase { while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { - if (cache.attributes == null) { - cache.attributes = new ArrayList<String>(); + if (cache.getAttributes() == null) { + cache.setAttributes(new ArrayList<String>()); } // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(); @@ -1196,7 +1195,7 @@ public class cgBase { attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(); } } - cache.attributes.add(attribute); + cache.getAttributes().add(attribute); } } } @@ -1209,6 +1208,9 @@ public class cgBase { try { final String spoilers = BaseUtils.getMatch(page, GCConstants.PATTERN_SPOILERS, false, null); if (null != spoilers) { + if (CancellableHandler.isCancelled(handler)) { + return null; + } sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_spoilers); final Matcher matcherSpoilersInside = GCConstants.PATTERN_SPOILERSINSIDE.matcher(spoilers); @@ -1224,10 +1226,10 @@ public class cgBase { spoiler.description = matcherSpoilersInside.group(3); } - if (cache.spoilers == null) { - cache.spoilers = new ArrayList<cgImage>(); + if (cache.getSpoilers() == null) { + cache.setSpoilers(new ArrayList<cgImage>()); } - cache.spoilers.add(spoiler); + cache.getSpoilers().add(spoiler); } } } catch (Exception e) { @@ -1237,12 +1239,12 @@ public class cgBase { // cache inventory try { - cache.inventoryItems = 0; + cache.setInventoryItems(0); final Matcher matcherInventory = GCConstants.PATTERN_INVENTORY.matcher(page); if (matcherInventory.find()) { - if (cache.inventory == null) { - cache.inventory = new ArrayList<cgTrackable>(); + if (cache.getInventory() == null) { + cache.setInventory(new ArrayList<cgTrackable>()); } if (matcherInventory.groupCount() > 1) { @@ -1257,8 +1259,8 @@ public class cgBase { inventoryItem.setGuid(matcherInventoryInside.group(1)); inventoryItem.setName(matcherInventoryInside.group(2)); - cache.inventory.add(inventoryItem); - cache.inventoryItems++; + cache.getInventory().add(inventoryItem); + cache.setInventoryItems(cache.getInventoryItems() + 1); } } } @@ -1285,7 +1287,7 @@ public class cgBase { && logTypes.containsKey(typeStr.toLowerCase()) && StringUtils.isNotBlank(countStr)) { - cache.logCounts.put(logTypes.get(typeStr.toLowerCase()), Integer.parseInt(countStr)); + cache.getLogCounts().put(logTypes.get(typeStr.toLowerCase()), Integer.parseInt(countStr)); } } } @@ -1300,6 +1302,9 @@ public class cgBase { wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints + if (CancellableHandler.isCancelled(handler)) { + return null; + } sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_waypoints); final Pattern patternWpType = Pattern.compile("\\/wpttypes\\/sm\\/(.+)\\.jpg", Pattern.CASE_INSENSITIVE); @@ -1336,7 +1341,7 @@ public class cgBase { try { final Matcher matcherWpType = patternWpType.matcher(wp[3]); if (matcherWpType.find() && matcherWpType.groupCount() > 0) { - waypoint.type = WaypointType.FIND_BY_ID.get(matcherWpType.group(1).trim()); + waypoint.setWaypointType(WaypointType.FIND_BY_ID.get(matcherWpType.group(1).trim())); } } catch (Exception e) { // failed to parse type @@ -1358,7 +1363,7 @@ public class cgBase { try { final Matcher matcherWpLookup = patternWpPrefixOrLookupOrLatlon.matcher(wp[5]); if (matcherWpLookup.find() && matcherWpLookup.groupCount() > 1) { - waypoint.lookup = matcherWpLookup.group(2).trim(); + waypoint.setLookup(matcherWpLookup.group(2).trim()); } } catch (Exception e) { // failed to parse lookup @@ -1370,13 +1375,13 @@ public class cgBase { final Matcher matcherWpName = patternWpName.matcher(wp[6]); while (matcherWpName.find()) { if (matcherWpName.groupCount() > 0) { - waypoint.name = matcherWpName.group(1).trim(); - if (StringUtils.isNotBlank(waypoint.name)) { - waypoint.name = waypoint.name.trim(); + waypoint.setName(matcherWpName.group(1).trim()); + if (StringUtils.isNotBlank(waypoint.getName())) { + waypoint.setName(waypoint.getName().trim()); } } if (matcherWpName.find() && matcherWpName.groupCount() > 0) { - waypoint.name = matcherWpName.group(1).trim(); + waypoint.setName(matcherWpName.group(1).trim()); } } } catch (Exception e) { @@ -1390,8 +1395,8 @@ public class cgBase { if (matcherWpLatLon.find() && matcherWpLatLon.groupCount() > 1) { String latlon = Html.fromHtml(matcherWpLatLon.group(2)).toString().trim(); if (!StringUtils.startsWith(latlon, "???")) { - waypoint.latlon = latlon; - waypoint.coords = new Geopoint(latlon); + waypoint.setLatlon(latlon); + waypoint.setCoords(new Geopoint(latlon)); } } } catch (Exception e) { @@ -1408,17 +1413,17 @@ public class cgBase { try { final Matcher matcherWpNote = patternWpNote.matcher(wp[3]); if (matcherWpNote.find() && matcherWpNote.groupCount() > 0) { - waypoint.note = matcherWpNote.group(1).trim(); + waypoint.setNote(matcherWpNote.group(1).trim()); } } catch (Exception e) { // failed to parse note Log.w(Settings.tag, "cgeoBase.parseCache: Failed to parse waypoint note"); } - if (cache.waypoints == null) { - cache.waypoints = new ArrayList<cgWaypoint>(); + if (cache.getWaypoints() == null) { + cache.setWaypoints(new ArrayList<cgWaypoint>()); } - cache.waypoints.add(waypoint); + cache.getWaypoints().add(waypoint); } } } @@ -1428,21 +1433,34 @@ public class cgBase { return caches; } - private static void getExtraOnlineInfo(final cgCache cache, final String page, final Handler handler) { + private static void getExtraOnlineInfo(final cgCache cache, final String page, final CancellableHandler handler) { + if (CancellableHandler.isCancelled(handler)) { + return; + } sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_logs); loadLogsFromDetails(page, cache); - sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_elevation); - if (cache.coords != null) { - cache.elevation = getElevation(cache.coords); + if (Settings.isElevationWanted()) { + if (CancellableHandler.isCancelled(handler)) { + return; + } + sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_elevation); + if (cache.getCoords() != null) { + cache.setElevation(getElevation(cache.getCoords())); + } } - sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_gcvote); - final cgRating rating = GCVote.getRating(cache.guid, cache.geocode); - if (rating != null) { - cache.rating = rating.rating; - cache.votes = rating.votes; - cache.myVote = rating.myVote; + if (Settings.isRatingWanted()) { + if (CancellableHandler.isCancelled(handler)) { + return; + } + sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_gcvote); + final cgRating rating = GCVote.getRating(cache.getGuid(), cache.getGeocode()); + if (rating != null) { + cache.setRating(rating.rating); + cache.setVotes(rating.votes); + cache.setMyVote(rating.myVote); + } } } @@ -1527,10 +1545,10 @@ public class cgBase { logDone.logImages.add(logImage); } - if (null == cache.logs) { - cache.logs = new ArrayList<cgLog>(); + if (null == cache.getLogs()) { + cache.setLogs(new ArrayList<cgLog>()); } - cache.logs.add(logDone); + cache.getLogs().add(logDone); } } catch (JSONException e) { // failed to parse logs @@ -1539,43 +1557,43 @@ public class cgBase { } private static void checkFields(cgCache cache) { - if (StringUtils.isBlank(cache.geocode)) { + if (StringUtils.isBlank(cache.getGeocode())) { Log.e(Settings.tag, "cgBase.loadLogsFromDetails: geo code not parsed correctly"); } - if (StringUtils.isBlank(cache.name)) { + if (StringUtils.isBlank(cache.getName())) { Log.e(Settings.tag, "name not parsed correctly"); } - if (StringUtils.isBlank(cache.guid)) { + if (StringUtils.isBlank(cache.getGuid())) { Log.e(Settings.tag, "guid not parsed correctly"); } - if (cache.terrain == null || cache.terrain == 0.0) { + if (cache.getTerrain() == null || cache.getTerrain() == 0.0) { Log.e(Settings.tag, "terrain not parsed correctly"); } - if (cache.difficulty == null || cache.difficulty == 0.0) { + if (cache.getDifficulty() == null || cache.getDifficulty() == 0.0) { Log.e(Settings.tag, "difficulty not parsed correctly"); } - if (StringUtils.isBlank(cache.owner)) { + if (StringUtils.isBlank(cache.getOwner())) { Log.e(Settings.tag, "owner not parsed correctly"); } - if (StringUtils.isBlank(cache.ownerReal)) { + if (StringUtils.isBlank(cache.getOwnerReal())) { Log.e(Settings.tag, "owner real not parsed correctly"); } - if (cache.hidden == null) { + if (cache.getHidden() == null) { Log.e(Settings.tag, "hidden not parsed correctly"); } - if (cache.favouriteCnt == null) { + if (cache.getFavouriteCnt() == null) { Log.e(Settings.tag, "favoriteCount not parsed correctly"); } - if (cache.size == null) { + if (cache.getSize() == null) { Log.e(Settings.tag, "size not parsed correctly"); } - if (StringUtils.isBlank(cache.type)) { + if (StringUtils.isBlank(cache.getType())) { Log.e(Settings.tag, "type not parsed correctly"); } - if (cache.coords == null) { + if (cache.getCoords() == null) { Log.e(Settings.tag, "coordinates not parsed correctly"); } - if (StringUtils.isBlank(cache.location)) { + if (StringUtils.isBlank(cache.getLocation())) { Log.e(Settings.tag, "location not parsed correctly"); } } @@ -1635,7 +1653,7 @@ public class cgBase { final String profile = BaseUtils.replaceWhitespace(getResponseData(request("http://www.geocaching.com/my/", null, false))); final String avatarURL = BaseUtils.getMatch(profile, GCConstants.PATTERN_AVATAR_IMAGE, false, null); if (null != avatarURL) { - final cgHtmlImg imgGetter = new cgHtmlImg(context, "", false, 0, false, false); + final HtmlImage imgGetter = new HtmlImage(context, "", false, 0, false, false); return imgGetter.getDrawable(avatarURL); } // No match? There may be no avatar set by user. @@ -2008,19 +2026,19 @@ public class cgBase { } } - public UUID searchByNextPage(cgSearchThread thread, final UUID searchId, int reason, boolean showCaptcha) { - final String[] viewstates = app.getViewstates(searchId); + public cgSearch searchByNextPage(cgSearchThread thread, final cgSearch search, int reason, boolean showCaptcha) { + final String[] viewstates = cgeoapplication.getViewstates(search); - final String url = app.getUrl(searchId); + final String url = cgeoapplication.getUrl(search); if (StringUtils.isBlank(url)) { Log.e(Settings.tag, "cgeoBase.searchByNextPage: No url found"); - return searchId; + return search; } if (isEmpty(viewstates)) { Log.e(Settings.tag, "cgeoBase.searchByNextPage: No viewstate given"); - return searchId; + return search; } // As in the original code, remove the query string @@ -2039,39 +2057,39 @@ public class cgBase { } else if (loginState == StatusCode.NO_LOGIN_INFO_STORED) { Log.i(Settings.tag, "Working as guest."); } else { - app.setError(searchId, loginState); + cgeoapplication.setError(search, loginState); Log.e(Settings.tag, "cgeoBase.searchByNextPage: Can not log in geocaching"); - return searchId; + return search; } } if (StringUtils.isBlank(page)) { Log.e(Settings.tag, "cgeoBase.searchByNextPage: No data from server"); - return searchId; + return search; } final cgCacheWrap caches = parseSearch(thread, url, page, showCaptcha); if (caches == null || CollectionUtils.isEmpty(caches.cacheList)) { Log.e(Settings.tag, "cgeoBase.searchByNextPage: No cache parsed"); - return searchId; + return search; } // save to application - app.setError(searchId, caches.error); - app.setViewstates(searchId, caches.viewstates); + cgeoapplication.setError(search, caches.error); + cgeoapplication.setViewstates(search, caches.viewstates); final List<cgCache> cacheList = new ArrayList<cgCache>(); for (cgCache cache : caches.cacheList) { - app.addGeocode(searchId, cache.geocode); + cgeoapplication.addGeocode(search, cache.getGeocode()); cacheList.add(cache); } - app.addSearch(searchId, cacheList, true, reason); + app.addSearch(search, cacheList, true, reason); - return searchId; + return search; } - public UUID searchByGeocode(final String geocode, final String guid, final int reason, final boolean forceReload, final Handler handler) { + public cgSearch searchByGeocode(final String geocode, final String guid, final int reason, final boolean forceReload, final CancellableHandler handler) { final cgSearch search = new cgSearch(); if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { @@ -2083,7 +2101,7 @@ public class cgBase { final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : app.getGeocode(guid); List<cgCache> cacheList = new ArrayList<cgCache>(); - cacheList.add(app.getCacheByGeocode(realGeocode, true, true, true, true, true, true)); + cacheList.add(app.getCacheByGeocode(realGeocode, cgCache.LOADALL)); search.addGeocode(realGeocode); app.addSearch(search, cacheList, false, reason); @@ -2091,23 +2109,23 @@ public class cgBase { cacheList.clear(); cacheList = null; - return search.getCurrentId(); + return search; } return ConnectorFactory.getConnector(geocode).searchByGeocode(this, geocode, guid, app, search, reason, handler); } - public UUID searchByOffline(final Geopoint coords, final String cacheType, final int list) { + public cgSearch searchByOffline(final Geopoint coords, final String cacheType, final int list) { if (app == null) { Log.e(Settings.tag, "cgeoBase.searchByOffline: No application found"); return null; } final cgSearch search = app.getBatchOfStoredCaches(true, coords, cacheType, list); search.totalCnt = app.getAllStoredCachesCount(true, cacheType, list); - return search.getCurrentId(); + return search; } - public UUID searchByHistory(final String cacheType) { + public cgSearch searchByHistory(final String cacheType) { if (app == null) { Log.e(Settings.tag, "cgeoBase.searchByHistory: No application found"); return null; @@ -2116,7 +2134,7 @@ public class cgBase { final cgSearch search = app.getHistoryOfCaches(true, cacheType); search.totalCnt = app.getAllHistoricCachesCount(); - return search.getCurrentId(); + return search; } /** @@ -2129,7 +2147,7 @@ public class cgBase { * the parameters to add to the request URI * @return */ - private UUID searchByAny(final cgSearchThread thread, final String cacheType, final boolean my, final int reason, final boolean showCaptcha, final Parameters params) { + private cgSearch searchByAny(final cgSearchThread thread, final String cacheType, final boolean my, final int reason, final boolean showCaptcha, final Parameters params) { final cgSearch search = new cgSearch(); insertCacheType(params, cacheType); @@ -2156,15 +2174,15 @@ public class cgBase { app.addSearch(search, cacheList, true, reason); - return search.getCurrentId(); + return search; } - public UUID searchByCoords(final cgSearchThread thread, final Geopoint coords, final String cacheType, final int reason, final boolean showCaptcha) { + public cgSearch searchByCoords(final cgSearchThread thread, final Geopoint coords, final String cacheType, final int reason, final boolean showCaptcha) { final Parameters params = new Parameters("lat", Double.toString(coords.getLatitude()), "lng", Double.toString(coords.getLongitude())); return searchByAny(thread, cacheType, false, reason, showCaptcha, params); } - public UUID searchByKeyword(final cgSearchThread thread, final String keyword, final String cacheType, final int reason, final boolean showCaptcha) { + public cgSearch searchByKeyword(final cgSearchThread thread, final String keyword, final String cacheType, final int reason, final boolean showCaptcha) { if (StringUtils.isBlank(keyword)) { Log.e(Settings.tag, "cgeoBase.searchByKeyword: No keyword given"); return null; @@ -2174,7 +2192,7 @@ public class cgBase { return searchByAny(thread, cacheType, false, reason, showCaptcha, params); } - public UUID searchByUsername(final cgSearchThread thread, final String userName, final String cacheType, final int reason, final boolean showCaptcha) { + public cgSearch searchByUsername(final cgSearchThread thread, final String userName, final String cacheType, final int reason, final boolean showCaptcha) { if (StringUtils.isBlank(userName)) { Log.e(Settings.tag, "cgeoBase.searchByUsername: No user name given"); return null; @@ -2191,7 +2209,7 @@ public class cgBase { return searchByAny(thread, cacheType, my, reason, showCaptcha, params); } - public UUID searchByOwner(final cgSearchThread thread, final String userName, final String cacheType, final int reason, final boolean showCaptcha) { + public cgSearch searchByOwner(final cgSearchThread thread, final String userName, final String cacheType, final int reason, final boolean showCaptcha) { if (StringUtils.isBlank(userName)) { Log.e(Settings.tag, "cgeoBase.searchByOwner: No user name given"); return null; @@ -2201,7 +2219,7 @@ public class cgBase { return searchByAny(thread, cacheType, false, reason, showCaptcha, params); } - public UUID searchByViewport(final String userToken, final double latMin, final double latMax, final double lonMin, final double lonMax, int reason) { + public cgSearch searchByViewport(final String userToken, final double latMin, final double latMax, final double lonMin, final double lonMax, int reason) { final cgSearch search = new cgSearch(); String page = null; @@ -2230,7 +2248,7 @@ public class cgBase { app.addSearch(search, cacheList, true, reason); - return search.getCurrentId(); + return search; } private static String requestJSONgc(final String uri, final String params) { @@ -2324,11 +2342,11 @@ public class cgBase { if (CollectionUtils.isNotEmpty(caches.cacheList)) { for (final cgCache cache : caches.cacheList) { // Is there any reason to exclude the cache from the list? - final boolean excludeCache = (excludeDisabled && cache.disabled) || - (excludeMine && (cache.own || cache.found)) || - (cacheType != null && !cacheType.equals(cache.type)); + final boolean excludeCache = (excludeDisabled && cache.isDisabled()) || + (excludeMine && (cache.isOwn() || cache.isFound())) || + (cacheType != null && !cacheType.equals(cache.getType())); if (!excludeCache) { - search.addGeocode(cache.geocode); + search.addGeocode(cache.getGeocode()); cacheList.add(cache); } } @@ -2610,7 +2628,7 @@ public class cgBase { * @return -1: error occured */ public static int addToWatchlist(final cgCache cache) { - final String uri = "http://www.geocaching.com/my/watchlist.aspx?w=" + cache.cacheId; + final String uri = "http://www.geocaching.com/my/watchlist.aspx?w=" + cache.getCacheId(); String page = postRequestLogged(uri); if (StringUtils.isBlank(page)) { @@ -2621,7 +2639,7 @@ public class cgBase { boolean guidOnPage = cache.isGuidContainedInPage(page); if (guidOnPage) { Log.i(Settings.tag, "cgBase.addToWatchlist: cache is on watchlist"); - cache.onWatchlist = true; + cache.setOnWatchlist(true); } else { Log.e(Settings.tag, "cgBase.addToWatchlist: cache is not on watchlist"); } @@ -2636,7 +2654,7 @@ public class cgBase { * @return -1: error occured */ public static int removeFromWatchlist(final cgCache cache) { - final String uri = "http://www.geocaching.com/my/watchlist.aspx?ds=1&action=rem&id=" + cache.cacheId; + final String uri = "http://www.geocaching.com/my/watchlist.aspx?ds=1&action=rem&id=" + cache.getCacheId(); String page = postRequestLogged(uri); if (StringUtils.isBlank(page)) { @@ -2655,7 +2673,7 @@ public class cgBase { boolean guidOnPage = cache.isGuidContainedInPage(page); if (!guidOnPage) { Log.i(Settings.tag, "cgBase.removeFromWatchlist: cache removed from watchlist"); - cache.onWatchlist = false; + cache.setOnWatchlist(false); } else { Log.e(Settings.tag, "cgBase.removeFromWatchlist: cache not removed from watchlist"); } @@ -2677,7 +2695,7 @@ public class cgBase { status = "I found " + url; } else { - String name = cache.name; + String name = cache.getName(); status = "I found " + name + " (" + url + ")"; if (status.length() > Twitter.MAX_TWEET_SIZE) { name = name.substring(0, name.length() - (status.length() - Twitter.MAX_TWEET_SIZE) - 3) + "..."; @@ -2959,18 +2977,18 @@ public class cgBase { return path.delete(); } - public void storeCache(cgeoapplication app, Activity activity, cgCache cache, String geocode, int listId, Handler handler) { + public void storeCache(cgeoapplication app, Activity activity, cgCache cache, String geocode, int listId, CancellableHandler handler) { try { // get cache details, they may not yet be complete if (cache != null) { // only reload the cache, if it was already stored or has not all details (by checking the description) - if (cache.reason > 0 || StringUtils.isBlank(cache.getDescription())) { - final UUID searchId = searchByGeocode(cache.geocode, null, listId, false, null); - cache = app.getCache(searchId); + if (cache.getReason() > 0 || StringUtils.isBlank(cache.getDescription())) { + final cgSearch search = searchByGeocode(cache.getGeocode(), null, listId, false, null); + cache = app.getCache(search); } } else if (StringUtils.isNotBlank(geocode)) { - final UUID searchId = searchByGeocode(geocode, null, listId, false, null); - cache = app.getCache(searchId); + final cgSearch search = searchByGeocode(geocode, null, listId, false, null); + cache = app.getCache(search); } if (cache == null) { @@ -2981,23 +2999,35 @@ public class cgBase { return; } - final cgHtmlImg imgGetter = new cgHtmlImg(activity, cache.geocode, false, listId, true); + if (CancellableHandler.isCancelled(handler)) { + return; + } + + final HtmlImage imgGetter = new HtmlImage(activity, cache.getGeocode(), false, listId, true); // store images from description if (StringUtils.isNotBlank(cache.getDescription())) { Html.fromHtml(cache.getDescription(), imgGetter, null); } + if (CancellableHandler.isCancelled(handler)) { + return; + } + // store spoilers - if (CollectionUtils.isNotEmpty(cache.spoilers)) { - for (cgImage oneSpoiler : cache.spoilers) { + if (CollectionUtils.isNotEmpty(cache.getSpoilers())) { + for (cgImage oneSpoiler : cache.getSpoilers()) { imgGetter.getDrawable(oneSpoiler.url); } } + if (CancellableHandler.isCancelled(handler)) { + return; + } + // store images from logs - if (Settings.isStoreLogImages() && cache.logs != null) { - for (cgLog log : cache.logs) { + if (Settings.isStoreLogImages() && cache.getLogs() != null) { + for (cgLog log : cache.getLogs()) { if (CollectionUtils.isNotEmpty(log.logImages)) { for (cgImage oneLogImg : log.logImages) { imgGetter.getDrawable(oneLogImg.url); @@ -3006,24 +3036,32 @@ public class cgBase { } } + if (CancellableHandler.isCancelled(handler)) { + return; + } + // store map previews StaticMapsProvider.downloadMaps(cache, activity); - app.markStored(cache.geocode, listId); - app.removeCacheFromCache(cache.geocode); + if (CancellableHandler.isCancelled(handler)) { + return; + } + + app.markStored(cache.getGeocode(), listId); + app.removeCacheFromCache(cache.getGeocode()); if (handler != null) { handler.sendMessage(new Message()); } } catch (Exception e) { - Log.e(Settings.tag, "cgBase.storeCache: " + e.toString()); + Log.e(Settings.tag, "cgBase.storeCache"); } } public static void dropCache(final cgeoapplication app, final cgCache cache, final Handler handler) { try { - app.markDropped(cache.geocode); - app.removeCacheFromCache(cache.geocode); + app.markDropped(cache.getGeocode()); + app.removeCacheFromCache(cache.getGeocode()); handler.sendMessage(new Message()); } catch (Exception e) { diff --git a/main/src/cgeo/geocaching/cgCache.java b/main/src/cgeo/geocaching/cgCache.java index 1479fec..edca68a 100644 --- a/main/src/cgeo/geocaching/cgCache.java +++ b/main/src/cgeo/geocaching/cgCache.java @@ -31,60 +31,68 @@ import java.util.regex.Pattern; */ public class cgCache implements ICache { - public Long updated = null; - public Long detailedUpdate = null; - public Long visitedDate = null; - public Integer reason = 0; - public Boolean detailed = false; /** - * Code of the cache like GCABCD + * Cache loading parameters */ - public String geocode = ""; - public String cacheId = ""; - public String guid = ""; - public String type = ""; - public String name = ""; - public Spannable nameSp = null; - public String owner = ""; - public String ownerReal = ""; - public Date hidden = null; - public String hint = ""; - public CacheSize size = null; - public Float difficulty = Float.valueOf(0); - public Float terrain = Float.valueOf(0); - public Float direction = null; - public Float distance = null; - public String latlon = ""; - public String location = ""; - public Geopoint coords = null; - public boolean reliableLatLon = false; - public Double elevation = null; - public String personalNote = null; - public String shortdesc = ""; + final public static int LOADATTRIBUTES = 1 << 0; + final public static int LOADWAYPOINTS = 1 << 1; + final public static int LOADSPOILERS = 1 << 2; + final public static int LOADLOGS = 1 << 3; + final public static int LOADINVENTORY = 1 << 4; + final public static int LOADOFFLINELOG = 1 << 5; + final public static int LOADALL = LOADATTRIBUTES | LOADWAYPOINTS | LOADSPOILERS | LOADLOGS | LOADINVENTORY | LOADOFFLINELOG; + + private Long updated = null; + private Long detailedUpdate = null; + private Long visitedDate = null; + private Integer reason = 0; + private Boolean detailed = false; + private String geocode = ""; + private String cacheId = ""; + private String guid = ""; + private CacheType cacheType = CacheType.UNKNOWN; + private String name = ""; + private Spannable nameSp = null; + private String owner = ""; + private String ownerReal = ""; + private Date hidden = null; + private String hint = ""; + private CacheSize size = null; + private Float difficulty = Float.valueOf(0); + private Float terrain = Float.valueOf(0); + private Float direction = null; + private Float distance = null; + private String latlon = ""; + private String location = ""; + private Geopoint coords = null; + private boolean reliableLatLon = false; + private Double elevation = null; + private String personalNote = null; + private String shortdesc = ""; private String description = null; - public boolean disabled = false; - public boolean archived = false; - public boolean members = false; - public boolean found = false; - public boolean favourite = false; - public boolean own = false; - public Integer favouriteCnt = null; - public Float rating = null; - public Integer votes = null; - public Float myVote = null; - public int inventoryItems = 0; - public boolean onWatchlist = false; - public List<String> attributes = null; - public List<cgWaypoint> waypoints = null; - public ArrayList<cgImage> spoilers = null; - public List<cgLog> logs = null; - public List<cgTrackable> inventory = null; - public Map<Integer, Integer> logCounts = new HashMap<Integer, Integer>(); - public boolean logOffline = false; + private boolean disabled = false; + private boolean archived = false; + private boolean members = false; + private boolean found = false; + private boolean favourite = false; + private boolean own = false; + private Integer favouriteCnt = null; + private Float rating = null; + private Integer votes = null; + private Float myVote = null; + private int inventoryItems = 0; + private boolean onWatchlist = false; + private List<String> attributes = null; + private List<cgWaypoint> waypoints = null; + private ArrayList<cgImage> spoilers = null; + private List<cgLog> logs = null; + private List<cgTrackable> inventory = null; + private Map<Integer, Integer> logCounts = new HashMap<Integer, Integer>(); + private boolean logOffline = false; // temporary values - public boolean statusChecked = false; - public boolean statusCheckedView = false; - public String directionImg = null; + private boolean statusChecked = false; + private boolean statusCheckedView = false; + private String directionImg = null; private String nameForSorting; private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+"); @@ -106,34 +114,34 @@ public class cgCache implements ICache { } if (visitedDate == null || visitedDate == 0) { - visitedDate = other.visitedDate; + visitedDate = other.getVisitedDate(); } if (reason == null || reason == 0) { reason = other.reason; } if (StringUtils.isBlank(geocode)) { - geocode = other.geocode; + geocode = other.getGeocode(); } if (StringUtils.isBlank(cacheId)) { cacheId = other.cacheId; } if (StringUtils.isBlank(guid)) { - guid = other.guid; + guid = other.getGuid(); } - if (StringUtils.isBlank(type)) { - type = other.type; + if (null == cacheType || CacheType.UNKNOWN == cacheType) { + cacheType = other.getCacheType(); } if (StringUtils.isBlank(name)) { - name = other.name; + name = other.getName(); } if (StringUtils.isBlank(nameSp)) { nameSp = other.nameSp; } if (StringUtils.isBlank(owner)) { - owner = other.owner; + owner = other.getOwner(); } if (StringUtils.isBlank(ownerReal)) { - ownerReal = other.ownerReal; + ownerReal = other.getOwnerReal(); } if (hidden == null) { hidden = other.hidden; @@ -145,16 +153,16 @@ public class cgCache implements ICache { size = other.size; } if (difficulty == null || difficulty == 0) { - difficulty = other.difficulty; + difficulty = other.getDifficulty(); } if (terrain == null || terrain == 0) { - terrain = other.terrain; + terrain = other.getTerrain(); } if (direction == null) { direction = other.direction; } if (distance == null) { - distance = other.distance; + distance = other.getDistance(); } if (StringUtils.isBlank(latlon)) { latlon = other.latlon; @@ -163,7 +171,7 @@ public class cgCache implements ICache { location = other.location; } if (coords == null) { - coords = other.coords; + coords = other.getCoords(); } if (elevation == null) { elevation = other.elevation; @@ -172,31 +180,31 @@ public class cgCache implements ICache { personalNote = other.personalNote; } if (StringUtils.isBlank(shortdesc)) { - shortdesc = other.shortdesc; + shortdesc = other.getShortdesc(); } if (StringUtils.isBlank(description)) { description = other.description; } if (favouriteCnt == null) { - favouriteCnt = other.favouriteCnt; + favouriteCnt = other.getFavouriteCnt(); } if (rating == null) { - rating = other.rating; + rating = other.getRating(); } if (votes == null) { votes = other.votes; } if (myVote == null) { - myVote = other.myVote; + myVote = other.getMyVote(); } if (attributes == null) { - attributes = other.attributes; + attributes = other.getAttributes(); } if (waypoints == null) { - waypoints = other.waypoints; + waypoints = other.getWaypoints(); } else { - cgWaypoint.mergeWayPoints(waypoints, other.waypoints); + cgWaypoint.mergeWayPoints(waypoints, other.getWaypoints()); } if (spoilers == null) { spoilers = other.spoilers; @@ -265,8 +273,8 @@ public class cgCache implements ICache { } public boolean isEventCache() { - return CacheType.EVENT.id.equalsIgnoreCase(type) || CacheType.MEGA_EVENT.id.equalsIgnoreCase(type) - || CacheType.CITO.id.equalsIgnoreCase(type) || CacheType.LOSTANDFOUND.id.equalsIgnoreCase(type); + return CacheType.EVENT == cacheType || CacheType.MEGA_EVENT == cacheType + || CacheType.CITO == cacheType || CacheType.LOSTANDFOUND == cacheType; } public boolean logVisit(IAbstractActivity fromActivity) { @@ -321,7 +329,7 @@ public class cgCache implements ICache { if (isOwner) { types.add(cgBase.LOG_ANNOUNCEMENT); } - } else if (CacheType.WEBCAM.id.equals(type)) { + } else if (CacheType.WEBCAM == cacheType) { types.add(cgBase.LOG_WEBCAM_PHOTO_TAKEN); types.add(cgBase.LOG_DIDNT_FIND_IT); types.add(cgBase.LOG_NOTE); @@ -407,9 +415,17 @@ public class cgCache implements ICache { return terrain; } - @Override + /** + * @deprecated Use getCacheType() instead + * @return cache type as an id + */ + @Deprecated public String getType() { - return type; + if (null != cacheType) { + return cacheType.id; + } else { + return ""; + } } @Override @@ -550,7 +566,7 @@ public class cgCache implements ICache { } @Override - public List<cgImage> getSpoilers() { + public ArrayList<cgImage> getSpoilers() { return spoilers; } @@ -579,11 +595,335 @@ public class cgCache implements ICache { } public boolean isVirtual() { - return CacheType.VIRTUAL.id.equalsIgnoreCase(type) || CacheType.WEBCAM.id.equalsIgnoreCase(type) - || CacheType.EARTH.id.equalsIgnoreCase(type); + return CacheType.VIRTUAL == cacheType || CacheType.WEBCAM == cacheType + || CacheType.EARTH == cacheType; } public boolean showSize() { return !((isEventCache() || isVirtual()) && size == CacheSize.NOT_CHOSEN); } + + public Long getUpdated() { + return updated; + } + + public void setUpdated(Long updated) { + this.updated = updated; + } + + public Long getDetailedUpdate() { + return detailedUpdate; + } + + public void setDetailedUpdate(Long detailedUpdate) { + this.detailedUpdate = detailedUpdate; + } + + public Long getVisitedDate() { + return visitedDate; + } + + public void setVisitedDate(Long visitedDate) { + this.visitedDate = visitedDate; + } + + public Integer getReason() { + return reason; + } + + public void setReason(Integer reason) { + this.reason = reason; + } + + public Boolean getDetailed() { + return detailed; + } + + public void setDetailed(Boolean detailed) { + this.detailed = detailed; + } + + public Spannable getNameSp() { + return nameSp; + } + + public void setNameSp(Spannable nameSp) { + this.nameSp = nameSp; + } + + public Date getHidden() { + return hidden; + } + + public void setHidden(Date hidden) { + this.hidden = hidden; + } + + public Float getDirection() { + return direction; + } + + public void setDirection(Float direction) { + this.direction = direction; + } + + public Float getDistance() { + return distance; + } + + public void setDistance(Float distance) { + this.distance = distance; + } + + public String getLatlon() { + return latlon; + } + + public void setLatlon(String latlon) { + this.latlon = latlon; + } + + public Geopoint getCoords() { + return coords; + } + + public void setCoords(Geopoint coords) { + this.coords = coords; + } + + public boolean isReliableLatLon() { + return reliableLatLon; + } + + public void setReliableLatLon(boolean reliableLatLon) { + this.reliableLatLon = reliableLatLon; + } + + public Double getElevation() { + return elevation; + } + + public void setElevation(Double elevation) { + this.elevation = elevation; + } + + public String getShortdesc() { + return shortdesc; + } + + public void setShortdesc(String shortdesc) { + this.shortdesc = shortdesc; + } + + public boolean isMembers() { + return members; + } + + public void setMembers(boolean members) { + this.members = members; + } + + public boolean isFavourite() { + return favourite; + } + + public void setFavourite(boolean favourite) { + this.favourite = favourite; + } + + public Integer getFavouriteCnt() { + return favouriteCnt; + } + + public void setFavouriteCnt(Integer favouriteCnt) { + this.favouriteCnt = favouriteCnt; + } + + public Float getRating() { + return rating; + } + + public void setRating(Float rating) { + this.rating = rating; + } + + public Integer getVotes() { + return votes; + } + + public void setVotes(Integer votes) { + this.votes = votes; + } + + public Float getMyVote() { + return myVote; + } + + public void setMyVote(Float myVote) { + this.myVote = myVote; + } + + public int getInventoryItems() { + return inventoryItems; + } + + public void setInventoryItems(int inventoryItems) { + this.inventoryItems = inventoryItems; + } + + public boolean isOnWatchlist() { + return onWatchlist; + } + + public void setOnWatchlist(boolean onWatchlist) { + this.onWatchlist = onWatchlist; + } + + public List<cgWaypoint> getWaypoints() { + return waypoints; + } + + public void setWaypoints(List<cgWaypoint> waypoints) { + this.waypoints = waypoints; + } + + public List<cgLog> getLogs() { + return logs; + } + + public void setLogs(List<cgLog> logs) { + this.logs = logs; + } + + public boolean isLogOffline() { + return logOffline; + } + + public void setLogOffline(boolean logOffline) { + this.logOffline = logOffline; + } + + public boolean isStatusChecked() { + return statusChecked; + } + + public void setStatusChecked(boolean statusChecked) { + this.statusChecked = statusChecked; + } + + public boolean isStatusCheckedView() { + return statusCheckedView; + } + + public void setStatusCheckedView(boolean statusCheckedView) { + this.statusCheckedView = statusCheckedView; + } + + public String getDirectionImg() { + return directionImg; + } + + public void setDirectionImg(String directionImg) { + this.directionImg = directionImg; + } + + public void setGeocode(String geocode) { + this.geocode = geocode; + } + + public void setCacheId(String cacheId) { + this.cacheId = cacheId; + } + + public void setGuid(String guid) { + this.guid = guid; + } + + + public void setName(String name) { + this.name = name; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public void setOwnerReal(String ownerReal) { + this.ownerReal = ownerReal; + } + + public void setHint(String hint) { + this.hint = hint; + } + + public void setSize(CacheSize size) { + this.size = size; + } + + public void setDifficulty(Float difficulty) { + this.difficulty = difficulty; + } + + public void setTerrain(Float terrain) { + this.terrain = terrain; + } + + public void setLocation(String location) { + this.location = location; + } + + public void setPersonalNote(String personalNote) { + this.personalNote = personalNote; + } + + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } + + public void setArchived(boolean archived) { + this.archived = archived; + } + + public void setFound(boolean found) { + this.found = found; + } + + public void setOwn(boolean own) { + this.own = own; + } + + public void setAttributes(List<String> attributes) { + this.attributes = attributes; + } + + public void setSpoilers(ArrayList<cgImage> spoilers) { + this.spoilers = spoilers; + } + + public void setInventory(List<cgTrackable> inventory) { + this.inventory = inventory; + } + + public void setLogCounts(Map<Integer, Integer> logCounts) { + this.logCounts = logCounts; + } + + public void setNameForSorting(String nameForSorting) { + this.nameForSorting = nameForSorting; + } + + @Override + public CacheType getCacheType() { + return cacheType; + } + + public void setCacheType(CacheType cacheType) { + if (cacheType == null) { + this.cacheType = CacheType.UNKNOWN; + } + else { + this.cacheType = cacheType; + } + } + } diff --git a/main/src/cgeo/geocaching/cgCacheListAdapter.java b/main/src/cgeo/geocaching/cgCacheListAdapter.java index faf4e44..72d8d2a 100644 --- a/main/src/cgeo/geocaching/cgCacheListAdapter.java +++ b/main/src/cgeo/geocaching/cgCacheListAdapter.java @@ -180,13 +180,13 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { if (!selectMode && clear) { for (final cgCache cache : list) { - cache.statusChecked = false; - cache.statusCheckedView = false; + cache.setStatusChecked(false); + cache.setStatusCheckedView(false); } checked = 0; } else if (selectMode) { for (final cgCache cache : list) { - cache.statusCheckedView = false; + cache.setStatusCheckedView(false); } } checkChecked(0); @@ -205,13 +205,13 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { if (!selectMode) { for (final cgCache cache : list) { - cache.statusChecked = false; - cache.statusCheckedView = false; + cache.setStatusChecked(false); + cache.setStatusCheckedView(false); } checked = 0; } else { for (final cgCache cache : list) { - cache.statusCheckedView = false; + cache.setStatusCheckedView(false); } } checkChecked(0); @@ -223,12 +223,12 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { int check = 0; for (cgCache cache : list) { - if (cache.statusChecked) { - cache.statusChecked = false; - cache.statusCheckedView = false; + if (cache.isStatusChecked()) { + cache.setStatusChecked(false); + cache.setStatusCheckedView(false); } else { - cache.statusChecked = true; - cache.statusCheckedView = true; + cache.setStatusChecked(true); + cache.setStatusCheckedView(true); check++; } @@ -308,8 +308,8 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { boolean status = getSelectMode(); int cleared = 0; for (cgCache cache : list) { - if (cache.statusChecked) { - cache.statusChecked = false; + if (cache.isStatusChecked()) { + cache.setStatusChecked(false); checkChecked(-1); cleared++; @@ -361,7 +361,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { holder = (cgCacheView) v.getTag(); } - if (cache.own) { + if (cache.isOwn()) { if (Settings.isLightSkin()) { holder.oneInfo.setBackgroundResource(R.color.owncache_background_light); holder.oneCheckbox.setBackgroundResource(R.color.owncache_background_light); @@ -379,28 +379,28 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } } - final touchListener touchLst = new touchListener(cache.geocode, cache.name, cache); + final touchListener touchLst = new touchListener(cache.getGeocode(), cache.getName(), cache); v.setOnClickListener(touchLst); v.setOnLongClickListener(touchLst); v.setOnTouchListener(touchLst); v.setLongClickable(true); if (selectMode) { - if (cache.statusCheckedView) { + if (cache.isStatusCheckedView()) { moveRight(holder, cache, true); // move fast when already slided } else { moveRight(holder, cache, false); } - } else if (cache.statusChecked) { + } else if (cache.isStatusChecked()) { holder.checkbox.setChecked(true); - if (cache.statusCheckedView) { + if (cache.isStatusCheckedView()) { moveRight(holder, cache, true); // move fast when already slided } else { moveRight(holder, cache, false); } } else { holder.checkbox.setChecked(false); - if (cache.statusCheckedView) { + if (cache.isStatusCheckedView()) { moveLeft(holder, cache, false); } else { holder.oneInfo.clearAnimation(); @@ -410,33 +410,33 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { holder.checkbox.setOnClickListener(new checkBoxListener(cache)); distances.add(holder.distance); - holder.distance.setContent(base, cache.coords); + holder.distance.setContent(base, cache.getCoords()); compasses.add(holder.direction); - holder.direction.setContent(cache.coords); + holder.direction.setContent(cache.getCoords()); - if (cache.found && cache.logOffline) { + if (cache.isFound() && cache.isLogOffline()) { holder.logStatusMark.setImageResource(R.drawable.mark_green_orange); holder.logStatusMark.setVisibility(View.VISIBLE); - } else if (cache.found) { + } else if (cache.isFound()) { holder.logStatusMark.setImageResource(R.drawable.mark_green_more); holder.logStatusMark.setVisibility(View.VISIBLE); - } else if (cache.logOffline) { + } else if (cache.isLogOffline()) { holder.logStatusMark.setImageResource(R.drawable.mark_orange); holder.logStatusMark.setVisibility(View.VISIBLE); } else { holder.logStatusMark.setVisibility(View.GONE); } - if (cache.nameSp == null) { - cache.nameSp = (new Spannable.Factory()).newSpannable(cache.name); - if (cache.disabled || cache.archived) { // strike - cache.nameSp.setSpan(new StrikethroughSpan(), 0, cache.nameSp.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); + if (cache.getNameSp() == null) { + cache.setNameSp((new Spannable.Factory()).newSpannable(cache.getName())); + if (cache.isDisabled() || cache.isArchived()) { // strike + cache.getNameSp().setSpan(new StrikethroughSpan(), 0, cache.getNameSp().toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } - holder.text.setText(cache.nameSp, TextView.BufferType.SPANNABLE); - if (gcIconDrawables.containsKey(cache.type)) { // cache icon - holder.text.setCompoundDrawablesWithIntrinsicBounds(gcIconDrawables.get(cache.type), null, null, null); + holder.text.setText(cache.getNameSp(), TextView.BufferType.SPANNABLE); + if (gcIconDrawables.containsKey(cache.getType())) { // cache icon + holder.text.setCompoundDrawablesWithIntrinsicBounds(gcIconDrawables.get(cache.getType()), null, null, null); } else { // unknown cache type, "mystery" icon holder.text.setCompoundDrawablesWithIntrinsicBounds(gcIconDrawables.get(CacheType.MYSTERY.id), null, null, null); } @@ -446,7 +446,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } ImageView tbIcon = null; - if (cache.inventoryItems > 0) { + if (cache.getInventoryItems() > 0) { tbIcon = (ImageView) inflater.inflate(R.layout.trackable_icon, null); tbIcon.setImageResource(R.drawable.trackable_all); @@ -457,7 +457,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } boolean setDiDi = false; - if (cache.coords != null) { + if (cache.getCoords() != null) { holder.direction.setVisibility(View.VISIBLE); holder.direction.updateAzimuth(azimuth); if (coords != null) { @@ -466,14 +466,14 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } setDiDi = true; } else { - if (cache.distance != null) { - holder.distance.setDistance(cache.distance); + if (cache.getDistance() != null) { + holder.distance.setDistance(cache.getDistance()); setDiDi = true; } - if (cache.direction != null) { + if (cache.getDirection() != null) { holder.direction.setVisibility(View.VISIBLE); holder.direction.updateAzimuth(azimuth); - holder.direction.updateHeading(cache.direction); + holder.direction.updateHeading(cache.getDirection()); setDiDi = true; } } @@ -485,7 +485,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { holder.directionLayout.setVisibility(View.GONE); holder.distance.clear(); - final Bitmap dirImgPre = BitmapFactory.decodeFile(cgDirectionImg.getDirectionFile(cache.geocode).getPath()); + final Bitmap dirImgPre = BitmapFactory.decodeFile(cgDirectionImg.getDirectionFile(cache.getGeocode()).getPath()); final Bitmap dirImg; if (dirImgPre != null) { // null happens for invalid caches (not yet released) dirImg = dirImgPre.copy(Bitmap.Config.ARGB_8888, true); @@ -516,8 +516,8 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } } - if (cache.favouriteCnt != null) { - holder.favourite.setText(String.format("%d", cache.favouriteCnt)); + if (cache.getFavouriteCnt() != null) { + holder.favourite.setText(String.format("%d", cache.getFavouriteCnt())); } else { holder.favourite.setText("---"); } @@ -529,64 +529,64 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } else { favoriteBack = R.drawable.favourite_background_dark; } - if (cache.myVote != null && cache.myVote > 0) { - if (cache.myVote >= 4) { + if (cache.getMyVote() != null && cache.getMyVote() > 0) { + if (cache.getMyVote() >= 4) { favoriteBack = ratingBcgs[2]; - } else if (cache.myVote >= 3) { + } else if (cache.getMyVote() >= 3) { favoriteBack = ratingBcgs[1]; - } else if (cache.myVote > 0) { + } else if (cache.getMyVote() > 0) { favoriteBack = ratingBcgs[0]; } - } else if (cache.rating != null && cache.rating > 0) { - if (cache.rating >= 3.5) { + } else if (cache.getRating() != null && cache.getRating() > 0) { + if (cache.getRating() >= 3.5) { favoriteBack = ratingBcgs[2]; - } else if (cache.rating >= 2.1) { + } else if (cache.getRating() >= 2.1) { favoriteBack = ratingBcgs[1]; - } else if (cache.rating > 0.0) { + } else if (cache.getRating() > 0.0) { favoriteBack = ratingBcgs[0]; } } holder.favourite.setBackgroundResource(favoriteBack); StringBuilder cacheInfo = new StringBuilder(); - if (historic && cache.visitedDate != null) { - cacheInfo.append(base.formatTime(cache.visitedDate)); + if (historic && cache.getVisitedDate() != null) { + cacheInfo.append(base.formatTime(cache.getVisitedDate())); cacheInfo.append("; "); - cacheInfo.append(base.formatDate(cache.visitedDate)); + cacheInfo.append(base.formatDate(cache.getVisitedDate())); } else { - if (StringUtils.isNotBlank(cache.geocode)) { - cacheInfo.append(cache.geocode); + if (StringUtils.isNotBlank(cache.getGeocode())) { + cacheInfo.append(cache.getGeocode()); } - if (cache.size != null) { + if (cache.getSize() != null) { // don't show "not chosen" for events and virtuals, that should be the normal case if (cache.showSize()) { if (cacheInfo.length() > 0) { cacheInfo.append(" | "); } - cacheInfo.append(res.getString(cache.size.stringId)); + cacheInfo.append(res.getString(cache.getSize().stringId)); } } - if ((cache.difficulty != null && cache.difficulty > 0f) || (cache.terrain != null && cache.terrain > 0f) || (cache.rating != null && cache.rating > 0f)) { - if (cacheInfo.length() > 0 && ((cache.difficulty != null && cache.difficulty > 0f) || (cache.terrain != null && cache.terrain > 0f))) { + if ((cache.getDifficulty() != null && cache.getDifficulty() > 0f) || (cache.getTerrain() != null && cache.getTerrain() > 0f) || (cache.getRating() != null && cache.getRating() > 0f)) { + if (cacheInfo.length() > 0 && ((cache.getDifficulty() != null && cache.getDifficulty() > 0f) || (cache.getTerrain() != null && cache.getTerrain() > 0f))) { cacheInfo.append(" |"); } - if (cache.difficulty != null && cache.difficulty > 0f) { + if (cache.getDifficulty() != null && cache.getDifficulty() > 0f) { cacheInfo.append(" D:"); - cacheInfo.append(String.format(Locale.getDefault(), "%.1f", cache.difficulty)); + cacheInfo.append(String.format(Locale.getDefault(), "%.1f", cache.getDifficulty())); } - if (cache.terrain != null && cache.terrain > 0f) { + if (cache.getTerrain() != null && cache.getTerrain() > 0f) { cacheInfo.append(" T:"); - cacheInfo.append(String.format(Locale.getDefault(), "%.1f", cache.terrain)); + cacheInfo.append(String.format(Locale.getDefault(), "%.1f", cache.getTerrain())); } } - if (cache.members) { + if (cache.isMembers()) { if (cacheInfo.length() > 0) { cacheInfo.append(" | "); } cacheInfo.append(res.getString(R.string.cache_premium)); } - if (cache.reason != null && cache.reason == 1) { + if (cache.getReason() != null && cache.getReason() == 1) { if (cacheInfo.length() > 0) { cacheInfo.append(" | "); } @@ -604,7 +604,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { checked = 0; for (cgCache cache : list) { - if (cache.statusChecked) { + if (cache.isStatusChecked()) { checked++; } } @@ -625,10 +625,10 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { final boolean checkNow = ((CheckBox) view).isChecked(); if (checkNow) { - cache.statusChecked = true; + cache.setStatusChecked(true); checked++; } else { - cache.statusChecked = false; + cache.setStatusChecked(false); checked--; } } @@ -713,21 +713,21 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { if ((e2.getX() - e1.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY)) { // left to right swipe - if (cache.statusChecked) { + if (cache.isStatusChecked()) { return true; } if (holder != null && holder.oneInfo != null) { checkChecked(+1); holder.checkbox.setChecked(true); - cache.statusChecked = true; + cache.setStatusChecked(true); moveRight(holder, cache, false); } return true; } else if ((e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY)) { // right to left swipe - if (!cache.statusChecked) { + if (!cache.isStatusChecked()) { return true; } @@ -738,7 +738,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { checkChecked(-1); holder.checkbox.setChecked(false); - cache.statusChecked = false; + cache.setStatusChecked(false); moveLeft(holder, cache, false); } @@ -767,7 +767,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return; } - holder.checkbox.setChecked(cache.statusChecked); + holder.checkbox.setChecked(cache.isStatusChecked()); // slide cache info final Animation showCheckbox = new TranslateAnimation(0, (int) (SWIPE_DISTANCE * pixelDensity), 0, 0); @@ -794,7 +794,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { selectAnimation.addAnimation(dimInfo); holder.oneInfo.startAnimation(selectAnimation); - cache.statusCheckedView = true; + cache.setStatusCheckedView(true); } private void moveLeft(cgCacheView holder, cgCache cache, boolean force) { @@ -802,7 +802,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return; } - holder.checkbox.setChecked(cache.statusChecked); + holder.checkbox.setChecked(cache.isStatusChecked()); // slide cache info final Animation hideCheckbox = new TranslateAnimation((int) (SWIPE_DISTANCE * pixelDensity), 0, 0, 0); @@ -829,6 +829,6 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { selectAnimation.addAnimation(brightenInfo); holder.oneInfo.startAnimation(selectAnimation); - cache.statusCheckedView = false; + cache.setStatusCheckedView(false); } } diff --git a/main/src/cgeo/geocaching/cgCoord.java b/main/src/cgeo/geocaching/cgCoord.java index 60f6b63..5227883 100644 --- a/main/src/cgeo/geocaching/cgCoord.java +++ b/main/src/cgeo/geocaching/cgCoord.java @@ -2,46 +2,167 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.CacheType; +import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; -public class cgCoord { +public class cgCoord implements IBasicCache, IWaypoint { - public Integer id = null; - public String geocode = ""; - public String type = "cache"; - public String typeSpec = CacheType.TRADITIONAL.id; - public String name = ""; - public boolean found = false; - public boolean disabled = false; - public Geopoint coords = new Geopoint(0, 0); - public Float difficulty = null; - public Float terrain = null; - public CacheSize size = null; + private Integer id = null; // only valid if constructed with a waypoint + private WaypointType waypointType = null; // only valid if constructed with a waypoint + private String guid = null; // only valid if constructed with a cache + private CacheType cacheType = null; // only valid if constructed with a cache + private String geocode = ""; + private String type = "cache"; // used values: { cache, waypoint } + private String typeSpec = CacheType.TRADITIONAL.id; + private String name = ""; + private boolean found = false; + private boolean disabled = false; + private Geopoint coords = new Geopoint(0, 0); + private Float difficulty = null; + private Float terrain = null; + private CacheSize size = null; public cgCoord() { } public cgCoord(cgCache cache) { - disabled = cache.disabled; - found = cache.found; - geocode = cache.geocode; - coords = cache.coords; - name = cache.name; + guid = cache.getGuid(); + disabled = cache.isDisabled(); + found = cache.isFound(); + geocode = cache.getGeocode(); + coords = cache.getCoords(); + name = cache.getName(); type = "cache"; - typeSpec = cache.type; - difficulty = cache.difficulty; - terrain = cache.terrain; - size = cache.size; + typeSpec = cache.getType(); + difficulty = cache.getDifficulty(); + terrain = cache.getTerrain(); + size = cache.getSize(); + cacheType = cache.getCacheType(); } public cgCoord(cgWaypoint waypoint) { - id = waypoint.id; + id = waypoint.getId(); disabled = false; found = false; geocode = ""; - coords = waypoint.coords; - name = waypoint.name; + coords = waypoint.getCoords(); + name = waypoint.getName(); type = "waypoint"; - typeSpec = waypoint.type != null ? waypoint.type.id : null; + typeSpec = waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null; + waypointType = waypoint.getWaypointType(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + @Override + public String getGeocode() { + return geocode; + } + + public void setGeocode(String geocode) { + this.geocode = geocode; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getTypeSpec() { + return typeSpec; + } + + public void setTypeSpec(String typeSpec) { + this.typeSpec = typeSpec; + } + + @Override + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean isFound() { + return found; + } + + public void setFound(boolean found) { + this.found = found; + } + + @Override + public boolean isDisabled() { + return disabled; + } + + public void setDisabled(boolean disabled) { + this.disabled = disabled; + } + + public Geopoint getCoords() { + return coords; + } + + public void setCoords(Geopoint coords) { + this.coords = coords; + } + + @Override + public Float getDifficulty() { + return difficulty; + } + + public void setDifficulty(Float difficulty) { + this.difficulty = difficulty; + } + + @Override + public Float getTerrain() { + return terrain; + } + + public void setTerrain(Float terrain) { + this.terrain = terrain; + } + + @Override + public CacheSize getSize() { + return size; + } + + public void setSize(CacheSize size) { + this.size = size; + } + + public void setGuid(String guid) { + this.guid = guid; + } + + @Override + public String getGuid() { + return guid; + } + + @Override + public WaypointType getWaypointType() { + return waypointType; + } + + @Override + public CacheType getCacheType() { + return cacheType; } } diff --git a/main/src/cgeo/geocaching/cgData.java b/main/src/cgeo/geocaching/cgData.java index e8c7c6c..d77b3c0 100644 --- a/main/src/cgeo/geocaching/cgData.java +++ b/main/src/cgeo/geocaching/cgData.java @@ -1,6 +1,7 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.CacheSize; +import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.Geopoint; @@ -1199,102 +1200,102 @@ public class cgData { ContentValues values = new ContentValues(); - if (cache.updated == null) { + if (cache.getUpdated() == null) { values.put("updated", System.currentTimeMillis()); } else { - values.put("updated", cache.updated); - } - values.put("reason", cache.reason); - values.put("detailed", cache.detailed ? 1 : 0); - values.put("detailedupdate", cache.detailedUpdate); - values.put("visiteddate", cache.visitedDate); - values.put("geocode", cache.geocode); - values.put("cacheid", cache.cacheId); - values.put("guid", cache.guid); - values.put("type", cache.type); - values.put("name", cache.name); - values.put("own", cache.own ? 1 : 0); - values.put("owner", cache.owner); - values.put("owner_real", cache.ownerReal); - if (cache.hidden == null) { + values.put("updated", cache.getUpdated()); + } + values.put("reason", cache.getReason()); + values.put("detailed", cache.getDetailed() ? 1 : 0); + values.put("detailedupdate", cache.getDetailedUpdate()); + values.put("visiteddate", cache.getVisitedDate()); + values.put("geocode", cache.getGeocode()); + values.put("cacheid", cache.getCacheId()); + values.put("guid", cache.getGuid()); + values.put("type", cache.getCacheType().id); + values.put("name", cache.getName()); + values.put("own", cache.isOwn() ? 1 : 0); + values.put("owner", cache.getOwner()); + values.put("owner_real", cache.getOwnerReal()); + if (cache.getHidden() == null) { values.put("hidden", 0); } else { - values.put("hidden", cache.hidden.getTime()); - } - values.put("hint", cache.hint); - values.put("size", cache.size == null ? "" : cache.size.id); - values.put("difficulty", cache.difficulty); - values.put("terrain", cache.terrain); - values.put("latlon", cache.latlon); - values.put("location", cache.location); - values.put("distance", cache.distance); - values.put("direction", cache.direction); - putCoords(values, cache.coords); - values.put("reliable_latlon", cache.reliableLatLon ? 1 : 0); - values.put("elevation", cache.elevation); - values.put("shortdesc", cache.shortdesc); - values.put("personal_note", cache.personalNote); + values.put("hidden", cache.getHidden().getTime()); + } + values.put("hint", cache.getHint()); + values.put("size", cache.getSize() == null ? "" : cache.getSize().id); + values.put("difficulty", cache.getDifficulty()); + values.put("terrain", cache.getTerrain()); + values.put("latlon", cache.getLatlon()); + values.put("location", cache.getLocation()); + values.put("distance", cache.getDistance()); + values.put("direction", cache.getDirection()); + putCoords(values, cache.getCoords()); + values.put("reliable_latlon", cache.isReliableLatLon() ? 1 : 0); + values.put("elevation", cache.getElevation()); + values.put("shortdesc", cache.getShortdesc()); + values.put("personal_note", cache.getPersonalNote()); values.put("description", cache.getDescription()); - values.put("favourite_cnt", cache.favouriteCnt); - values.put("rating", cache.rating); - values.put("votes", cache.votes); - values.put("myvote", cache.myVote); - values.put("disabled", cache.disabled ? 1 : 0); - values.put("archived", cache.archived ? 1 : 0); - values.put("members", cache.members ? 1 : 0); - values.put("found", cache.found ? 1 : 0); - values.put("favourite", cache.favourite ? 1 : 0); - values.put("inventoryunknown", cache.inventoryItems); - values.put("onWatchlist", cache.onWatchlist ? 1 : 0); + values.put("favourite_cnt", cache.getFavouriteCnt()); + values.put("rating", cache.getRating()); + values.put("votes", cache.getVotes()); + values.put("myvote", cache.getMyVote()); + values.put("disabled", cache.isDisabled() ? 1 : 0); + values.put("archived", cache.isArchived() ? 1 : 0); + values.put("members", cache.isMembers() ? 1 : 0); + values.put("found", cache.isFound() ? 1 : 0); + values.put("favourite", cache.isFavourite() ? 1 : 0); + values.put("inventoryunknown", cache.getInventoryItems()); + values.put("onWatchlist", cache.isOnWatchlist() ? 1 : 0); boolean statusOk = true; - if (cache.attributes != null) { - if (!saveAttributes(cache.geocode, cache.attributes)) { + if (cache.getAttributes() != null) { + if (!saveAttributes(cache.getGeocode(), cache.getAttributes())) { statusOk = false; } } - if (cache.waypoints != null) { - if (!saveWaypoints(cache.geocode, cache.waypoints, true)) { + if (cache.getWaypoints() != null) { + if (!saveWaypoints(cache.getGeocode(), cache.getWaypoints(), true)) { statusOk = false; } } - if (cache.spoilers != null) { - if (!saveSpoilers(cache.geocode, cache.spoilers)) { + if (cache.getSpoilers() != null) { + if (!saveSpoilers(cache.getGeocode(), cache.getSpoilers())) { statusOk = false; } } - if (cache.logs != null) { - if (!saveLogs(cache.geocode, cache.logs)) { + if (cache.getLogs() != null) { + if (!saveLogs(cache.getGeocode(), cache.getLogs())) { statusOk = false; } } - if (MapUtils.isNotEmpty(cache.logCounts)) { - if (!saveLogCount(cache.geocode, cache.logCounts)) { + if (MapUtils.isNotEmpty(cache.getLogCounts())) { + if (!saveLogCount(cache.getGeocode(), cache.getLogCounts())) { statusOk = false; } } - if (cache.inventory != null) { - if (!saveInventory(cache.geocode, cache.inventory)) { + if (cache.getInventory() != null) { + if (!saveInventory(cache.getGeocode(), cache.getInventory())) { statusOk = false; } } if (!statusOk) { - cache.detailed = false; - cache.detailedUpdate = 0L; + cache.setDetailed(false); + cache.setDetailedUpdate(0L); } init(); //try to update record else insert fresh.. try { - int rows = databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { cache.geocode }); + int rows = databaseRW.update(dbTableCaches, values, "geocode = ?", new String[] { cache.getGeocode() }); if (rows > 0) { values = null; return true; @@ -1414,13 +1415,13 @@ public class cgData { values.clear(); values.put("geocode", geocode); values.put("updated", timeStamp); - values.put("type", oneWaypoint.type != null ? oneWaypoint.type.id : null); + values.put("type", oneWaypoint.getWaypointType() != null ? oneWaypoint.getWaypointType().id : null); values.put("prefix", oneWaypoint.getPrefix()); - values.put("lookup", oneWaypoint.lookup); - values.put("name", oneWaypoint.name); - values.put("latlon", oneWaypoint.latlon); - putCoords(values, oneWaypoint.coords); - values.put("note", oneWaypoint.note); + values.put("lookup", oneWaypoint.getLookup()); + values.put("name", oneWaypoint.getName()); + values.put("latlon", oneWaypoint.getLatlon()); + putCoords(values, oneWaypoint.getCoords()); + values.put("note", oneWaypoint.getNote()); databaseRW.insert(dbTableWaypoints, null, values); } @@ -1500,13 +1501,13 @@ public class cgData { ContentValues values = new ContentValues(); values.put("geocode", geocode); values.put("updated", System.currentTimeMillis()); - values.put("type", waypoint.type != null ? waypoint.type.id : null); + values.put("type", waypoint.getWaypointType() != null ? waypoint.getWaypointType().id : null); values.put("prefix", waypoint.getPrefix()); - values.put("lookup", waypoint.lookup); - values.put("name", waypoint.name); - values.put("latlon", waypoint.latlon); - putCoords(values, waypoint.coords); - values.put("note", waypoint.note); + values.put("lookup", waypoint.getLookup()); + values.put("name", waypoint.getName()); + values.put("latlon", waypoint.getLatlon()); + putCoords(values, waypoint.getCoords()); + values.put("note", waypoint.getNote()); if (id <= 0) { databaseRW.insert(dbTableWaypoints, null, values); @@ -1794,7 +1795,7 @@ public class cgData { * @return the loaded cache */ - public cgCache loadCache(String geocode, String guid, boolean loadAttributes, boolean loadWaypoints, boolean loadSpoilers, boolean loadLogs, boolean loadInventory, boolean loadOfflineLogs) { + public cgCache loadCache(final String geocode, final String guid, final int loadFlags) { Object[] geocodes = new Object[1]; Object[] guids = new Object[1]; @@ -1810,7 +1811,7 @@ public class cgData { guids = null; } - List<cgCache> caches = loadCaches(geocodes, null, null, null, null, null, loadAttributes, loadWaypoints, loadSpoilers, loadLogs, loadInventory, loadOfflineLogs); + List<cgCache> caches = loadCaches(geocodes, null, null, null, null, null, loadFlags); if (CollectionUtils.isNotEmpty(caches)) { return caches.get(0); } @@ -1818,7 +1819,7 @@ public class cgData { return null; } - public List<cgCache> loadCaches(Object[] geocodes, Object[] guids, Long centerLat, Long centerLon, Long spanLat, Long spanLon, boolean loadAttributes, boolean loadWaypoints, boolean loadSpoilers, boolean loadLogs, boolean loadInventory, boolean loadOfflineLogs) { + public List<cgCache> loadCaches(final Object[] geocodes, final Object[] guids, final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final int loadFlags) { init(); // Using more than one of the parametersets results in overly comlex wheres if (((geocodes != null && geocodes.length > 0) && (guids != null && guids.length > 0))) { @@ -1925,76 +1926,76 @@ public class cgData { cgCache cache = createCacheFromDatabaseContent(cursor); // FIXME: in the following code (and similar blocks below), the - // cache.attributes entity probably does not need to be preserved, + // cache.getAttributes() entity probably does not need to be preserved, // and the resolution of the "if" statement could be simply - // cache.attributes = attributes - if (loadAttributes) { - final List<String> attributes = loadAttributes(cache.geocode); + // cache.getAttributes() = attributes + if ((loadFlags & cgCache.LOADATTRIBUTES) != 0) { + final List<String> attributes = loadAttributes(cache.getGeocode()); if (CollectionUtils.isNotEmpty(attributes)) { - if (cache.attributes == null) { - cache.attributes = new ArrayList<String>(); + if (cache.getAttributes() == null) { + cache.setAttributes(new ArrayList<String>()); } else { - cache.attributes.clear(); + cache.getAttributes().clear(); } - cache.attributes.addAll(attributes); + cache.getAttributes().addAll(attributes); } } - if (loadWaypoints) { - final List<cgWaypoint> waypoints = loadWaypoints(cache.geocode); + if ((loadFlags & cgCache.LOADWAYPOINTS) != 0) { + final List<cgWaypoint> waypoints = loadWaypoints(cache.getGeocode()); if (CollectionUtils.isNotEmpty(waypoints)) { - if (cache.waypoints == null) { - cache.waypoints = new ArrayList<cgWaypoint>(); + if (cache.getWaypoints() == null) { + cache.setWaypoints(new ArrayList<cgWaypoint>()); } else { - cache.waypoints.clear(); + cache.getWaypoints().clear(); } - cache.waypoints.addAll(waypoints); + cache.getWaypoints().addAll(waypoints); } } - if (loadSpoilers) { - final List<cgImage> spoilers = loadSpoilers(cache.geocode); + if ((loadFlags & cgCache.LOADSPOILERS) != 0) { + final List<cgImage> spoilers = loadSpoilers(cache.getGeocode()); if (CollectionUtils.isNotEmpty(spoilers)) { - if (cache.spoilers == null) { - cache.spoilers = new ArrayList<cgImage>(); + if (cache.getSpoilers() == null) { + cache.setSpoilers(new ArrayList<cgImage>()); } else { - cache.spoilers.clear(); + cache.getSpoilers().clear(); } - cache.spoilers.addAll(spoilers); + cache.getSpoilers().addAll(spoilers); } } - if (loadLogs) { - final List<cgLog> logs = loadLogs(cache.geocode); + if ((loadFlags & cgCache.LOADLOGS) != 0) { + final List<cgLog> logs = loadLogs(cache.getGeocode()); if (CollectionUtils.isNotEmpty(logs)) { - if (cache.logs == null) { - cache.logs = new ArrayList<cgLog>(); + if (cache.getLogs() == null) { + cache.setLogs(new ArrayList<cgLog>()); } else { - cache.logs.clear(); + cache.getLogs().clear(); } - cache.logs.addAll(logs); + cache.getLogs().addAll(logs); } - final Map<Integer, Integer> logCounts = loadLogCounts(cache.geocode); + final Map<Integer, Integer> logCounts = loadLogCounts(cache.getGeocode()); if (MapUtils.isNotEmpty(logCounts)) { - cache.logCounts.clear(); - cache.logCounts.putAll(logCounts); + cache.getLogCounts().clear(); + cache.getLogCounts().putAll(logCounts); } } - if (loadInventory) { - final List<cgTrackable> inventory = loadInventory(cache.geocode); + if ((loadFlags & cgCache.LOADINVENTORY) != 0) { + final List<cgTrackable> inventory = loadInventory(cache.getGeocode()); if (CollectionUtils.isNotEmpty(inventory)) { - if (cache.inventory == null) { - cache.inventory = new ArrayList<cgTrackable>(); + if (cache.getInventory() == null) { + cache.setInventory(new ArrayList<cgTrackable>()); } else { - cache.inventory.clear(); + cache.getInventory().clear(); } - cache.inventory.addAll(inventory); + cache.getInventory().addAll(inventory); } } - if (loadOfflineLogs) { - cache.logOffline = hasLogOffline(cache.geocode); + if ((loadFlags & cgCache.LOADOFFLINELOG) != 0) { + cache.setLogOffline(hasLogOffline(cache.getGeocode())); } caches.add(cache); @@ -2067,60 +2068,60 @@ public class cgData { cacheColumnIndex[36] = cursor.getColumnIndex("reliable_latlon"); } - cache.updated = cursor.getLong(cacheColumnIndex[0]); - cache.reason = cursor.getInt(cacheColumnIndex[1]); - cache.detailed = cursor.getInt(cacheColumnIndex[2]) == 1; - cache.detailedUpdate = cursor.getLong(cacheColumnIndex[3]); - cache.visitedDate = cursor.getLong(cacheColumnIndex[4]); - cache.geocode = cursor.getString(cacheColumnIndex[5]); - cache.cacheId = cursor.getString(cacheColumnIndex[6]); - cache.guid = cursor.getString(cacheColumnIndex[7]); - cache.type = cursor.getString(cacheColumnIndex[8]); - cache.name = cursor.getString(cacheColumnIndex[9]); - cache.own = cursor.getInt(cacheColumnIndex[10]) == 1; - cache.owner = cursor.getString(cacheColumnIndex[11]); - cache.ownerReal = cursor.getString(cacheColumnIndex[12]); - cache.hidden = new Date(cursor.getLong(cacheColumnIndex[13])); - cache.hint = cursor.getString(cacheColumnIndex[14]); - cache.size = CacheSize.FIND_BY_ID.get(cursor.getString(cacheColumnIndex[15])); - cache.difficulty = cursor.getFloat(cacheColumnIndex[16]); + cache.setUpdated(cursor.getLong(cacheColumnIndex[0])); + cache.setReason(cursor.getInt(cacheColumnIndex[1])); + cache.setDetailed(cursor.getInt(cacheColumnIndex[2]) == 1); + cache.setDetailedUpdate(cursor.getLong(cacheColumnIndex[3])); + cache.setVisitedDate(cursor.getLong(cacheColumnIndex[4])); + cache.setGeocode(cursor.getString(cacheColumnIndex[5])); + cache.setCacheId(cursor.getString(cacheColumnIndex[6])); + cache.setGuid(cursor.getString(cacheColumnIndex[7])); + cache.setCacheType(CacheType.getById(cursor.getString(cacheColumnIndex[8]))); + cache.setName(cursor.getString(cacheColumnIndex[9])); + cache.setOwn(cursor.getInt(cacheColumnIndex[10]) == 1); + cache.setOwner(cursor.getString(cacheColumnIndex[11])); + cache.setOwnerReal(cursor.getString(cacheColumnIndex[12])); + cache.setHidden(new Date(cursor.getLong(cacheColumnIndex[13]))); + cache.setHint(cursor.getString(cacheColumnIndex[14])); + cache.setSize(CacheSize.FIND_BY_ID.get(cursor.getString(cacheColumnIndex[15]))); + cache.setDifficulty(cursor.getFloat(cacheColumnIndex[16])); index = cacheColumnIndex[17]; if (cursor.isNull(index)) { - cache.direction = null; + cache.setDirection(null); } else { - cache.direction = cursor.getFloat(index); + cache.setDirection(cursor.getFloat(index)); } index = cacheColumnIndex[18]; if (cursor.isNull(index)) { - cache.distance = null; + cache.setDistance(null); } else { - cache.distance = cursor.getFloat(index); + cache.setDistance(cursor.getFloat(index)); } - cache.terrain = cursor.getFloat(cacheColumnIndex[19]); - cache.latlon = cursor.getString(cacheColumnIndex[20]); - cache.location = cursor.getString(cacheColumnIndex[21]); - cache.coords = getCoords(cursor); + cache.setTerrain(cursor.getFloat(cacheColumnIndex[19])); + cache.setLatlon(cursor.getString(cacheColumnIndex[20])); + cache.setLocation(cursor.getString(cacheColumnIndex[21])); + cache.setCoords(getCoords(cursor)); index = cacheColumnIndex[22]; if (cursor.isNull(index)) { - cache.elevation = null; + cache.setElevation(null); } else { - cache.elevation = cursor.getDouble(index); + cache.setElevation(cursor.getDouble(index)); } - cache.personalNote = cursor.getString(cacheColumnIndex[23]); - cache.shortdesc = cursor.getString(cacheColumnIndex[24]); + cache.setPersonalNote(cursor.getString(cacheColumnIndex[23])); + cache.setShortdesc(cursor.getString(cacheColumnIndex[24])); // do not set cache.description ! - cache.favouriteCnt = cursor.getInt(cacheColumnIndex[25]); - cache.rating = cursor.getFloat(cacheColumnIndex[26]); - cache.votes = cursor.getInt(cacheColumnIndex[27]); - cache.myVote = cursor.getFloat(cacheColumnIndex[28]); - cache.disabled = cursor.getInt(cacheColumnIndex[29]) == 1; - cache.archived = cursor.getInt(cacheColumnIndex[30]) == 1; - cache.members = cursor.getInt(cacheColumnIndex[31]) == 1; - cache.found = cursor.getInt(cacheColumnIndex[32]) == 1; - cache.favourite = cursor.getInt(cacheColumnIndex[33]) == 1; - cache.inventoryItems = cursor.getInt(cacheColumnIndex[34]); - cache.onWatchlist = cursor.getInt(cacheColumnIndex[35]) == 1; - cache.reliableLatLon = cursor.getInt(cacheColumnIndex[36]) > 0; + cache.setFavouriteCnt(cursor.getInt(cacheColumnIndex[25])); + cache.setRating(cursor.getFloat(cacheColumnIndex[26])); + cache.setVotes(cursor.getInt(cacheColumnIndex[27])); + cache.setMyVote(cursor.getFloat(cacheColumnIndex[28])); + cache.setDisabled(cursor.getInt(cacheColumnIndex[29]) == 1); + cache.setArchived(cursor.getInt(cacheColumnIndex[30]) == 1); + cache.setMembers(cursor.getInt(cacheColumnIndex[31]) == 1); + cache.setFound(cursor.getInt(cacheColumnIndex[32]) == 1); + cache.setFavourite(cursor.getInt(cacheColumnIndex[33]) == 1); + cache.setInventoryItems(cursor.getInt(cacheColumnIndex[34])); + cache.setOnWatchlist(cursor.getInt(cacheColumnIndex[35]) == 1); + cache.setReliableLatLon(cursor.getInt(cacheColumnIndex[36]) > 0); return cache; } @@ -2231,15 +2232,15 @@ public class cgData { private static cgWaypoint createWaypointFromDatabaseContent(Cursor cursor) { cgWaypoint waypoint = new cgWaypoint(); - waypoint.id = cursor.getInt(cursor.getColumnIndex("_id")); - waypoint.geocode = cursor.getString(cursor.getColumnIndex("geocode")); - waypoint.type = WaypointType.FIND_BY_ID.get(cursor.getString(cursor.getColumnIndex("type"))); + waypoint.setId(cursor.getInt(cursor.getColumnIndex("_id"))); + waypoint.setGeocode(cursor.getString(cursor.getColumnIndex("geocode"))); + waypoint.setWaypointType(WaypointType.FIND_BY_ID.get(cursor.getString(cursor.getColumnIndex("type")))); waypoint.setPrefix(cursor.getString(cursor.getColumnIndex("prefix"))); - waypoint.lookup = cursor.getString(cursor.getColumnIndex("lookup")); - waypoint.name = cursor.getString(cursor.getColumnIndex("name")); - waypoint.latlon = cursor.getString(cursor.getColumnIndex("latlon")); - waypoint.coords = getCoords(cursor); - waypoint.note = cursor.getString(cursor.getColumnIndex("note")); + waypoint.setLookup(cursor.getString(cursor.getColumnIndex("lookup"))); + waypoint.setName(cursor.getString(cursor.getColumnIndex("name"))); + waypoint.setLatlon(cursor.getString(cursor.getColumnIndex("latlon"))); + waypoint.setCoords(getCoords(cursor)); + waypoint.setNote(cursor.getString(cursor.getColumnIndex("note"))); return waypoint; } diff --git a/main/src/cgeo/geocaching/cgDestination.java b/main/src/cgeo/geocaching/cgDestination.java index 96beec7..10753f4 100644 --- a/main/src/cgeo/geocaching/cgDestination.java +++ b/main/src/cgeo/geocaching/cgDestination.java @@ -58,7 +58,7 @@ public class cgDestination { return false; } cgDestination other = (cgDestination) obj; - return coords.isEqualTo(other.coords); + return coords.isEqualTo(other.getCoords()); } public long getId() { diff --git a/main/src/cgeo/geocaching/cgSearch.java b/main/src/cgeo/geocaching/cgSearch.java index fb217fb..b96b1cd 100644 --- a/main/src/cgeo/geocaching/cgSearch.java +++ b/main/src/cgeo/geocaching/cgSearch.java @@ -2,40 +2,86 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.StatusCode; +import android.os.Parcel; +import android.os.Parcelable; + import java.util.ArrayList; +import java.util.Collections; import java.util.List; -import java.util.UUID; -public class cgSearch { - private UUID id; - private List<String> geocodes = new ArrayList<String>(); +public class cgSearch implements Parcelable { + final private List<String> geocodes; public StatusCode error = null; public String url = ""; public String[] viewstates = null; public int totalCnt = 0; + final public static Parcelable.Creator<cgSearch> CREATOR = new Parcelable.Creator<cgSearch>() { + public cgSearch createFromParcel(Parcel in) { + return new cgSearch(in); + } + + public cgSearch[] newArray(int size) { + return new cgSearch[size]; + } + }; + public cgSearch() { - id = UUID.randomUUID(); + this((List<String>) null); } - public UUID getCurrentId() { - return id; + public cgSearch(final List<String> geocodes) { + if (geocodes == null) { + this.geocodes = new ArrayList<String>(); + } else { + this.geocodes = new ArrayList<String>(geocodes.size()); + this.geocodes.addAll(geocodes); + } + } + + public cgSearch(final Parcel in) { + geocodes = new ArrayList<String>(); + in.readStringList(geocodes); + error = (StatusCode) in.readSerializable(); + url = in.readString(); + final int length = in.readInt(); + if (length >= 0) { + viewstates = new String[length]; + in.readStringArray(viewstates); + } + totalCnt = in.readInt(); + } + + @Override + public void writeToParcel(final Parcel out, final int flags) { + out.writeStringList(geocodes); + out.writeSerializable(error); + out.writeString(url); + if (viewstates == null) { + out.writeInt(-1); + } else { + out.writeInt(viewstates.length); + out.writeStringArray(viewstates); + } + out.writeInt(totalCnt); + } + + @Override + public int describeContents() { + return 0; } public List<String> getGeocodes() { - return geocodes; + return Collections.unmodifiableList(geocodes); } public int getCount() { return geocodes.size(); } - public void addGeocode(String geocode) { - if (geocodes == null) { - geocodes = new ArrayList<String>(); - } - + public void addGeocode(final String geocode) { geocodes.add(geocode); } + } diff --git a/main/src/cgeo/geocaching/cgTrackable.java b/main/src/cgeo/geocaching/cgTrackable.java index 29001a8..5cde2f5 100644 --- a/main/src/cgeo/geocaching/cgTrackable.java +++ b/main/src/cgeo/geocaching/cgTrackable.java @@ -6,7 +6,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -public class cgTrackable { +public class cgTrackable implements ILogable { static final public int SPOTTED_UNSET = 0; static final public int SPOTTED_CACHE = 1; static final public int SPOTTED_USER = 2; @@ -194,4 +194,5 @@ public class cgTrackable { public void setLogs(List<cgLog> logs) { this.logs = logs; } + } diff --git a/main/src/cgeo/geocaching/cgWaypoint.java b/main/src/cgeo/geocaching/cgWaypoint.java index b454891..d8db277 100644 --- a/main/src/cgeo/geocaching/cgWaypoint.java +++ b/main/src/cgeo/geocaching/cgWaypoint.java @@ -10,16 +10,17 @@ import android.widget.TextView; import java.util.List; -public class cgWaypoint implements Comparable<cgWaypoint> { - public Integer id = 0; - public String geocode = "geocode"; - public WaypointType type = WaypointType.WAYPOINT; +public class cgWaypoint implements IWaypoint, Comparable<cgWaypoint> { + + private Integer id = 0; + private String geocode = "geocode"; + private WaypointType waypointType = WaypointType.WAYPOINT; private String prefix = ""; - public String lookup = ""; - public String name = ""; - public String latlon = ""; - public Geopoint coords = null; - public String note = ""; + private String lookup = ""; + private String name = ""; + private String latlon = ""; + private Geopoint coords = null; + private String note = ""; private Integer cachedOrder = null; /** @@ -39,7 +40,7 @@ public class cgWaypoint implements Comparable<cgWaypoint> { } public void setIcon(final Resources res, final TextView nameView) { - nameView.setCompoundDrawablesWithIntrinsicBounds(res.getDrawable(type.drawableId), null, null, null); + nameView.setCompoundDrawablesWithIntrinsicBounds(res.getDrawable(waypointType.drawableId), null, null, null); } public void merge(final cgWaypoint old) { @@ -50,13 +51,13 @@ public class cgWaypoint implements Comparable<cgWaypoint> { lookup = old.lookup; } if (StringUtils.isBlank(name)) { - this.name = old.name; + setName(old.getName()); } if (StringUtils.isBlank(latlon) || latlon.startsWith("?")) { // there are waypoints containing "???" latlon = old.latlon; } if (coords == null) { - coords = old.coords; + coords = old.getCoords(); } if (StringUtils.isBlank(note)) { note = old.note; @@ -74,10 +75,10 @@ public class cgWaypoint implements Comparable<cgWaypoint> { if (newPoints != null && oldPoints != null) { for (cgWaypoint old : oldPoints) { boolean merged = false; - if (old != null && old.name != null && old.name.length() > 0) { + if (old != null && old.getName() != null && old.getName().length() > 0) { for (cgWaypoint waypoint : newPoints) { - if (waypoint != null && waypoint.name != null) { - if (old.name.equalsIgnoreCase(waypoint.name)) { + if (waypoint != null && waypoint.getName() != null) { + if (old.getName().equalsIgnoreCase(waypoint.getName())) { waypoint.merge(old); merged = true; break; @@ -94,16 +95,16 @@ public class cgWaypoint implements Comparable<cgWaypoint> { } public boolean isUserDefined() { - return type == WaypointType.OWN; + return waypointType == WaypointType.OWN; } public void setUserDefined() { - type = WaypointType.OWN; + waypointType = WaypointType.OWN; setPrefix("OWN"); } private int computeOrder() { - switch (type) { + switch (waypointType) { case PARKING: return -1; case TRAILHEAD: @@ -145,4 +146,77 @@ public class cgWaypoint implements Comparable<cgWaypoint> { public String getUrl() { return "http://coord.info/" + geocode.toUpperCase(); } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getGeocode() { + return geocode; + } + + public void setGeocode(String geocode) { + this.geocode = geocode; + } + + public WaypointType getWaypointType() { + return waypointType; + } + + public void setWaypointType(WaypointType type) { + this.waypointType = type; + } + + public String getLookup() { + return lookup; + } + + public void setLookup(String lookup) { + this.lookup = lookup; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getLatlon() { + return latlon; + } + + public void setLatlon(String latlon) { + this.latlon = latlon; + } + + public Geopoint getCoords() { + return coords; + } + + public void setCoords(Geopoint coords) { + this.coords = coords; + } + + public String getNote() { + return note; + } + + public void setNote(String note) { + this.note = note; + } + + public Integer getCachedOrder() { + return cachedOrder; + } + + public void setCachedOrder(Integer cachedOrder) { + this.cachedOrder = cachedOrder; + } + }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/cgeo.java b/main/src/cgeo/geocaching/cgeo.java index 8014c7c..313d4b7 100644 --- a/main/src/cgeo/geocaching/cgeo.java +++ b/main/src/cgeo/geocaching/cgeo.java @@ -250,7 +250,7 @@ public class cgeo extends AbstractActivity { menu.add(0, MENU_SETTINGS, 0, res.getString(R.string.menu_settings)).setIcon(android.R.drawable.ic_menu_preferences); menu.add(0, MENU_HISTORY, 0, res.getString(R.string.menu_history)).setIcon(android.R.drawable.ic_menu_recent_history); menu.add(0, MENU_HELPERS, 0, res.getString(R.string.menu_helpers)).setIcon(R.drawable.ic_menu_shopping); - menu.add(0, MENU_SCAN, 0, res.getString(R.string.menu_scan)).setIcon(R.drawable.ic_menu_barcode); + menu.add(0, MENU_SCAN, 0, res.getString(R.string.menu_scan_geo)).setIcon(R.drawable.ic_menu_barcode); menu.add(0, MENU_ABOUT, 0, res.getString(R.string.menu_about)).setIcon(android.R.drawable.ic_menu_info_details); return true; } diff --git a/main/src/cgeo/geocaching/cgeoapplication.java b/main/src/cgeo/geocaching/cgeoapplication.java index ac82c1a..7c93c47 100644 --- a/main/src/cgeo/geocaching/cgeoapplication.java +++ b/main/src/cgeo/geocaching/cgeoapplication.java @@ -16,7 +16,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; public class cgeoapplication extends Application { @@ -27,7 +26,6 @@ public class cgeoapplication extends Application { private boolean geoInUse = false; private cgDirection dir = null; private boolean dirInUse = false; - final private Map<UUID, cgSearch> searches = new HashMap<UUID, cgSearch>(); // information about searches final private Map<String, cgCache> cachesCache = new HashMap<String, cgCache>(); // caching caches into memory public boolean firstRun = true; // c:geo is just launched public boolean showLoginToast = true; //login toast shown just once. @@ -217,117 +215,106 @@ public class cgeoapplication extends Application { return getStorage().getCacheidForGeocode(geocode); } - public StatusCode getError(final UUID searchId) { - if (unknownSearch(searchId)) { + public static StatusCode getError(final cgSearch search) { + if (search == null) { return null; } - return searches.get(searchId).error; + return search.error; } - public boolean setError(final UUID searchId, final StatusCode error) { - if (unknownSearch(searchId)) { + public static boolean setError(final cgSearch search, final StatusCode error) { + if (search == null) { return false; } - searches.get(searchId).error = error; + search.error = error; return true; } - public String getUrl(final UUID searchId) { - if (unknownSearch(searchId)) { + public static String getUrl(final cgSearch search) { + if (search == null) { return null; } - return searches.get(searchId).url; + return search.url; } - public boolean setUrl(final UUID searchId, String url) { - if (unknownSearch(searchId)) { + public static boolean setUrl(final cgSearch search, String url) { + if (search == null) { return false; } - searches.get(searchId).url = url; + search.url = url; return true; } - public String[] getViewstates(final UUID searchId) { - if (unknownSearch(searchId)) { + public static String[] getViewstates(final cgSearch search) { + if (search == null) { return null; } - return searches.get(searchId).viewstates; + return search.viewstates; } - public boolean setViewstates(final UUID searchId, String[] viewstates) { - if (cgBase.isEmpty(viewstates)) { - return false; - } - if (unknownSearch(searchId)) { + public static boolean setViewstates(final cgSearch search, String[] viewstates) { + if (cgBase.isEmpty(viewstates) || search == null) { return false; } - searches.get(searchId).viewstates = viewstates; + search.viewstates = viewstates; return true; } - public Integer getTotal(final UUID searchId) { - if (unknownSearch(searchId)) { + public static Integer getTotal(final cgSearch search) { + if (search == null) { return null; } - return searches.get(searchId).totalCnt; + return search.totalCnt; } - public Integer getCount(final UUID searchId) { - if (unknownSearch(searchId)) { + public static Integer getCount(final cgSearch search) { + if (search == null) { return 0; } - return searches.get(searchId).getCount(); + return search.getCount(); } - public boolean hasUnsavedCaches(final UUID searchId) { - if (unknownSearch(searchId)) { + public boolean hasUnsavedCaches(final cgSearch search) { + if (search == null) { return false; } - List<String> geocodes = searches.get(searchId).getGeocodes(); - if (geocodes != null) { - for (String geocode : geocodes) { - if (!isOffline(geocode, null)) { - return true; - } + for (final String geocode : search.getGeocodes()) { + if (!isOffline(geocode, null)) { + return true; } } return false; } - private boolean unknownSearch(final UUID searchId) { - return searchId == null || !searches.containsKey(searchId); - } - public cgCache getCacheByGeocode(String geocode) { - return getCacheByGeocode(geocode, false, true, false, false, false, false); - } - - public cgCache getCacheByGeocode(String geocode, boolean loadAttributes, boolean loadWaypoints, boolean loadSpoilers, boolean loadLogs, boolean loadInventory, boolean loadOfflineLog) { if (StringUtils.isBlank(geocode)) { return null; } - cgCache cache = null; + return getCacheByGeocode(geocode, cgCache.LOADWAYPOINTS); + } + + public cgCache getCacheByGeocode(final String geocode, final int loadFlags) { if (cachesCache.containsKey(geocode)) { - cache = cachesCache.get(geocode); - } else { - cache = getStorage().loadCache(geocode, null, loadAttributes, loadWaypoints, loadSpoilers, loadLogs, loadInventory, loadOfflineLog); + return cachesCache.get(geocode); + } - if (cache != null && cache.detailed && loadAttributes && loadWaypoints && loadSpoilers && loadLogs && loadInventory) { - putCacheInCache(cache); - } + final cgCache cache = getStorage().loadCache(geocode, null, loadFlags); + + if (cache != null && cache.getDetailed() && loadFlags == cgCache.LOADALL) { + putCacheInCache(cache); } return cache; @@ -351,15 +338,15 @@ public class cgeoapplication extends Application { } public void putCacheInCache(cgCache cache) { - if (cache == null || cache.geocode == null) { + if (cache == null || cache.getGeocode() == null) { return; } - if (cachesCache.containsKey(cache.geocode)) { - cachesCache.remove(cache.geocode); + if (cachesCache.containsKey(cache.getGeocode())) { + cachesCache.remove(cache.getGeocode()); } - cachesCache.put(cache.geocode, cache); + cachesCache.put(cache.getGeocode(), cache); } public String[] geocodesInCache() { @@ -385,8 +372,8 @@ public class cgeoapplication extends Application { return getBounds(geocodeList); } - public List<Object> getBounds(final UUID searchId) { - if (unknownSearch(searchId)) { + public List<Object> getBounds(final cgSearch search) { + if (search == null) { return null; } @@ -394,7 +381,6 @@ public class cgeoapplication extends Application { storage = new cgData(this); } - final cgSearch search = searches.get(searchId); final List<String> geocodeList = search.getGeocodes(); return getBounds(geocodeList); @@ -408,37 +394,35 @@ public class cgeoapplication extends Application { return getStorage().getBounds(geocodes.toArray()); } - public cgCache getCache(final UUID searchId) { - if (unknownSearch(searchId)) { + public cgCache getCache(final cgSearch search) { + if (search == null) { return null; } - cgSearch search = searches.get(searchId); - List<String> geocodeList = search.getGeocodes(); + final List<String> geocodeList = search.getGeocodes(); - return getCacheByGeocode(geocodeList.get(0), true, true, true, true, true, true); + return getCacheByGeocode(geocodeList.get(0), cgCache.LOADALL); } /** - * @param searchId + * @param search * @param loadWaypoints * only load waypoints for map usage. All other callers should set this to <code>false</code> * @return */ - public List<cgCache> getCaches(final UUID searchId, final boolean loadWaypoints) { - return getCaches(searchId, null, null, null, null, false, loadWaypoints, false, false, false, true); + public List<cgCache> getCaches(final cgSearch search, final boolean loadWaypoints) { + return getCaches(search, null, null, null, null, (loadWaypoints ? cgCache.LOADWAYPOINTS : 0) | cgCache.LOADOFFLINELOG); } - public List<cgCache> getCaches(final UUID searchId, Long centerLat, Long centerLon, Long spanLat, Long spanLon) { - return getCaches(searchId, centerLat, centerLon, spanLat, spanLon, false, true, false, false, false, true); + public List<cgCache> getCaches(final cgSearch search, Long centerLat, Long centerLon, Long spanLat, Long spanLon) { + return getCaches(search, centerLat, centerLon, spanLat, spanLon, cgCache.LOADWAYPOINTS | cgCache.LOADOFFLINELOG); } - public List<cgCache> getCaches(final UUID searchId, Long centerLat, Long centerLon, Long spanLat, Long spanLon, boolean loadA, boolean loadW, boolean loadS, boolean loadL, boolean loadI, boolean loadO) { - if (unknownSearch(searchId)) { + public List<cgCache> getCaches(final cgSearch search, final Long centerLat, final Long centerLon, final Long spanLat, final Long spanLon, final int loadFlags) { + if (search == null) { List<cgCache> cachesOut = new ArrayList<cgCache>(); - final List<cgCache> cachesPre = storage.loadCaches(null, null, centerLat, centerLon, spanLat, spanLon, loadA, loadW, loadS, loadL, loadI, loadO); - + final List<cgCache> cachesPre = storage.loadCaches(null, null, centerLat, centerLon, spanLat, spanLon, loadFlags); if (cachesPre != null) { cachesOut.addAll(cachesPre); } @@ -448,11 +432,10 @@ public class cgeoapplication extends Application { List<cgCache> cachesOut = new ArrayList<cgCache>(); - cgSearch search = searches.get(searchId); - List<String> geocodeList = search.getGeocodes(); + final List<String> geocodeList = search.getGeocodes(); // The list of geocodes is sufficient. more parameters generate an overly complex select. - final List<cgCache> cachesPre = getStorage().loadCaches(geocodeList.toArray(), null, null, null, null, null, loadA, loadW, loadS, loadL, loadI, loadO); + final List<cgCache> cachesPre = getStorage().loadCaches(geocodeList.toArray(), null, null, null, null, null, loadFlags); if (cachesPre != null) { cachesOut.addAll(cachesPre); } @@ -460,27 +443,9 @@ public class cgeoapplication extends Application { return cachesOut; } - /** - * Create new search and register it - * - * @param geocodes - * the list of geocodes to search for - * @return the newly created search, which has been added to the list of searches - */ - private cgSearch createNewSearch(final List<String> geocodes) { - final cgSearch search = new cgSearch(); - if (CollectionUtils.isNotEmpty(geocodes)) { - for (final String gccode : geocodes) { - search.addGeocode(gccode); - } - } - searches.put(search.getCurrentId(), search); - return search; - } - public cgSearch getBatchOfStoredCaches(boolean detailedOnly, final Geopoint coords, String cachetype, int list) { final List<String> geocodes = getStorage().loadBatchOfStoredGeocodes(detailedOnly, coords, cachetype, list); - return createNewSearch(geocodes); + return new cgSearch(geocodes); } public List<cgDestination> getHistoryOfSearchedLocations() { @@ -489,22 +454,22 @@ public class cgeoapplication extends Application { public cgSearch getHistoryOfCaches(boolean detailedOnly, String cachetype) { final List<String> geocodes = getStorage().loadBatchOfHistoricGeocodes(detailedOnly, cachetype); - return createNewSearch(geocodes); + return new cgSearch(geocodes); } - public UUID getCachedInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { + public cgSearch getCachedInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { final List<String> geocodes = getStorage().getCachedInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); - return createNewSearch(geocodes).getCurrentId(); + return new cgSearch(geocodes); } - public UUID getStoredInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { + public cgSearch getStoredInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { final List<String> geocodes = getStorage().getStoredInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); - return createNewSearch(geocodes).getCurrentId(); + return new cgSearch(geocodes); } - public UUID getOfflineAll(String cachetype) { + public cgSearch getOfflineAll(String cachetype) { final List<String> geocodes = getStorage().getOfflineAll(cachetype); - return createNewSearch(geocodes).getCurrentId(); + return new cgSearch(geocodes); } public int getAllStoredCachesCount(boolean detailedOnly, String cachetype, Integer list) { @@ -561,44 +526,39 @@ public class cgeoapplication extends Application { return getStorage().saveInventory("---", list); } - public void addGeocode(final UUID searchId, String geocode) { - if (!this.searches.containsKey(searchId) || StringUtils.isBlank(geocode)) { + public static void addGeocode(final cgSearch search, final String geocode) { + if (search == null || StringUtils.isBlank(geocode)) { return; } - this.searches.get(searchId).addGeocode(geocode); + search.addGeocode(geocode); } - public UUID addSearch(final UUID searchId, List<cgCache> cacheList, Boolean newItem, int reason) { - if (!this.searches.containsKey(searchId)) { + public cgSearch addSearch(final cgSearch search, List<cgCache> cacheList, Boolean newItem, int reason) { + if (search == null) { return null; } - cgSearch search = this.searches.get(searchId); - return addSearch(search, cacheList, newItem, reason); } - public UUID addSearch(final cgSearch search, final List<cgCache> cacheList, final boolean newItem, final int reason) { + public cgSearch addSearch(final cgSearch search, final List<cgCache> cacheList, final boolean newItem, final int reason) { if (CollectionUtils.isEmpty(cacheList)) { return null; } - final UUID searchId = search.getCurrentId(); - searches.put(searchId, search); - if (storage == null) { storage = new cgData(this); } if (newItem) { // save only newly downloaded data for (final cgCache cache : cacheList) { - cache.reason = reason; + cache.setReason(reason); storeWithMerge(cache, false); } } - return searchId; + return search; } public boolean addCacheToSearch(cgSearch search, cgCache cache) { @@ -606,16 +566,10 @@ public class cgeoapplication extends Application { return false; } - final UUID searchId = search.getCurrentId(); - - if (!searches.containsKey(searchId)) { - searches.put(searchId, search); - } - - final boolean status = storeWithMerge(cache, cache.reason >= 1); + final boolean status = storeWithMerge(cache, cache.getReason() >= 1); if (status) { - search.addGeocode(cache.geocode); + search.addGeocode(cache.getGeocode()); } return status; @@ -633,8 +587,7 @@ public class cgeoapplication extends Application { private boolean storeWithMerge(final cgCache cache, final boolean override) { if (!override) { - final cgCache oldCache = storage.loadCache(cache.geocode, cache.guid, - true, true, true, true, true, true); + final cgCache oldCache = storage.loadCache(cache.getGeocode(), cache.getGuid(), cgCache.LOADALL); cache.gatherMissingFrom(oldCache); } return storage.saveCache(cache); diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java index 17a3ac2..ed9f583 100644 --- a/main/src/cgeo/geocaching/cgeocaches.java +++ b/main/src/cgeo/geocaching/cgeocaches.java @@ -74,7 +74,6 @@ import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.UUID; public class cgeocaches extends AbstractListActivity { @@ -153,7 +152,7 @@ public class cgeocaches extends AbstractListActivity { private String keyword = null; private String address = null; private String username = null; - private UUID searchId = null; + private cgSearch search = null; private List<cgCache> cacheList = new ArrayList<cgCache>(); private cgCacheListAdapter adapter = null; private LayoutInflater inflater = null; @@ -183,11 +182,11 @@ public class cgeocaches extends AbstractListActivity { @Override public void handleMessage(Message msg) { try { - if (searchId != null) { - setTitle(title + " [" + app.getCount(searchId) + "]"); + if (search != null) { + setTitle(title + " [" + cgeoapplication.getCount(search) + "]"); cacheList.clear(); - final List<cgCache> cacheListTmp = app.getCaches(searchId, false); + final List<cgCache> cacheListTmp = app.getCaches(search, false); if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); @@ -204,10 +203,10 @@ public class cgeocaches extends AbstractListActivity { showToast(res.getString(R.string.err_list_load_fail)); setMoreCaches(false); } else { - final Integer count = app.getTotal(searchId); + final Integer count = cgeoapplication.getTotal(search); if (count != null && count > 0) { - if (cacheList.size() < app.getTotal(searchId) && cacheList.size() < MAX_LIST_ITEMS) { + if (cacheList.size() < cgeoapplication.getTotal(search) && cacheList.size() < MAX_LIST_ITEMS) { setMoreCaches(true); } else { setMoreCaches(false); @@ -217,7 +216,7 @@ public class cgeocaches extends AbstractListActivity { } } - if (cacheList != null && app.getError(searchId) == StatusCode.UNAPPROVED_LICENSE) { + if (cacheList != null && cgeoapplication.getError(search) == StatusCode.UNAPPROVED_LICENSE) { AlertDialog.Builder dialog = new AlertDialog.Builder(cgeocaches.this); dialog.setTitle(res.getString(R.string.license)); dialog.setMessage(res.getString(R.string.err_license)); @@ -239,8 +238,8 @@ public class cgeocaches extends AbstractListActivity { AlertDialog alert = dialog.create(); alert.show(); - } else if (app != null && app.getError(searchId) != null) { - showToast(res.getString(R.string.err_download_fail) + app.getError(searchId).getErrorString(res) + "."); + } else if (app != null && cgeoapplication.getError(search) != null) { + showToast(res.getString(R.string.err_download_fail) + cgeoapplication.getError(search).getErrorString(res) + "."); hideLoading(); showProgress(false); @@ -281,11 +280,11 @@ public class cgeocaches extends AbstractListActivity { @Override public void handleMessage(Message msg) { try { - if (searchId != null) { - setTitle(title + " [" + app.getCount(searchId) + "]"); + if (search != null) { + setTitle(title + " [" + cgeoapplication.getCount(search) + "]"); cacheList.clear(); - final List<cgCache> cacheListTmp = app.getCaches(searchId, false); + final List<cgCache> cacheListTmp = app.getCaches(search, false); if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); @@ -304,9 +303,9 @@ public class cgeocaches extends AbstractListActivity { showToast(res.getString(R.string.err_list_load_fail)); setMoreCaches(false); } else { - final Integer count = app.getTotal(searchId); + final Integer count = cgeoapplication.getTotal(search); if (count != null && count > 0) { - if (cacheList.size() < app.getTotal(searchId) && cacheList.size() < MAX_LIST_ITEMS) { + if (cacheList.size() < cgeoapplication.getTotal(search) && cacheList.size() < MAX_LIST_ITEMS) { setMoreCaches(true); } else { setMoreCaches(false); @@ -316,8 +315,8 @@ public class cgeocaches extends AbstractListActivity { } } - if (app.getError(searchId) != null) { - showToast(res.getString(R.string.err_download_fail) + app.getError(searchId).getErrorString(res) + "."); + if (cgeoapplication.getError(search) != null) { + showToast(res.getString(R.string.err_download_fail) + cgeoapplication.getError(search).getErrorString(res) + "."); listFooter.setOnClickListener(new moreCachesListener()); hideLoading(); @@ -354,7 +353,7 @@ public class cgeocaches extends AbstractListActivity { if (msg.what > -1) { if (waitDialog != null) { - cacheList.get(msg.what).statusChecked = false; + cacheList.get(msg.what).setStatusChecked(false); if (adapter != null) { adapter.notifyDataSetChanged(); @@ -373,8 +372,8 @@ public class cgeocaches extends AbstractListActivity { } } } else { - if (cacheList != null && searchId != null) { - final List<cgCache> cacheListTmp = app.getCaches(searchId, false); + if (cacheList != null && search != null) { + final List<cgCache> cacheListTmp = app.getCaches(search, false); if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.clear(); cacheList.addAll(cacheListTmp); @@ -444,7 +443,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.clear(); - final List<cgCache> cacheListTmp = app.getCaches(searchId, false); + final List<cgCache> cacheListTmp = app.getCaches(search, false); if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); @@ -472,7 +471,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.clear(); - final List<cgCache> cacheListTmp = app.getCaches(searchId, false); + final List<cgCache> cacheListTmp = app.getCaches(search, false); if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); @@ -493,7 +492,7 @@ public class cgeocaches extends AbstractListActivity { setAdapter(); if (msg.what > -1) { - cacheList.get(msg.what).statusChecked = false; + cacheList.get(msg.what).setStatusChecked(false); } else { if (adapter != null) { adapter.setSelectMode(false, true); @@ -517,7 +516,7 @@ public class cgeocaches extends AbstractListActivity { if (msg.what > -1) { - cacheList.get(msg.what).statusChecked = false; + cacheList.get(msg.what).setStatusChecked(false); waitDialog.setProgress(detailProgress); } else if (-2 == msg.what) @@ -692,7 +691,7 @@ public class cgeocaches extends AbstractListActivity { title = res.getString(R.string.map_map); setTitle(title); showProgress(true); - searchId = (UUID) extras.get("searchId"); + search = (cgSearch) extras.get("search"); loadCachesHandler.sendMessage(Message.obtain()); break; default: @@ -729,9 +728,17 @@ public class cgeocaches extends AbstractListActivity { } } - if (loadCachesHandler != null && searchId != null) { + if (loadCachesHandler != null && search != null) { loadCachesHandler.sendEmptyMessage(0); } + + // refresh standard list if it has changed (new caches downloaded) + if (type == CacheListType.OFFLINE && listId == cgList.STANDARD_LIST_ID && search != null) { + cgSearch newSearch = base.searchByOffline(coords, cachetype, listId); + if (newSearch != null && newSearch.totalCnt != search.totalCnt) { + refreshCurrentList(); + } + } } @Override @@ -960,7 +967,7 @@ public class cgeocaches extends AbstractListActivity { item.setEnabled(false); for (cgCache cache : cacheList) { - if (cache.logOffline) + if (cache.isLogOffline()) { item.setEnabled(true); break; @@ -1084,7 +1091,7 @@ public class cgeocaches extends AbstractListActivity { return false; } - return CacheListAppFactory.onMenuItemSelected(item, geo, cacheList, this, res, searchId); + return CacheListAppFactory.onMenuItemSelected(item, geo, cacheList, this, res, search); } private void setComparator(MenuItem item, @@ -1151,20 +1158,20 @@ public class cgeocaches extends AbstractListActivity { } final cgCache cache = adapter.getItem(adapterInfo.position); - if (StringUtils.isNotBlank(cache.name)) { - menu.setHeaderTitle(cache.name); + if (StringUtils.isNotBlank(cache.getName())) { + menu.setHeaderTitle(cache.getName()); } else { - menu.setHeaderTitle(cache.geocode); + menu.setHeaderTitle(cache.getGeocode()); } - if (cache.coords != null) { + if (cache.getCoords() != null) { menu.add(0, MENU_COMPASS, 0, res.getString(R.string.cache_menu_compass)); SubMenu subMenu = menu.addSubMenu(1, 0, 0, res.getString(R.string.cache_menu_navigate)).setIcon(android.R.drawable.ic_menu_mapmode); NavigationAppFactory.addMenuItems(subMenu, this, res); addVisitMenu(menu, cache); menu.add(0, MENU_CACHE_DETAILS, 0, res.getString(R.string.cache_menu_details)); } - if (cache.reason >= 1) { + if (cache.getReason() >= 1) { menu.add(0, MENU_DROP_CACHE, 0, res.getString(R.string.cache_offline_drop)); List<cgList> cacheLists = app.getLists(); int listCount = cacheLists.size(); @@ -1220,10 +1227,10 @@ public class cgeocaches extends AbstractListActivity { if (id == MENU_COMPASS) { Intent navigateIntent = new Intent(this, cgeonavigate.class); - navigateIntent.putExtra("latitude", cache.coords.getLatitude()); - navigateIntent.putExtra("longitude", cache.coords.getLongitude()); - navigateIntent.putExtra("geocode", cache.geocode.toUpperCase()); - navigateIntent.putExtra("name", cache.name); + navigateIntent.putExtra("latitude", cache.getCoords().getLatitude()); + navigateIntent.putExtra("longitude", cache.getCoords().getLongitude()); + navigateIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); + navigateIntent.putExtra("name", cache.getName()); startActivity(navigateIntent); @@ -1232,8 +1239,8 @@ public class cgeocaches extends AbstractListActivity { return cache.logVisit(this); } else if (id == MENU_CACHE_DETAILS) { Intent cachesIntent = new Intent(this, cgeodetail.class); - cachesIntent.putExtra("geocode", cache.geocode.toUpperCase()); - cachesIntent.putExtra("name", cache.name); + cachesIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); + cachesIntent.putExtra("name", cache.getName()); startActivity(cachesIntent); return true; @@ -1293,7 +1300,7 @@ public class cgeocaches extends AbstractListActivity { } else if (id >= CONTEXT_MENU_MOVE_TO_LIST && id < CONTEXT_MENU_MOVE_TO_LIST + 100) { int newListId = id - CONTEXT_MENU_MOVE_TO_LIST; if (cache != null) { - app.moveToList(cache.geocode, newListId); + app.moveToList(cache.getGeocode(), newListId); } adapter.resetChecks(); @@ -1304,8 +1311,8 @@ public class cgeocaches extends AbstractListActivity { boolean moveAll = adapter.getChecked() == 0; final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache c : cacheListTemp) { - if (moveAll || c.statusChecked) { - app.moveToList(c.geocode, newListId); + if (moveAll || c.isStatusChecked()) { + app.moveToList(c.getGeocode(), newListId); } } adapter.resetChecks(); @@ -1320,11 +1327,11 @@ public class cgeocaches extends AbstractListActivity { lastMenuInfo = info; if (cache != null) { - // create a searchId for a single cache (as if in details view) - final UUID singleSearchId = base.searchByGeocode(cache.geocode, null, 0, false, null); + // create a search for a single cache (as if in details view) + final cgSearch singleSearch = base.searchByGeocode(cache.getGeocode(), null, 0, false, null); if (NavigationAppFactory.onMenuItemSelected(item, geo, this, - res, cache, singleSearchId, null, null)) { + res, cache, singleSearch, null, null)) { return true; } @@ -1415,19 +1422,18 @@ public class cgeocaches extends AbstractListActivity { return; } - if (!more) { + if (more) { + listFooterText.setText(res.getString(R.string.caches_more_caches) + " (" + res.getString(R.string.caches_more_caches_currently) + ": " + cacheList.size() + ")"); + listFooter.setOnClickListener(new moreCachesListener()); + } else { if (CollectionUtils.isEmpty(cacheList)) { listFooterText.setText(res.getString(R.string.caches_no_cache)); } else { listFooterText.setText(res.getString(R.string.caches_more_caches_no)); } - listFooter.setClickable(false); listFooter.setOnClickListener(null); - } else { - listFooterText.setText(res.getString(R.string.caches_more_caches)); - listFooter.setClickable(true); - listFooter.setOnClickListener(new moreCachesListener()); } + listFooter.setClickable(more); } private void init() { @@ -1444,10 +1450,10 @@ public class cgeocaches extends AbstractListActivity { } if (CollectionUtils.isNotEmpty(cacheList)) { - final Integer count = app.getTotal(searchId); + final Integer count = cgeoapplication.getTotal(search); if (count != null && count > 0) { setTitle(title); - if (cacheList.size() < app.getTotal(searchId) && cacheList.size() < MAX_LIST_ITEMS) { + if (cacheList.size() < cgeoapplication.getTotal(search) && cacheList.size() < MAX_LIST_ITEMS) { setMoreCaches(true); } else { setMoreCaches(false); @@ -1791,7 +1797,7 @@ public class cgeocaches extends AbstractListActivity { private Handler handler = null; private Geopoint coords = null; - private int listId = 1; + private int listId = cgList.STANDARD_LIST_ID; public geocachesLoadByOffline(final Handler handlerIn, final Geopoint coordsIn, int listIdIn) { handler = handlerIn; @@ -1802,9 +1808,9 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { if (coords != null) { - searchId = base.searchByOffline(coords, Settings.getCacheType(), listId); + search = base.searchByOffline(coords, Settings.getCacheType(), listId); } else { - searchId = base.searchByOffline(null, null, 1); + search = base.searchByOffline(null, null, cgList.STANDARD_LIST_ID); } handler.sendMessage(new Message()); } @@ -1820,7 +1826,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - searchId = base.searchByHistory(coords != null ? Settings.getCacheType() : null); + search = base.searchByHistory(coords != null ? Settings.getCacheType() : null); handler.sendMessage(new Message()); } } @@ -1835,7 +1841,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - searchId = base.searchByNextPage(this, searchId, 0, Settings.isShowCaptcha()); + search = base.searchByNextPage(this, search, 0, Settings.isShowCaptcha()); handler.sendMessage(new Message()); } @@ -1864,7 +1870,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - searchId = base.searchByCoords(this, coords, cachetype, 0, Settings.isShowCaptcha()); + search = base.searchByCoords(this, coords, cachetype, 0, Settings.isShowCaptcha()); handler.sendMessage(new Message()); } @@ -1893,7 +1899,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - searchId = base.searchByKeyword(this, keyword, cachetype, 0, Settings.isShowCaptcha()); + search = base.searchByKeyword(this, keyword, cachetype, 0, Settings.isShowCaptcha()); handler.sendMessage(new Message()); } } @@ -1921,7 +1927,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - searchId = base.searchByUsername(this, username, cachetype, 0, Settings.isShowCaptcha()); + search = base.searchByUsername(this, username, cachetype, 0, Settings.isShowCaptcha()); handler.sendMessage(new Message()); } } @@ -1953,7 +1959,7 @@ public class cgeocaches extends AbstractListActivity { params.put("username", username); params.put("cachetype", cachetype); - searchId = base.searchByOwner(this, username, cachetype, 0, Settings.isShowCaptcha()); + search = base.searchByOwner(this, username, cachetype, 0, Settings.isShowCaptcha()); handler.sendMessage(new Message()); } @@ -1993,7 +1999,7 @@ public class cgeocaches extends AbstractListActivity { final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache cache : cacheListTemp) { - if (checked > 0 && !cache.statusChecked) { + if (checked > 0 && !cache.isStatusChecked()) { handler.sendEmptyMessage(0); yield(); @@ -2176,7 +2182,7 @@ public class cgeocaches extends AbstractListActivity { final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache cache : cacheListTemp) { - if (checked > 0 && !cache.statusChecked) { + if (checked > 0 && !cache.isStatusChecked()) { continue; } @@ -2186,7 +2192,7 @@ public class cgeocaches extends AbstractListActivity { break; } - app.markDropped(cache.geocode); + app.markDropped(cache.getGeocode()); } catch (Exception e) { Log.e(Settings.tag, "cgeocaches.geocachesDropDetails: " + e.toString()); } @@ -2220,7 +2226,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { for (cgCache cache : cacheList) { - if (checked > 0 && !cache.statusChecked) { + if (checked > 0 && !cache.isStatusChecked()) { handler.sendEmptyMessage(0); yield(); @@ -2233,7 +2239,7 @@ public class cgeocaches extends AbstractListActivity { break; } - app.clearVisitDate(cache.geocode); + app.clearVisitDate(cache.getGeocode()); handler.sendEmptyMessage(cacheList.indexOf(cache)); @@ -2290,7 +2296,7 @@ public class cgeocaches extends AbstractListActivity { logTypes.put(cgBase.LOG_WEBCAM_PHOTO_TAKEN, "Webcam Photo Taken"); for (cgCache cache : cacheList) { - if (checked > 0 && !cache.statusChecked) { + if (checked > 0 && !cache.isStatusChecked()) { handler.sendEmptyMessage(0); yield(); @@ -2304,13 +2310,13 @@ public class cgeocaches extends AbstractListActivity { break; } - if (cache.logOffline) + if (cache.isLogOffline()) { - cgLog log = app.loadLogOffline(cache.geocode); + cgLog log = app.loadLogOffline(cache.getGeocode()); if (null != logTypes.get(log.type)) { - fieldNoteBuffer.append(cache.geocode) + fieldNoteBuffer.append(cache.getGeocode()) .append(',') .append(fieldNoteDateFormat.format(new Date(log.date))) .append(',') @@ -2485,8 +2491,8 @@ public class cgeocaches extends AbstractListActivity { if (checked > 0) { final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache cache : cacheListTemp) { - if (cache.statusChecked) { - app.moveToList(cache.geocode, listId); + if (cache.isStatusChecked()) { + app.moveToList(cache.getGeocode(), listId); } } } @@ -2599,13 +2605,13 @@ public class cgeocaches extends AbstractListActivity { * unused here but needed since this method is referenced from XML layout */ public void goMap(View view) { - if (searchId == null || CollectionUtils.isEmpty(cacheList)) { + if (search == null || CollectionUtils.isEmpty(cacheList)) { showToast(res.getString(R.string.warn_no_cache_coord)); return; } - CGeoMap.startActivitySearch(this, searchId, title + " [" + app.getCount(searchId) + "]", false); + CGeoMap.startActivitySearch(this, search, title + " [" + cgeoapplication.getCount(search) + "]", false); } public void goManual(View view) { @@ -2724,10 +2730,10 @@ public class cgeocaches extends AbstractListActivity { context.startActivity(cachesIntent); } - public static void startActivityMap(final Context context, final UUID uuid) { + public static void startActivityMap(final Context context, final cgSearch search) { final Intent cachesIntent = new Intent(context, cgeocaches.class); cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.MAP); - cachesIntent.putExtra("searchId", uuid); + cachesIntent.putExtra("search", search); context.startActivity(cachesIntent); } diff --git a/main/src/cgeo/geocaching/cgeodetail.java b/main/src/cgeo/geocaching/cgeodetail.java index dfb0e63..a6c6b18 100644 --- a/main/src/cgeo/geocaching/cgeodetail.java +++ b/main/src/cgeo/geocaching/cgeodetail.java @@ -8,6 +8,8 @@ import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.enumerations.CacheType; +import cgeo.geocaching.network.HtmlImage; +import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.CryptUtils; import org.apache.commons.collections.CollectionUtils; @@ -67,7 +69,6 @@ import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; -import java.util.UUID; /** * Activity to display all details of a cache like owner, difficulty, description etc. @@ -82,7 +83,7 @@ public class cgeodetail extends AbstractActivity { super("c:geo-cache-details"); } - public UUID searchId = null; + public cgSearch search = null; public cgCache cache = null; public String geocode = null; public String name = null; @@ -121,13 +122,13 @@ public class cgeodetail extends AbstractActivity { private Progress progress = new Progress(); - private Handler storeCacheHandler = new Handler() { + private class StoreCacheHandler extends CancellableHandler { @Override - public void handleMessage(Message msg) { + public void handleRegularMessage(Message msg) { storeThread = null; try { - cache = app.getCache(searchId); // reload cache details + cache = app.getCache(search); // reload cache details } catch (Exception e) { showToast(res.getString(R.string.err_store_failed)); @@ -136,15 +137,15 @@ public class cgeodetail extends AbstractActivity { setView(); } - }; + } - private Handler refreshCacheHandler = new Handler() { + private class RefreshCacheHandler extends CancellableHandler { @Override - public void handleMessage(Message msg) { + public void handleRegularMessage(Message msg) { refreshThread = null; try { - cache = app.getCache(searchId); // reload cache details + cache = app.getCache(search); // reload cache details } catch (Exception e) { showToast(res.getString(R.string.err_refresh_failed)); @@ -153,13 +154,13 @@ public class cgeodetail extends AbstractActivity { setView(); } - }; + } private Handler dropCacheHandler = new Handler() { @Override public void handleMessage(Message msg) { try { - cache = app.getCache(searchId); // reload cache details + cache = app.getCache(search); // reload cache details } catch (Exception e) { showToast(res.getString(R.string.err_drop_failed)); @@ -170,21 +171,21 @@ public class cgeodetail extends AbstractActivity { } }; - private Handler loadCacheHandler = new Handler() { + private class LoadCacheHandler extends CancellableHandler { @Override - public void handleMessage(Message msg) { + public void handleRegularMessage(final Message msg) { if (cgBase.UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { updateStatusMsg((String) msg.obj); } else { - if (searchId == null) { + if (search == null) { showToast(res.getString(R.string.err_dwld_details_failed)); finish(); return; } - if (app.getError(searchId) != null) { - showToast(res.getString(R.string.err_dwld_details_failed_reason) + " " + app.getError(searchId) + "."); + if (cgeoapplication.getError(search) != null) { + showToast(res.getString(R.string.err_dwld_details_failed_reason) + " " + cgeoapplication.getError(search) + "."); finish(); return; @@ -211,7 +212,13 @@ public class cgeodetail extends AbstractActivity { + "\n\n" + msg); } - }; + + @Override + public void handleCancel(final Object extra) { + finish(); + } + + } final Handler loadMapPreviewHandler = new Handler() { @Override @@ -304,7 +311,7 @@ public class cgeodetail extends AbstractActivity { Button buttonRemove = (Button) findViewById(R.id.remove_from_watchlist); TextView text = (TextView) findViewById(R.id.watchlist_text); - if (cache.onWatchlist) { + if (cache.isOnWatchlist()) { buttonAdd.setVisibility(View.GONE); buttonRemove.setVisibility(View.VISIBLE); text.setText(R.string.cache_watchlist_on); @@ -399,6 +406,8 @@ public class cgeodetail extends AbstractActivity { app.setAction(geocode); + final LoadCacheHandler loadCacheHandler = new LoadCacheHandler(); + try { String title = res.getString(R.string.cache); if (StringUtils.isNotBlank(name)) { @@ -406,7 +415,7 @@ public class cgeodetail extends AbstractActivity { } else if (StringUtils.isNotBlank(geocode)) { title = geocode.toUpperCase(); } - progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, true); + progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage()); } catch (Exception e) { // nothing, we lost the window } @@ -474,10 +483,10 @@ public class cgeodetail extends AbstractActivity { if (viewId == R.id.author) { // Author of a log entry contextMenuUser = ((TextView) view).getText().toString(); } else if (viewId == R.id.value) { // The owner of the cache - if (StringUtils.isNotBlank(cache.ownerReal)) { - contextMenuUser = cache.ownerReal; + if (StringUtils.isNotBlank(cache.getOwnerReal())) { + contextMenuUser = cache.getOwnerReal(); } else { - contextMenuUser = cache.owner; + contextMenuUser = cache.getOwner(); } } @@ -491,15 +500,15 @@ public class cgeodetail extends AbstractActivity { addNavigationMenuItems(menu); break; case -1: - if (null != cache.waypoints) { + if (null != cache.getWaypoints()) { try { final ViewGroup parent = ((ViewGroup) view.getParent()); for (int i = 0; i < parent.getChildCount(); i++) { if (parent.getChildAt(i) == view) { - final List<cgWaypoint> sortedWaypoints = new ArrayList<cgWaypoint>(cache.waypoints); + final List<cgWaypoint> sortedWaypoints = new ArrayList<cgWaypoint>(cache.getWaypoints()); Collections.sort(sortedWaypoints); final cgWaypoint waypoint = sortedWaypoints.get(i); - final int index = cache.waypoints.indexOf(waypoint); + final int index = cache.getWaypoints().indexOf(waypoint); menu.setHeaderTitle(res.getString(R.string.waypoint)); menu.add(CONTEXT_MENU_WAYPOINT_DUPLICATE, index, 0, R.string.waypoint_duplicate); if (waypoint.isUserDefined()) { @@ -541,22 +550,22 @@ public class cgeodetail extends AbstractActivity { } break; case CONTEXT_MENU_WAYPOINT_DUPLICATE: - if (null != cache.waypoints && index < cache.waypoints.size()) { - final cgWaypoint copy = new cgWaypoint(cache.waypoints.get(index)); + if (null != cache.getWaypoints() && index < cache.getWaypoints().size()) { + final cgWaypoint copy = new cgWaypoint(cache.getWaypoints().get(index)); copy.setUserDefined(); - copy.name = res.getString(R.string.waypoint_copy_of) + " " + copy.name; - cache.waypoints.add(index + 1, copy); - app.saveOwnWaypoint(-1, cache.geocode, copy); + copy.setName(res.getString(R.string.waypoint_copy_of) + " " + copy.getName()); + cache.getWaypoints().add(index + 1, copy); + app.saveOwnWaypoint(-1, cache.getGeocode(), copy); app.removeCacheFromCache(geocode); setView(); // refresh } break; case CONTEXT_MENU_WAYPOINT_DELETE: - if (null != cache.waypoints && index < cache.waypoints.size()) { - final cgWaypoint waypoint = cache.waypoints.get(index); + if (null != cache.getWaypoints() && index < cache.getWaypoints().size()) { + final cgWaypoint waypoint = cache.getWaypoints().get(index); if (waypoint.isUserDefined()) { - cache.waypoints.remove(index); - app.deleteWaypoint(waypoint.id); + cache.getWaypoints().remove(index); + app.deleteWaypoint(waypoint.getId()); app.removeCacheFromCache(geocode); setView(); // refresh } @@ -570,7 +579,7 @@ public class cgeodetail extends AbstractActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { - if (cache != null && cache.coords != null) { + if (cache != null && cache.getCoords() != null) { menu.add(0, 2, 0, res.getString(R.string.cache_menu_compass)).setIcon(android.R.drawable.ic_menu_compass); // compass SubMenu subMenu = menu.addSubMenu(1, 0, 0, res.getString(R.string.cache_menu_navigate)).setIcon(android.R.drawable.ic_menu_mapmode); addNavigationMenuItems(subMenu); @@ -581,11 +590,11 @@ public class cgeodetail extends AbstractActivity { } addVisitMenu(menu, cache); - if (cache != null && CollectionUtils.isNotEmpty(cache.spoilers)) { + if (cache != null && CollectionUtils.isNotEmpty(cache.getSpoilers())) { menu.add(1, 5, 0, res.getString(R.string.cache_menu_spoilers)).setIcon(android.R.drawable.ic_menu_gallery); // spoiler images } - if (cache != null && cache.coords != null && cache.supportsCachesAround()) { + if (cache != null && cache.getCoords() != null && cache.supportsCachesAround()) { menu.add(0, 10, 0, res.getString(R.string.cache_menu_around)).setIcon(android.R.drawable.ic_menu_rotate); // caches around } @@ -636,7 +645,7 @@ public class cgeodetail extends AbstractActivity { } return false; } - if (NavigationAppFactory.onMenuItemSelected(item, geo, this, res, cache, searchId, null, null)) { + if (NavigationAppFactory.onMenuItemSelected(item, geo, this, res, cache, search, null, null)) { return true; } if (GeneralAppsFactory.onMenuItemSelected(item, this, cache)) { @@ -659,10 +668,10 @@ public class cgeodetail extends AbstractActivity { geo = app.startGeo(this, geoUpdate, base, 0, 0); } - if (searchId != null) { - cache = app.getCache(searchId); - if (cache != null && cache.geocode != null) { - geocode = cache.geocode; + if (search != null) { + cache = app.getCache(search); + if (cache != null && cache.getGeocode() != null) { + geocode = cache.getGeocode(); } } @@ -676,11 +685,11 @@ public class cgeodetail extends AbstractActivity { TextView itemName; TextView itemValue; - if (searchId == null) { + if (search == null) { return; } - cache = app.getCache(searchId); + cache = app.getCache(search); if (cache == null) { progress.dismiss(); @@ -698,15 +707,15 @@ public class cgeodetail extends AbstractActivity { try { - if (geocode == null && StringUtils.isNotBlank(cache.geocode)) { - geocode = cache.geocode; + if (geocode == null && StringUtils.isNotBlank(cache.getGeocode())) { + geocode = cache.getGeocode(); } - if (guid == null && StringUtils.isNotBlank(cache.guid)) { - guid = cache.guid; + if (guid == null && StringUtils.isNotBlank(cache.getGuid())) { + guid = cache.getGuid(); } - setTitle(cache.geocode.toUpperCase()); + setTitle(cache.getGeocode().toUpperCase()); inflater = getLayoutInflater(); @@ -717,7 +726,7 @@ public class cgeodetail extends AbstractActivity { detailsList.removeAllViews(); // actionbar icon, default myster< - ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); + ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.getType())), null, null, null); // cache name (full name) itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); @@ -725,8 +734,8 @@ public class cgeodetail extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_name)); - Spannable span = (new Spannable.Factory()).newSpannable(Html.fromHtml(cache.name).toString()); - if (cache.disabled || cache.archived) { // strike + Spannable span = (new Spannable.Factory()).newSpannable(Html.fromHtml(cache.getName()).toString()); + if (cache.isDisabled() || cache.isArchived()) { // strike span.setSpan(new StrikethroughSpan(), 0, span.toString().length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } itemValue.setText(span); @@ -740,15 +749,15 @@ public class cgeodetail extends AbstractActivity { itemName.setText(res.getString(R.string.cache_type)); String size = ""; - if (cache.size != null) { + if (cache.getSize() != null) { // don't show "not chosen" for events and virtuals, that should be the normal case if (cache.showSize()) { - size = " (" + res.getString(cache.size.stringId) + ")"; + size = " (" + res.getString(cache.getSize().stringId) + ")"; } } - if (cgBase.cacheTypesInv.containsKey(cache.type)) { // cache icon - itemValue.setText(cgBase.cacheTypesInv.get(cache.type) + size); + if (cgBase.cacheTypesInv.containsKey(cache.getType())) { // cache icon + itemValue.setText(cgBase.cacheTypesInv.get(cache.getType()) + size); } else { itemValue.setText(cgBase.cacheTypesInv.get(CacheType.MYSTERY.id) + size); } @@ -760,11 +769,11 @@ public class cgeodetail extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_geocode)); - itemValue.setText(cache.geocode.toUpperCase()); + itemValue.setText(cache.getGeocode().toUpperCase()); detailsList.addView(itemLayout); // cache state - if (cache.logOffline || cache.archived || cache.disabled || cache.members || cache.found) { + if (cache.isLogOffline() || cache.isArchived() || cache.isDisabled() || cache.isMembers() || cache.isFound()) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); @@ -772,31 +781,31 @@ public class cgeodetail extends AbstractActivity { itemName.setText(res.getString(R.string.cache_status)); StringBuilder state = new StringBuilder(); - if (cache.logOffline) { + if (cache.isLogOffline()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_offline_log)); } - if (cache.found) { + if (cache.isFound()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_found)); } - if (cache.archived) { + if (cache.isArchived()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_archived)); } - if (cache.disabled) { + if (cache.isDisabled()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_disabled)); } - if (cache.members) { + if (cache.isMembers()) { if (state.length() > 0) { state.append(", "); } @@ -815,8 +824,8 @@ public class cgeodetail extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_distance)); - if (cache.distance != null) { - itemValue.setText("~" + cgBase.getHumanDistance(cache.distance)); + if (cache.getDistance() != null) { + itemValue.setText("~" + cgBase.getHumanDistance(cache.getDistance())); } else { itemValue.setText("--"); } @@ -824,54 +833,54 @@ public class cgeodetail extends AbstractActivity { cacheDistance = itemValue; // difficulty - if (cache.difficulty != null && cache.difficulty > 0) { - addStarRating(detailsList, res.getString(R.string.cache_difficulty), cache.difficulty); + if (cache.getDifficulty() != null && cache.getDifficulty() > 0) { + addStarRating(detailsList, res.getString(R.string.cache_difficulty), cache.getDifficulty()); } // terrain - if (cache.terrain != null && cache.terrain > 0) { - addStarRating(detailsList, res.getString(R.string.cache_terrain), cache.terrain); + if (cache.getTerrain() != null && cache.getTerrain() > 0) { + addStarRating(detailsList, res.getString(R.string.cache_terrain), cache.getTerrain()); } // rating - if (cache.rating != null && cache.rating > 0) { - itemLayout = addStarRating(detailsList, res.getString(R.string.cache_rating), cache.rating); - if (cache.votes != null) { + if (cache.getRating() != null && cache.getRating() > 0) { + itemLayout = addStarRating(detailsList, res.getString(R.string.cache_rating), cache.getRating()); + if (cache.getVotes() != null) { final TextView itemAddition = (TextView) itemLayout.findViewById(R.id.addition); - itemAddition.setText("(" + cache.votes + ")"); + itemAddition.setText("(" + cache.getVotes() + ")"); itemAddition.setVisibility(View.VISIBLE); } } // favourite count - if (cache.favouriteCnt != null) { + if (cache.getFavouriteCnt() != null) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_favourite)); - itemValue.setText(String.format("%d", cache.favouriteCnt) + "×"); + itemValue.setText(String.format("%d", cache.getFavouriteCnt()) + "×"); detailsList.addView(itemLayout); } // cache author - if (StringUtils.isNotBlank(cache.owner) || StringUtils.isNotBlank(cache.ownerReal)) { + if (StringUtils.isNotBlank(cache.getOwner()) || StringUtils.isNotBlank(cache.getOwnerReal())) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_owner)); - if (StringUtils.isNotBlank(cache.owner)) { - itemValue.setText(Html.fromHtml(cache.owner), TextView.BufferType.SPANNABLE); - } else if (StringUtils.isNotBlank(cache.ownerReal)) { - itemValue.setText(Html.fromHtml(cache.ownerReal), TextView.BufferType.SPANNABLE); + if (StringUtils.isNotBlank(cache.getOwner())) { + itemValue.setText(Html.fromHtml(cache.getOwner()), TextView.BufferType.SPANNABLE); + } else if (StringUtils.isNotBlank(cache.getOwnerReal())) { + itemValue.setText(Html.fromHtml(cache.getOwnerReal()), TextView.BufferType.SPANNABLE); } itemValue.setOnClickListener(new userActions()); detailsList.addView(itemLayout); } // cache hidden - if (cache.hidden != null && cache.hidden.getTime() > 0) { + if (cache.getHidden() != null && cache.getHidden().getTime() > 0) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); @@ -881,23 +890,23 @@ public class cgeodetail extends AbstractActivity { } else { itemName.setText(res.getString(R.string.cache_hidden)); } - itemValue.setText(base.formatFullDate(cache.hidden.getTime())); + itemValue.setText(base.formatFullDate(cache.getHidden().getTime())); detailsList.addView(itemLayout); } // cache location - if (StringUtils.isNotBlank(cache.location)) { + if (StringUtils.isNotBlank(cache.getLocation())) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_location)); - itemValue.setText(cache.location); + itemValue.setText(cache.getLocation()); detailsList.addView(itemLayout); } // cache coordinates - if (cache.coords != null) { + if (cache.getCoords() != null) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); @@ -908,7 +917,7 @@ public class cgeodetail extends AbstractActivity { } // cache attributes - if (CollectionUtils.isNotEmpty(cache.attributes)) { + if (CollectionUtils.isNotEmpty(cache.getAttributes())) { final LinearLayout attribBox = (LinearLayout) findViewById( R.id.attributes_innerbox); @@ -955,12 +964,12 @@ public class cgeodetail extends AbstractActivity { } // cache inventory - if (CollectionUtils.isNotEmpty(cache.inventory)) { + if (CollectionUtils.isNotEmpty(cache.getInventory())) { final LinearLayout inventBox = (LinearLayout) findViewById(R.id.inventory_box); final TextView inventView = (TextView) findViewById(R.id.inventory); StringBuilder inventoryString = new StringBuilder(); - for (cgTrackable inventoryItem : cache.inventory) { + for (cgTrackable inventoryItem : cache.getInventory()) { if (inventoryString.length() > 0) { inventoryString.append('\n'); } @@ -977,8 +986,8 @@ public class cgeodetail extends AbstractActivity { final Button offlineRefresh = (Button) findViewById(R.id.offline_refresh); final Button offlineStore = (Button) findViewById(R.id.offline_store); - if (cache.reason >= 1) { - Long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.detailedUpdate / (60 * 1000)); // minutes + if (cache.getReason() >= 1) { + Long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes String ago = ""; if (diff < 15) { @@ -1011,12 +1020,12 @@ public class cgeodetail extends AbstractActivity { offlineRefresh.setClickable(true); // cache personal note - if (StringUtils.isNotBlank(cache.personalNote)) { + if (StringUtils.isNotBlank(cache.getPersonalNote())) { ((LinearLayout) findViewById(R.id.personalnote_box)).setVisibility(View.VISIBLE); TextView personalNoteText = (TextView) findViewById(R.id.personalnote); personalNoteText.setVisibility(View.VISIBLE); - personalNoteText.setText(cache.personalNote, TextView.BufferType.SPANNABLE); + personalNoteText.setText(cache.getPersonalNote(), TextView.BufferType.SPANNABLE); personalNoteText.setMovementMethod(LinkMovementMethod.getInstance()); } else { @@ -1024,12 +1033,12 @@ public class cgeodetail extends AbstractActivity { } // cache short desc - if (StringUtils.isNotBlank(cache.shortdesc)) { + if (StringUtils.isNotBlank(cache.getShortdesc())) { ((LinearLayout) findViewById(R.id.desc_box)).setVisibility(View.VISIBLE); TextView descView = (TextView) findViewById(R.id.shortdesc); descView.setVisibility(View.VISIBLE); - descView.setText(Html.fromHtml(cache.shortdesc.trim(), new cgHtmlImg(this, geocode, true, cache.reason, false), null), TextView.BufferType.SPANNABLE); + descView.setText(Html.fromHtml(cache.getShortdesc().trim(), new HtmlImage(this, geocode, true, cache.getReason(), false), null), TextView.BufferType.SPANNABLE); descView.setMovementMethod(LinkMovementMethod.getInstance()); } @@ -1073,40 +1082,40 @@ public class cgeodetail extends AbstractActivity { LinearLayout waypoints = (LinearLayout) findViewById(R.id.waypoints); waypoints.removeAllViews(); - if (CollectionUtils.isNotEmpty(cache.waypoints)) { + if (CollectionUtils.isNotEmpty(cache.getWaypoints())) { LinearLayout waypointView; // sort waypoints: PP, Sx, FI, OWN - List<cgWaypoint> sortedWaypoints = new ArrayList<cgWaypoint>(cache.waypoints); + List<cgWaypoint> sortedWaypoints = new ArrayList<cgWaypoint>(cache.getWaypoints()); Collections.sort(sortedWaypoints); for (cgWaypoint wpt : sortedWaypoints) { waypointView = (LinearLayout) inflater.inflate(R.layout.waypoint_item, null); final TextView identification = (TextView) waypointView.findViewById(R.id.identification); - ((TextView) waypointView.findViewById(R.id.type)).setText(cgBase.waypointTypes.get(wpt.type)); + ((TextView) waypointView.findViewById(R.id.type)).setText(cgBase.waypointTypes.get(wpt.getWaypointType())); if (!wpt.getPrefix().equalsIgnoreCase("OWN")) { - identification.setText(wpt.getPrefix().trim() + "/" + wpt.lookup.trim()); + identification.setText(wpt.getPrefix().trim() + "/" + wpt.getLookup().trim()); } else { identification.setText(res.getString(R.string.waypoint_custom)); } TextView nameView = (TextView) waypointView.findViewById(R.id.name); - if (StringUtils.isBlank(wpt.name)) { - nameView.setText(cgBase.formatCoords(wpt.coords, true)); + if (StringUtils.isBlank(wpt.getName())) { + nameView.setText(cgBase.formatCoords(wpt.getCoords(), true)); } else { - nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.name)); + nameView.setText(StringEscapeUtils.unescapeHtml4(wpt.getName())); } wpt.setIcon(res, nameView); TextView noteView = (TextView) waypointView.findViewById(R.id.note); - if (containsHtml(wpt.note)) { - noteView.setText(Html.fromHtml(wpt.note.trim()), TextView.BufferType.SPANNABLE); + if (containsHtml(wpt.getNote())) { + noteView.setText(Html.fromHtml(wpt.getNote().trim()), TextView.BufferType.SPANNABLE); } else { - noteView.setText(wpt.note.trim()); + noteView.setText(wpt.getNote().trim()); } - waypointView.setOnClickListener(new waypointInfo(wpt.id)); + waypointView.setOnClickListener(new waypointInfo(wpt.getId())); registerForContextMenu(waypointView); waypoints.addView(waypointView); @@ -1118,10 +1127,10 @@ public class cgeodetail extends AbstractActivity { addWaypoint.setOnClickListener(new addWaypoint()); // cache hint - if (StringUtils.isNotBlank(cache.hint)) { + if (StringUtils.isNotBlank(cache.getHint())) { ((LinearLayout) findViewById(R.id.hint_box)).setVisibility(View.VISIBLE); TextView hintView = ((TextView) findViewById(R.id.hint)); - hintView.setText(CryptUtils.rot13(cache.hint.trim())); + hintView.setText(CryptUtils.rot13(cache.getHint().trim())); hintView.setClickable(true); hintView.setOnClickListener(new codeHint()); } else { @@ -1131,8 +1140,8 @@ public class cgeodetail extends AbstractActivity { hintView.setOnClickListener(null); } - if (geo != null && geo.coordsNow != null && cache != null && cache.coords != null) { - cacheDistance.setText(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.coords))); + if (geo != null && geo.coordsNow != null && cache != null && cache.getCoords() != null) { + cacheDistance.setText(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); cacheDistance.bringToFront(); } } catch (Exception e) { @@ -1171,7 +1180,7 @@ public class cgeodetail extends AbstractActivity { if (longDesc == null && cache != null) { String description = cache.getDescription(); if (description != null) { - longDesc = Html.fromHtml(description.trim(), new cgHtmlImg(this, geocode, true, cache.reason, false), new UnknownTagsHandler()); + longDesc = Html.fromHtml(description.trim(), new HtmlImage(this, geocode, true, cache.getReason(), false), new UnknownTagsHandler()); } } } @@ -1203,14 +1212,14 @@ public class cgeodetail extends AbstractActivity { // cache logs TextView textView = (TextView) findViewById(R.id.logcount); int logCounter = 0; - if (cache != null && cache.logCounts != null) { + if (cache != null && cache.getLogCounts() != null) { final StringBuffer buff = new StringBuffer(); buff.append(res.getString(R.string.cache_log_types)); buff.append(": "); // sort the log counts by type id ascending. that way the FOUND, DNF log types are the first and most visible ones List<Entry<Integer, Integer>> sortedLogCounts = new ArrayList<Entry<Integer, Integer>>(); - sortedLogCounts.addAll(cache.logCounts.entrySet()); + sortedLogCounts.addAll(cache.getLogCounts().entrySet()); Collections.sort(sortedLogCounts, new Comparator<Entry<Integer, Integer>>() { @Override @@ -1249,8 +1258,8 @@ public class cgeodetail extends AbstractActivity { RelativeLayout rowView; - if (cache != null && cache.logs != null) { - for (cgLog log : cache.logs) { + if (cache != null && cache.getLogs() != null) { + for (cgLog log : cache.getLogs()) { rowView = (RelativeLayout) inflater.inflate(R.layout.log_item, null); if (log.date > 0) { @@ -1277,7 +1286,7 @@ public class cgeodetail extends AbstractActivity { } // avoid parsing HTML if not necessary if (containsHtml(log.log)) { - ((TextView) rowView.findViewById(R.id.log)).setText(Html.fromHtml(log.log, new cgHtmlImg(this, null, false, cache.reason, false), null), TextView.BufferType.SPANNABLE); + ((TextView) rowView.findViewById(R.id.log)).setText(Html.fromHtml(log.log, new HtmlImage(this, null, false, cache.getReason(), false), null), TextView.BufferType.SPANNABLE); } else { ((TextView) rowView.findViewById(R.id.log)).setText(log.log); @@ -1354,7 +1363,7 @@ public class cgeodetail extends AbstractActivity { listView.addView(rowView); } - if (cache.logs.size() > 0) { + if (cache.getLogs().size() > 0) { ((LinearLayout) findViewById(R.id.log_box)).setVisibility(View.VISIBLE); } } @@ -1362,9 +1371,9 @@ public class cgeodetail extends AbstractActivity { private class loadCache extends Thread { - private Handler handler = null; + private CancellableHandler handler = null; - public loadCache(Handler handlerIn) { + public loadCache(CancellableHandler handlerIn) { handler = handlerIn; if (geocode == null && guid == null) { @@ -1380,7 +1389,7 @@ public class cgeodetail extends AbstractActivity { if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) { return; } - searchId = base.searchByGeocode(geocode, StringUtils.isBlank(geocode) ? guid : null, 0, false, handler); + search = base.searchByGeocode(geocode, StringUtils.isBlank(geocode) ? guid : null, 0, false, handler); handler.sendMessage(new Message()); } } @@ -1394,15 +1403,15 @@ public class cgeodetail extends AbstractActivity { @Override public void run() { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { return; } BitmapDrawable image = null; try { - final String latlonMap = String.format((Locale) null, "%.6f", cache.coords.getLatitude()) + "," + - String.format((Locale) null, "%.6f", cache.coords.getLongitude()); + final String latlonMap = String.format((Locale) null, "%.6f", cache.getCoords().getLatitude()) + "," + + String.format((Locale) null, "%.6f", cache.getCoords().getLongitude()); final Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); int width = display.getWidth(); @@ -1410,7 +1419,7 @@ public class cgeodetail extends AbstractActivity { String markerUrl = cgBase.urlencode_rfc3986("http://cgeo.carnero.cc/_markers/my_location_mdpi.png"); - cgHtmlImg mapGetter = new cgHtmlImg(cgeodetail.this, cache.geocode, false, 0, false); + HtmlImage mapGetter = new HtmlImage(cgeodetail.this, cache.getGeocode(), false, 0, false); image = mapGetter.getDrawable("http://maps.google.com/maps/api/staticmap?center=" + latlonMap + "&zoom=15&size=" + width + "x" + height + "&maptype=terrain&markers=icon%3A" + markerUrl + "%7C" + latlonMap + "&sensor=false"); Message message = handler.obtainMessage(0, image); handler.sendMessage(message); @@ -1421,7 +1430,7 @@ public class cgeodetail extends AbstractActivity { } public void loadLongDesc() { - progress.show(this, null, res.getString(R.string.cache_dialog_loading_description), true, true); + progress.show(this, null, res.getString(R.string.cache_dialog_loading_description), true, null); threadLongDesc = new loadLongDesc(loadDescriptionHandler); threadLongDesc.start(); @@ -1451,13 +1460,13 @@ public class cgeodetail extends AbstractActivity { try { // cache coords = new cgCoord(); - coords.type = "cache"; + coords.setType("cache"); if (StringUtils.isNotBlank(name)) { - coords.name = name; + coords.setName(name); } else { - coords.name = geocode.toUpperCase(); + coords.setName(geocode.toUpperCase()); } - coords.coords = cache.coords; + coords.setCoords(cache.getCoords()); coordinates.add(coords); } catch (Exception e) { Log.e(Settings.tag, "cgeodetail.getCoordinates (cache): " + e.toString()); @@ -1465,13 +1474,13 @@ public class cgeodetail extends AbstractActivity { try { // waypoints - if (null != cache.waypoints) { - for (cgWaypoint waypoint : cache.waypoints) { - if (null != waypoint.coords) { + if (null != cache.getWaypoints()) { + for (cgWaypoint waypoint : cache.getWaypoints()) { + if (null != waypoint.getCoords()) { coords = new cgCoord(); - coords.type = "waypoint"; - coords.name = waypoint.name; - coords.coords = waypoint.coords; + coords.setType("waypoint"); + coords.setName(waypoint.getName()); + coords.setCoords(waypoint.getCoords()); coordinates.add(coords); } } @@ -1484,7 +1493,7 @@ public class cgeodetail extends AbstractActivity { } private void cachesAround() { - cgeocaches.startActivityCachesAround(this, cache.coords); + cgeocaches.startActivityCachesAround(this, cache.getCoords()); finish(); } @@ -1547,7 +1556,7 @@ public class cgeodetail extends AbstractActivity { final Integer[] keys = calendars.keySet().toArray(new Integer[calendars.size()]); final Integer calId = keys[index]; - final Date eventDate = cache.hidden; + final Date eventDate = cache.getHidden(); eventDate.setHours(0); eventDate.setMinutes(0); eventDate.setSeconds(0); @@ -1555,12 +1564,12 @@ public class cgeodetail extends AbstractActivity { StringBuilder description = new StringBuilder(); description.append(cache.getUrl()); description.append("\n\n"); - if (StringUtils.isNotBlank(cache.shortdesc)) { - description.append(Html.fromHtml(cache.shortdesc).toString()); + if (StringUtils.isNotBlank(cache.getShortdesc())) { + description.append(Html.fromHtml(cache.getShortdesc()).toString()); } - if (StringUtils.isNotBlank(cache.personalNote)) { - description.append("\n\n" + Html.fromHtml(cache.personalNote).toString()); + if (StringUtils.isNotBlank(cache.getPersonalNote())) { + description.append("\n\n" + Html.fromHtml(cache.getPersonalNote()).toString()); } ContentValues event = new ContentValues(); @@ -1568,20 +1577,20 @@ public class cgeodetail extends AbstractActivity { event.put("dtstart", eventDate.getTime() + 43200000); // noon event.put("dtend", eventDate.getTime() + 43200000 + 3600000); // + one hour event.put("eventTimezone", "UTC"); - event.put("title", Html.fromHtml(cache.name).toString()); + event.put("title", Html.fromHtml(cache.getName()).toString()); event.put("description", description.toString()); String location = ""; - if (cache.coords != null) { + if (cache.getCoords() != null) { location += cache.getLatitude() + " " + cache.getLongitude(); } - if (StringUtils.isNotBlank(cache.location)) { + if (StringUtils.isNotBlank(cache.getLocation())) { boolean addParenteses = false; if (location.length() > 0) { addParenteses = true; location += " ("; } - location += Html.fromHtml(cache.location).toString(); + location += Html.fromHtml(cache.getLocation()).toString(); if (addParenteses) { location += ")"; } @@ -1603,11 +1612,11 @@ public class cgeodetail extends AbstractActivity { } private void navigateTo() { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { showToast(res.getString(R.string.err_location_unknown)); } - cgeonavigate.startActivity(this, cache.geocode, cache.name, cache.coords, getCoordinates()); + cgeonavigate.startActivity(this, cache.getGeocode(), cache.getName(), cache.getCoords(), getCoordinates()); } private class waypointInfo implements View.OnClickListener { @@ -1620,7 +1629,7 @@ public class cgeodetail extends AbstractActivity { public void onClick(View arg0) { Intent waypointIntent = new Intent(cgeodetail.this, cgeowaypoint.class); waypointIntent.putExtra("waypoint", id); - waypointIntent.putExtra("geocode", cache.geocode); + waypointIntent.putExtra("geocode", cache.getGeocode()); startActivity(waypointIntent); } } @@ -1630,14 +1639,14 @@ public class cgeodetail extends AbstractActivity { } private void showSpoilers() { - if (cache == null || CollectionUtils.isEmpty(cache.spoilers)) { + if (cache == null || CollectionUtils.isEmpty(cache.getSpoilers())) { showToast(res.getString(R.string.err_detail_no_spoiler)); } Intent spoilersIntent = new Intent(this, cgeoimages.class); spoilersIntent.putExtra("geocode", geocode.toUpperCase()); spoilersIntent.putExtra("type", cgeoimages.SPOILER_IMAGES); - spoilersIntent.putParcelableArrayListExtra("images", cache.spoilers); + spoilersIntent.putParcelableArrayListExtra("images", cache.getSpoilers()); startActivity(spoilersIntent); } @@ -1662,13 +1671,13 @@ public class cgeodetail extends AbstractActivity { try { StringBuilder dist = new StringBuilder(); - if (geo.coordsNow != null && cache != null && cache.coords != null) { - dist.append(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.coords))); + if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { + dist.append(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); } - if (cache != null && cache.elevation != null) { + if (cache != null && cache.getElevation() != null) { if (geo.altitudeNow != null) { - Double diff = (cache.elevation - geo.altitudeNow); + Double diff = (cache.getElevation() - geo.altitudeNow); if (diff >= 0) { dist.append(" ↗"); } else if (diff < 0) { @@ -1697,8 +1706,8 @@ public class cgeodetail extends AbstractActivity { // show list of trackables try { // jump directly into details if there is only one trackable - if (cache != null && cache.inventory != null && cache.inventory.size() == 1) { - cgTrackable trackable = cache.inventory.get(0); + if (cache != null && cache.getInventory() != null && cache.getInventory().size() == 1) { + cgTrackable trackable = cache.getInventory().get(0); cgeotrackable.startActivity(cgeodetail.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName()); } else { @@ -1719,7 +1728,9 @@ public class cgeodetail extends AbstractActivity { return; } - progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, true); + final StoreCacheHandler storeCacheHandler = new StoreCacheHandler(); + + progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage()); if (storeThread != null) { storeThread.interrupt(); @@ -1737,7 +1748,9 @@ public class cgeodetail extends AbstractActivity { return; } - progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, true); + final RefreshCacheHandler refreshCacheHandler = new RefreshCacheHandler(); + + progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage()); if (refreshThread != null) { refreshThread.interrupt(); @@ -1749,30 +1762,30 @@ public class cgeodetail extends AbstractActivity { } private class storeCacheThread extends Thread { - private Handler handler = null; + final private CancellableHandler handler; - public storeCacheThread(Handler handlerIn) { - handler = handlerIn; + public storeCacheThread(final CancellableHandler handler) { + this.handler = handler; } @Override public void run() { - int reason = (cache.reason > 1) ? cache.reason : 1; + int reason = cache.getReason() > 1 ? cache.getReason() : 1; base.storeCache(app, cgeodetail.this, cache, null, reason, handler); } } private class refreshCacheThread extends Thread { - private Handler handler = null; + final private CancellableHandler handler; - public refreshCacheThread(Handler handlerIn) { - handler = handlerIn; + public refreshCacheThread(final CancellableHandler handler) { + this.handler = handler; } @Override public void run() { app.removeCacheFromCache(geocode); - searchId = base.searchByGeocode(cache.geocode, null, 0, true, null); + search = base.searchByGeocode(cache.getGeocode(), null, 0, true, handler); handler.sendEmptyMessage(0); } @@ -1785,7 +1798,7 @@ public class cgeodetail extends AbstractActivity { return; } - progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, false); + progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null); Thread thread = new dropCacheThread(dropCacheHandler); thread.start(); } @@ -1814,7 +1827,7 @@ public class cgeodetail extends AbstractActivity { showToast(res.getString(R.string.err_watchlist_still_managing)); return; } - progress.show(cgeodetail.this, res.getString(titleId), res.getString(messageId), true, true); + progress.show(cgeodetail.this, res.getString(titleId), res.getString(messageId), true, null); if (watchlistThread != null) { watchlistThread.interrupt(); @@ -1882,8 +1895,8 @@ public class cgeodetail extends AbstractActivity { addWptIntent.putExtra("geocode", geocode); int wpCount = 0; - if (cache.waypoints != null) { - wpCount = cache.waypoints.size(); + if (cache.getWaypoints() != null) { + wpCount = cache.getWaypoints().size(); } addWptIntent.putExtra("count", wpCount); @@ -1939,12 +1952,12 @@ public class cgeodetail extends AbstractActivity { * unused here but needed since this method is referenced from XML layout */ public void goCompass(View view) { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { showToast(res.getString(R.string.cache_coordinates_no)); return; } - cgeonavigate.startActivity(this, cache.geocode, cache.name, cache.coords, getCoordinates()); + cgeonavigate.startActivity(this, cache.getGeocode(), cache.getName(), cache.getCoords(), getCoordinates()); } /** @@ -2005,7 +2018,7 @@ public class cgeodetail extends AbstractActivity { noAttributeIconsFound = true; - for (String attributeName : cache.attributes) { + for (String attributeName : cache.getAttributes()) { boolean strikethru = attributeName.endsWith("_no"); // cut off _yes / _no if (attributeName.endsWith("_no") || attributeName.endsWith("_yes")) { @@ -2065,8 +2078,8 @@ public class cgeodetail extends AbstractActivity { StringBuilder buffer = new StringBuilder(); String attribute; - for (int i = 0; i < cache.attributes.size(); i++) { - attribute = cache.attributes.get(i); + for (int i = 0; i < cache.getAttributes().size(); i++) { + attribute = cache.getAttributes().get(i); // dynamically search for a translation of the attribute int id = res.getIdentifier("attribute_" + attribute, "string", diff --git a/main/src/cgeo/geocaching/cgeogpxes.java b/main/src/cgeo/geocaching/cgeogpxes.java index 4714049..865b9e7 100644 --- a/main/src/cgeo/geocaching/cgeogpxes.java +++ b/main/src/cgeo/geocaching/cgeogpxes.java @@ -20,7 +20,6 @@ import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; -import java.util.UUID; public class cgeogpxes extends FileList<cgGPXListAdapter> { @@ -135,11 +134,11 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> { @Override public void run() { - final UUID searchId = doImport(); - loadCachesHandler.sendMessage(loadCachesHandler.obtainMessage(0, app.getCount(searchId), 0)); + final cgSearch search = doImport(); + loadCachesHandler.sendMessage(loadCachesHandler.obtainMessage(0, cgeoapplication.getCount(search), 0)); } - protected abstract UUID doImport(); + protected abstract cgSearch doImport(); } private class ImportFileThread extends ImportThread { @@ -150,7 +149,7 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> { } @Override - protected UUID doImport() { + protected cgSearch doImport() { if (StringUtils.endsWithIgnoreCase(file.getName(), GPXParser.GPX_FILE_EXTENSION)) { return GPXParser.importGPX(file, listId, changeParseDialogHandler); } @@ -168,7 +167,7 @@ public class cgeogpxes extends FileList<cgGPXListAdapter> { } @Override - protected UUID doImport() { + protected cgSearch doImport() { return GPXParser.importGPX(stream, listId, changeParseDialogHandler); } } diff --git a/main/src/cgeo/geocaching/cgeoimages.java b/main/src/cgeo/geocaching/cgeoimages.java index df5578c..ef3f1f8 100644 --- a/main/src/cgeo/geocaching/cgeoimages.java +++ b/main/src/cgeo/geocaching/cgeoimages.java @@ -2,6 +2,7 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.files.LocalStorage; +import cgeo.geocaching.network.HtmlImage; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -89,7 +90,7 @@ public class cgeoimages extends AbstractActivity { @Override protected BitmapDrawable doInBackground(Void... params) { - final cgHtmlImg imgGetter = new cgHtmlImg(cgeoimages.this, geocode, true, offline ? 1 : 0, false, save); + final HtmlImage imgGetter = new HtmlImage(cgeoimages.this, geocode, true, offline ? 1 : 0, false, save); return imgGetter.getDrawable(img.url); } diff --git a/main/src/cgeo/geocaching/cgeoinit.java b/main/src/cgeo/geocaching/cgeoinit.java index 413e291..8391f15 100644 --- a/main/src/cgeo/geocaching/cgeoinit.java +++ b/main/src/cgeo/geocaching/cgeoinit.java @@ -314,6 +314,37 @@ public class cgeoinit extends AbstractActivity { } }); + // Cache details + final CheckBox autoloadButton = (CheckBox) findViewById(R.id.autoload); + autoloadButton.setChecked(Settings.isAutoLoadDescription()); + autoloadButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + Settings.setAutoLoadDesc(autoloadButton.isChecked()); + } + }); + + final CheckBox ratingWantedButton = (CheckBox) findViewById(R.id.ratingwanted); + ratingWantedButton.setChecked(Settings.isRatingWanted()); + ratingWantedButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + Settings.setRatingWanted(ratingWantedButton.isChecked()); + } + }); + + final CheckBox elevationWantedButton = (CheckBox) findViewById(R.id.elevationwanted); + elevationWantedButton.setChecked(Settings.isElevationWanted()); + elevationWantedButton.setOnClickListener(new View.OnClickListener() { + + @Override + public void onClick(View v) { + Settings.setElevationWanted(elevationWantedButton.isChecked()); + } + }); + // Other settings final CheckBox skinButton = (CheckBox) findViewById(R.id.skin); skinButton.setChecked(Settings.isLightSkin()); @@ -419,16 +450,6 @@ public class cgeoinit extends AbstractActivity { } }); - final CheckBox autoloadButton = (CheckBox) findViewById(R.id.autoload); - autoloadButton.setChecked(Settings.isAutoLoadDescription()); - autoloadButton.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - Settings.setAutoLoadDesc(autoloadButton.isChecked()); - } - }); - final CheckBox livelistButton = (CheckBox) findViewById(R.id.livelist); livelistButton.setChecked(Settings.isLiveList()); livelistButton.setOnClickListener(new View.OnClickListener() { diff --git a/main/src/cgeo/geocaching/cgeonavigate.java b/main/src/cgeo/geocaching/cgeonavigate.java index 9907486..284698d 100644 --- a/main/src/cgeo/geocaching/cgeonavigate.java +++ b/main/src/cgeo/geocaching/cgeonavigate.java @@ -216,7 +216,7 @@ public class cgeonavigate extends AbstractActivity { int cnt = 4; for (cgCoord coordinate : coordinates) { - subMenu.add(0, cnt, 0, coordinate.name + " (" + coordinate.type + ")"); + subMenu.add(0, cnt, 0, coordinate.getName() + " (" + coordinate.getType() + ")"); cnt++; } @@ -248,7 +248,7 @@ public class cgeonavigate extends AbstractActivity { int id = item.getItemId(); if (id == 0) { - CGeoMap.startActivityCoords(this, dstCoords, null); + CGeoMap.startActivityCoords(this, dstCoords, null, null); } else if (id == 1) { boolean oldSetting = Settings.isUseCompass(); Settings.setUseCompass(!oldSetting); @@ -270,8 +270,8 @@ public class cgeonavigate extends AbstractActivity { } else if (id > 3 && coordinates.get(id - 4) != null) { cgCoord coordinate = coordinates.get(id - 4); - title = coordinate.name; - dstCoords = coordinate.coords; + title = coordinate.getName(); + dstCoords = coordinate.getCoords(); setTitle(); setDestCoords(); updateDistanceInfo(); diff --git a/main/src/cgeo/geocaching/cgeopopup.java b/main/src/cgeo/geocaching/cgeopopup.java index 9f22164..de1bfd5 100644 --- a/main/src/cgeo/geocaching/cgeopopup.java +++ b/main/src/cgeo/geocaching/cgeopopup.java @@ -3,6 +3,7 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.enumerations.CacheType; +import cgeo.geocaching.utils.CancellableHandler; import org.apache.commons.lang3.StringUtils; @@ -53,10 +54,10 @@ public class cgeopopup extends AbstractActivity { } } }; - private Handler storeCacheHandler = new Handler() { + private CancellableHandler storeCacheHandler = new CancellableHandler() { @Override - public void handleMessage(Message msg) { + public void handleRegularMessage(Message msg) { try { if (storeDialog != null) { storeDialog.dismiss(); @@ -146,7 +147,7 @@ public class cgeopopup extends AbstractActivity { super.onPrepareOptionsMenu(menu); try { - if (cache != null && cache.coords != null) { + if (cache != null && cache.getCoords() != null) { menu.findItem(0).setVisible(true); menu.findItem(2).setVisible(true); menu.findItem(5).setVisible(true); @@ -180,7 +181,7 @@ public class cgeopopup extends AbstractActivity { finish(); return true; } else if (menuItem == 7) { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.geocode))); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.getGeocode()))); return true; } @@ -215,21 +216,21 @@ public class cgeopopup extends AbstractActivity { TextView itemValue; LinearLayout itemStars; - if (StringUtils.isNotBlank(cache.name)) { - setTitle(cache.name); + if (StringUtils.isNotBlank(cache.getName())) { + setTitle(cache.getName()); } else { setTitle(geocode.toUpperCase()); } inflater = getLayoutInflater(); - geocode = cache.geocode.toUpperCase(); + geocode = cache.getGeocode().toUpperCase(); ((ScrollView) findViewById(R.id.details_list_box)).setVisibility(View.VISIBLE); LinearLayout detailsList = (LinearLayout) findViewById(R.id.details_list); detailsList.removeAllViews(); // actionbar icon - ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); + ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.getType())), null, null, null); // cache type itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); @@ -237,17 +238,17 @@ public class cgeopopup extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_type)); - if (cgBase.cacheTypesInv.containsKey(cache.type)) { // cache icon - if (cache.size != null) { - itemValue.setText(cgBase.cacheTypesInv.get(cache.type) - + " (" + res.getString(cache.size.stringId) + ")"); + if (cgBase.cacheTypesInv.containsKey(cache.getType())) { // cache icon + if (cache.getSize() != null) { + itemValue.setText(cgBase.cacheTypesInv.get(cache.getType()) + + " (" + res.getString(cache.getSize().stringId) + ")"); } else { - itemValue.setText(cgBase.cacheTypesInv.get(cache.type)); + itemValue.setText(cgBase.cacheTypesInv.get(cache.getType())); } } else { - if (cache.size != null) { + if (cache.getSize() != null) { itemValue.setText(cgBase.cacheTypesInv.get(CacheType.MYSTERY.id) - + " (" + res.getString(cache.size.stringId) + ")"); + + " (" + res.getString(cache.getSize().stringId) + ")"); } else { itemValue.setText(cgBase.cacheTypesInv.get(CacheType.MYSTERY.id)); } @@ -260,11 +261,11 @@ public class cgeopopup extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.cache_geocode)); - itemValue.setText(cache.geocode.toUpperCase()); + itemValue.setText(cache.getGeocode().toUpperCase()); detailsList.addView(itemLayout); // cache state - if (cache.archived || cache.disabled || cache.members || cache.found) { + if (cache.isArchived() || cache.isDisabled() || cache.isMembers() || cache.isFound()) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); @@ -272,25 +273,25 @@ public class cgeopopup extends AbstractActivity { itemName.setText(res.getString(R.string.cache_status)); StringBuilder state = new StringBuilder(); - if (cache.found) { + if (cache.isFound()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_found)); } - if (cache.archived) { + if (cache.isArchived()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_archived)); } - if (cache.disabled) { + if (cache.isDisabled()) { if (state.length() > 0) { state.append(", "); } state.append(res.getString(R.string.cache_status_disabled)); } - if (cache.members) { + if (cache.isMembers()) { if (state.length() > 0) { state.append(", "); } @@ -314,19 +315,19 @@ public class cgeopopup extends AbstractActivity { cacheDistance = itemValue; // difficulty - if (cache.difficulty > 0f) { + if (cache.getDifficulty() > 0f) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_layout, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); itemStars = (LinearLayout) itemLayout.findViewById(R.id.stars); itemName.setText(res.getString(R.string.cache_difficulty)); - itemValue.setText(String.format(Locale.getDefault(), "%.1f", cache.difficulty) + ' ' + res.getString(R.string.cache_rating_of) + " 5"); + itemValue.setText(String.format(Locale.getDefault(), "%.1f", cache.getDifficulty()) + ' ' + res.getString(R.string.cache_rating_of) + " 5"); for (int i = 0; i <= 4; i++) { ImageView star = (ImageView) inflater.inflate(R.layout.star, null); - if ((cache.difficulty - i) >= 1.0) { + if ((cache.getDifficulty() - i) >= 1.0) { star.setImageResource(R.drawable.star_on); - } else if ((cache.difficulty - i) > 0.0) { + } else if ((cache.getDifficulty() - i) > 0.0) { star.setImageResource(R.drawable.star_half); } else { star.setImageResource(R.drawable.star_off); @@ -337,19 +338,19 @@ public class cgeopopup extends AbstractActivity { } // terrain - if (cache.terrain > 0f) { + if (cache.getTerrain() > 0f) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_layout, null); itemName = (TextView) itemLayout.findViewById(R.id.name); itemValue = (TextView) itemLayout.findViewById(R.id.value); itemStars = (LinearLayout) itemLayout.findViewById(R.id.stars); itemName.setText(res.getString(R.string.cache_terrain)); - itemValue.setText(String.format(Locale.getDefault(), "%.1f", cache.terrain) + ' ' + res.getString(R.string.cache_rating_of) + " 5"); + itemValue.setText(String.format(Locale.getDefault(), "%.1f", cache.getTerrain()) + ' ' + res.getString(R.string.cache_rating_of) + " 5"); for (int i = 0; i <= 4; i++) { ImageView star = (ImageView) inflater.inflate(R.layout.star, null); - if ((cache.terrain - i) >= 1.0) { + if ((cache.getTerrain() - i) >= 1.0) { star.setImageResource(R.drawable.star_on); - } else if ((cache.terrain - i) > 0.0) { + } else if ((cache.getTerrain() - i) > 0.0) { star.setImageResource(R.drawable.star_half); } else { star.setImageResource(R.drawable.star_off); @@ -360,14 +361,15 @@ public class cgeopopup extends AbstractActivity { } // rating - if (cache.rating != null && cache.rating > 0) { - setRating(cache.rating, cache.votes); + if (cache.getRating() != null && cache.getRating() > 0) { + setRating(cache.getRating(), cache.getVotes()); } else { if (cache.supportsGCVote()) { (new Thread() { + @Override public void run() { - cgRating rating = GCVote.getRating(cache.guid, geocode); + cgRating rating = GCVote.getRating(cache.getGuid(), geocode); Message msg = new Message(); Bundle bundle = new Bundle(); @@ -414,8 +416,8 @@ public class cgeopopup extends AbstractActivity { final Button offlineRefresh = (Button) findViewById(R.id.offline_refresh); final Button offlineStore = (Button) findViewById(R.id.offline_store); - if (cache.reason > 0) { - Long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.detailedUpdate / (60 * 1000)); // minutes + if (cache.getReason() > 0) { + Long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes String ago = ""; if (diff < 15) { @@ -513,8 +515,8 @@ public class cgeopopup extends AbstractActivity { } try { - if (geo.coordsNow != null && cache != null && cache.coords != null) { - cacheDistance.setText(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.coords))); + if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { + cacheDistance.setText(cgBase.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); cacheDistance.bringToFront(); } } catch (Exception e) { @@ -524,15 +526,15 @@ public class cgeopopup extends AbstractActivity { } private void navigateTo() { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { showToast(res.getString(R.string.err_location_unknown)); } cgeonavigate navigateActivity = new cgeonavigate(); Intent navigateIntent = new Intent(this, navigateActivity.getClass()); - navigateIntent.putExtra("latitude", cache.coords.getLatitude()); - navigateIntent.putExtra("longitude", cache.coords.getLongitude()); + navigateIntent.putExtra("latitude", cache.getCoords().getLatitude()); + navigateIntent.putExtra("longitude", cache.getCoords().getLongitude()); navigateIntent.putExtra("geocode", ""); navigateIntent.putExtra("name", res.getString(R.string.search_some_destination)); @@ -540,11 +542,11 @@ public class cgeopopup extends AbstractActivity { } private void cachesAround() { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { showToast(res.getString(R.string.err_location_unknown)); } - cgeocaches.startActivityCachesAround(this, cache.coords); + cgeocaches.startActivityCachesAround(this, cache.getCoords()); finish(); } @@ -566,10 +568,10 @@ public class cgeopopup extends AbstractActivity { private class storeCacheThread extends Thread { - private Handler handler = null; + final private CancellableHandler handler; - public storeCacheThread(Handler handlerIn) { - handler = handlerIn; + public storeCacheThread(final CancellableHandler handler) { + this.handler = handler; } @Override @@ -649,7 +651,7 @@ public class cgeopopup extends AbstractActivity { * unused here but needed since this method is referenced from XML layout */ public void goCompass(View view) { - if (cache == null || cache.coords == null) { + if (cache == null || cache.getCoords() == null) { showToast(res.getString(R.string.cache_coordinates_no)); return; @@ -658,16 +660,17 @@ public class cgeopopup extends AbstractActivity { cgeonavigate navigateActivity = new cgeonavigate(); Intent navigateIntent = new Intent(cgeopopup.this, navigateActivity.getClass()); - navigateIntent.putExtra("latitude", cache.coords.getLatitude()); - navigateIntent.putExtra("longitude", cache.coords.getLongitude()); - navigateIntent.putExtra("geocode", cache.geocode.toUpperCase()); - navigateIntent.putExtra("name", cache.name); + navigateIntent.putExtra("latitude", cache.getCoords().getLatitude()); + navigateIntent.putExtra("longitude", cache.getCoords().getLongitude()); + navigateIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); + navigateIntent.putExtra("name", cache.getName()); startActivity(navigateIntent); finish(); } + @Override public void goManual(View view) { super.goManual(view); finish(); diff --git a/main/src/cgeo/geocaching/cgeotrackable.java b/main/src/cgeo/geocaching/cgeotrackable.java index 4037853..453be7b 100644 --- a/main/src/cgeo/geocaching/cgeotrackable.java +++ b/main/src/cgeo/geocaching/cgeotrackable.java @@ -1,6 +1,7 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; +import cgeo.geocaching.network.HtmlImage; import org.apache.commons.lang3.StringUtils; @@ -226,7 +227,7 @@ public class cgeotrackable extends AbstractActivity { ((LinearLayout) findViewById(R.id.goal_box)).setVisibility(View.VISIBLE); TextView descView = (TextView) findViewById(R.id.goal); descView.setVisibility(View.VISIBLE); - descView.setText(Html.fromHtml(trackable.getGoal(), new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); + descView.setText(Html.fromHtml(trackable.getGoal(), new HtmlImage(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); descView.setMovementMethod(LinkMovementMethod.getInstance()); } @@ -235,7 +236,7 @@ public class cgeotrackable extends AbstractActivity { ((LinearLayout) findViewById(R.id.details_box)).setVisibility(View.VISIBLE); TextView descView = (TextView) findViewById(R.id.details); descView.setVisibility(View.VISIBLE); - descView.setText(Html.fromHtml(trackable.getDetails(), new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); + descView.setText(Html.fromHtml(trackable.getDetails(), new HtmlImage(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); descView.setMovementMethod(LinkMovementMethod.getInstance()); } @@ -273,7 +274,7 @@ public class cgeotrackable extends AbstractActivity { public void run() { BitmapDrawable image = null; try { - cgHtmlImg imgGetter = new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false); + HtmlImage imgGetter = new HtmlImage(cgeotrackable.this, geocode, true, 0, false); image = imgGetter.getDrawable(trackable.getImage()); Message message = handler.obtainMessage(0, image); @@ -520,7 +521,7 @@ public class cgeotrackable extends AbstractActivity { }); } - ((TextView) rowView.findViewById(R.id.log)).setText(Html.fromHtml(log.log, new cgHtmlImg(cgeotrackable.this, null, false, 0, false), null), TextView.BufferType.SPANNABLE); + ((TextView) rowView.findViewById(R.id.log)).setText(Html.fromHtml(log.log, new HtmlImage(cgeotrackable.this, null, false, 0, false), null), TextView.BufferType.SPANNABLE); ((TextView) rowView.findViewById(R.id.author)).setOnClickListener(new userActions()); listView.addView(rowView); @@ -572,7 +573,7 @@ public class cgeotrackable extends AbstractActivity { BitmapDrawable image = null; try { - cgHtmlImg imgGetter = new cgHtmlImg(cgeotrackable.this, trackable.getGeocode(), false, 0, false); + HtmlImage imgGetter = new HtmlImage(cgeotrackable.this, trackable.getGeocode(), false, 0, false); image = imgGetter.getDrawable(url); Message message = handler.obtainMessage(0, image); diff --git a/main/src/cgeo/geocaching/cgeovisit.java b/main/src/cgeo/geocaching/cgeovisit.java index f9a7606..af097d2 100644 --- a/main/src/cgeo/geocaching/cgeovisit.java +++ b/main/src/cgeo/geocaching/cgeovisit.java @@ -233,10 +233,10 @@ public class cgeovisit extends cgLogForm { cache = app.getCacheByGeocode(geocode); - if (StringUtils.isNotBlank(cache.name)) { - setTitle(res.getString(R.string.log_new_log) + " " + cache.name); + if (StringUtils.isNotBlank(cache.getName())) { + setTitle(res.getString(R.string.log_new_log) + " " + cache.getName()); } else { - setTitle(res.getString(R.string.log_new_log) + " " + cache.geocode.toUpperCase()); + setTitle(res.getString(R.string.log_new_log) + " " + cache.getGeocode().toUpperCase()); } app.setAction(geocode); @@ -293,7 +293,7 @@ public class cgeovisit extends cgLogForm { boolean signatureAvailable = Settings.getSignature() != null; menu.findItem(MENU_SIGNATURE).setVisible(signatureAvailable); - boolean voteAvailable = Settings.isGCvoteLogin() && typeSelected == cgBase.LOG_FOUND_IT && StringUtils.isNotBlank(cache.guid); + boolean voteAvailable = Settings.isGCvoteLogin() && typeSelected == cgBase.LOG_FOUND_IT && StringUtils.isNotBlank(cache.getGuid()); menu.findItem(SUBMENU_VOTE).setVisible(voteAvailable); return true; @@ -531,6 +531,7 @@ public class cgeovisit extends cgLogForm { clear.setOnClickListener(new clearListener()); } + @Override public void setDate(Calendar dateIn) { date = dateIn; @@ -720,15 +721,15 @@ public class cgeovisit extends cgLogForm { logNow.type = typeSelected; logNow.log = log; - if (cache != null && null != cache.logs) { - cache.logs.add(0, logNow); + if (cache != null && null != cache.getLogs()) { + cache.getLogs().add(0, logNow); } app.addLog(geocode, logNow); if (typeSelected == cgBase.LOG_FOUND_IT) { app.markFound(geocode); if (cache != null) { - cache.found = true; + cache.setFound(true); } } diff --git a/main/src/cgeo/geocaching/cgeowaypoint.java b/main/src/cgeo/geocaching/cgeowaypoint.java index 96a0d22..b0d183b 100644 --- a/main/src/cgeo/geocaching/cgeowaypoint.java +++ b/main/src/cgeo/geocaching/cgeowaypoint.java @@ -60,22 +60,22 @@ public class cgeowaypoint extends AbstractActivity { final View headline = findViewById(R.id.headline); registerNavigationMenu(headline); - if (StringUtils.isNotBlank(waypoint.name)) { - setTitle(Html.fromHtml(waypoint.name.trim()).toString()); + if (StringUtils.isNotBlank(waypoint.getName())) { + setTitle(Html.fromHtml(waypoint.getName().trim()).toString()); } else { setTitle(res.getString(R.string.waypoint_title)); } if (!waypoint.getPrefix().equalsIgnoreCase("OWN")) { - identification.setText(waypoint.getPrefix().trim() + "/" + waypoint.lookup.trim()); + identification.setText(waypoint.getPrefix().trim() + "/" + waypoint.getLookup().trim()); } else { identification.setText(res.getString(R.string.waypoint_custom)); } registerNavigationMenu(identification); waypoint.setIcon(res, identification); - if (waypoint.coords != null) { - coords.setText(Html.fromHtml(cgBase.formatCoords(waypoint.coords, true)), TextView.BufferType.SPANNABLE); + if (waypoint.getCoords() != null) { + coords.setText(Html.fromHtml(cgBase.formatCoords(waypoint.getCoords(), true)), TextView.BufferType.SPANNABLE); compass.setVisibility(View.VISIBLE); separator.setVisibility(View.VISIBLE); } else { @@ -85,9 +85,9 @@ public class cgeowaypoint extends AbstractActivity { } registerNavigationMenu(coords); - if (StringUtils.isNotBlank(waypoint.note)) { + if (StringUtils.isNotBlank(waypoint.getNote())) { final TextView note = (TextView) findViewById(R.id.note); - note.setText(Html.fromHtml(waypoint.note.trim()), TextView.BufferType.SPANNABLE); + note.setText(Html.fromHtml(waypoint.getNote().trim()), TextView.BufferType.SPANNABLE); registerNavigationMenu(note); } @@ -230,7 +230,7 @@ public class cgeowaypoint extends AbstractActivity { super.onPrepareOptionsMenu(menu); try { - boolean visible = waypoint != null && waypoint.coords != null; + boolean visible = waypoint != null && waypoint.getCoords() != null; menu.findItem(MENU_ID_NAVIGATION).setVisible(visible); menu.findItem(MENU_ID_COMPASS).setVisible(visible); menu.findItem(MENU_ID_CACHES_AROUND).setVisible(visible); @@ -256,11 +256,11 @@ public class cgeowaypoint extends AbstractActivity { } private void cachesAround() { - if (waypoint == null || waypoint.coords == null) { + if (waypoint == null || waypoint.getCoords() == null) { showToast(res.getString(R.string.err_location_unknown)); } - cgeocaches.startActivityCachesAround(this, waypoint.coords); + cgeocaches.startActivityCachesAround(this, waypoint.getCoords()); finish(); } @@ -321,11 +321,11 @@ public class cgeowaypoint extends AbstractActivity { Collection<cgCoord> coordinatesWithType = new ArrayList<cgCoord>(); coordinatesWithType.add(new cgCoord(waypoint)); - cgeonavigate.startActivity(this, waypoint.getPrefix().trim() + "/" + waypoint.lookup.trim(), waypoint.name, waypoint.coords, coordinatesWithType); + cgeonavigate.startActivity(this, waypoint.getPrefix().trim() + "/" + waypoint.getLookup().trim(), waypoint.getName(), waypoint.getCoords(), coordinatesWithType); } private boolean navigationPossible() { - if (waypoint == null || waypoint.coords == null) { + if (waypoint == null || waypoint.getCoords() == null) { showToast(res.getString(R.string.err_location_unknown)); return false; } diff --git a/main/src/cgeo/geocaching/cgeowaypointadd.java b/main/src/cgeo/geocaching/cgeowaypointadd.java index 5d21f0e..be90847 100644 --- a/main/src/cgeo/geocaching/cgeowaypointadd.java +++ b/main/src/cgeo/geocaching/cgeowaypointadd.java @@ -53,19 +53,19 @@ public class cgeowaypointadd extends AbstractActivity { id = -1; } else { - geocode = waypoint.geocode; - type = waypoint.type; + geocode = waypoint.getGeocode(); + type = waypoint.getWaypointType(); prefix = waypoint.getPrefix(); - lookup = waypoint.lookup; + lookup = waypoint.getLookup(); app.setAction(geocode); - if (waypoint.coords != null) { - ((Button) findViewById(R.id.buttonLatitude)).setText(cgBase.formatLatitude(waypoint.coords.getLatitude(), true)); - ((Button) findViewById(R.id.buttonLongitude)).setText(cgBase.formatLongitude(waypoint.coords.getLongitude(), true)); + if (waypoint.getCoords() != null) { + ((Button) findViewById(R.id.buttonLatitude)).setText(cgBase.formatLatitude(waypoint.getCoords().getLatitude(), true)); + ((Button) findViewById(R.id.buttonLongitude)).setText(cgBase.formatLongitude(waypoint.getCoords().getLongitude(), true)); } - ((EditText) findViewById(R.id.name)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.name)).toString()); - ((EditText) findViewById(R.id.note)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.note)).toString()); + ((EditText) findViewById(R.id.name)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getName())).toString()); + ((EditText) findViewById(R.id.note)).setText(Html.fromHtml(StringUtils.trimToEmpty(waypoint.getNote())).toString()); if (waitDialog != null) { waitDialog.dismiss(); @@ -223,8 +223,8 @@ public class cgeowaypointadd extends AbstractActivity { public void onClick(View arg0) { Geopoint gp = null; - if (waypoint != null && waypoint.coords != null) - gp = waypoint.coords; + if (waypoint != null && waypoint.getCoords() != null) + gp = waypoint.getCoords(); cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, gp, geo); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @@ -233,7 +233,7 @@ public class cgeowaypointadd extends AbstractActivity { ((Button) findViewById(R.id.buttonLatitude)).setText(gp.format(GeopointFormatter.Format.LAT_DECMINUTE)); ((Button) findViewById(R.id.buttonLongitude)).setText(gp.format(GeopointFormatter.Format.LON_DECMINUTE)); if (waypoint != null) { - waypoint.coords = gp; + waypoint.setCoords(gp); } } }); @@ -329,13 +329,13 @@ public class cgeowaypointadd extends AbstractActivity { final String note = ((EditText) findViewById(R.id.note)).getText().toString().trim(); final cgWaypoint waypoint = new cgWaypoint(); - waypoint.type = type; - waypoint.geocode = geocode; + waypoint.setWaypointType(type); + waypoint.setGeocode(geocode); waypoint.setPrefix(prefix); - waypoint.lookup = lookup; - waypoint.name = name; - waypoint.coords = new Geopoint(coords.get(0), coords.get(1)); - waypoint.note = note; + waypoint.setLookup(lookup); + waypoint.setName(name); + waypoint.setCoords(new Geopoint(coords.get(0), coords.get(1))); + waypoint.setNote(note); if (app.saveOwnWaypoint(id, geocode, waypoint)) { app.removeCacheFromCache(geocode); @@ -348,6 +348,7 @@ public class cgeowaypointadd extends AbstractActivity { } } + @Override public void goManual(View view) { if (id >= 0) { ActivityMixin.goManual(this, "c:geo-waypoint-edit"); diff --git a/main/src/cgeo/geocaching/connector/AbstractConnector.java b/main/src/cgeo/geocaching/connector/AbstractConnector.java index 1a3048a..a0ed628 100644 --- a/main/src/cgeo/geocaching/connector/AbstractConnector.java +++ b/main/src/cgeo/geocaching/connector/AbstractConnector.java @@ -4,10 +4,7 @@ import cgeo.geocaching.cgBase; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgeoapplication; - -import android.os.Handler; - -import java.util.UUID; +import cgeo.geocaching.utils.CancellableHandler; public abstract class AbstractConnector implements IConnector { @@ -47,7 +44,7 @@ public abstract class AbstractConnector implements IConnector { } @Override - public UUID searchByGeocode(cgBase base, String geocode, String guid, cgeoapplication app, cgSearch search, int reason, Handler handler) { + public cgSearch searchByGeocode(cgBase base, String geocode, String guid, cgeoapplication app, cgSearch search, int reason, CancellableHandler handler) { return null; } diff --git a/main/src/cgeo/geocaching/connector/ConnectorFactory.java b/main/src/cgeo/geocaching/connector/ConnectorFactory.java index 790090f..a264bd8 100644 --- a/main/src/cgeo/geocaching/connector/ConnectorFactory.java +++ b/main/src/cgeo/geocaching/connector/ConnectorFactory.java @@ -42,7 +42,7 @@ public final class ConnectorFactory { } public static IConnector getConnector(cgCache cache) { - return getConnector(cache.geocode); + return getConnector(cache.getGeocode()); } public static IConnector getConnector(String geocode) { diff --git a/main/src/cgeo/geocaching/connector/GCConnector.java b/main/src/cgeo/geocaching/connector/GCConnector.java index 05c0218..f86aa28 100644 --- a/main/src/cgeo/geocaching/connector/GCConnector.java +++ b/main/src/cgeo/geocaching/connector/GCConnector.java @@ -8,16 +8,15 @@ import cgeo.geocaching.cgCache; import cgeo.geocaching.cgCacheWrap; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.utils.CancellableHandler; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import android.os.Handler; import android.util.Log; import java.util.ArrayList; import java.util.List; -import java.util.UUID; public class GCConnector extends AbstractConnector implements IConnector { @@ -33,8 +32,8 @@ public class GCConnector extends AbstractConnector implements IConnector { @Override public String getCacheUrl(cgCache cache) { - // it would also be possible to use "http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.geocode; - return "http://coord.info/" + cache.geocode; + // it would also be possible to use "http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.getGeocode(); + return "http://coord.info/" + cache.getGeocode(); } @Override @@ -68,7 +67,7 @@ public class GCConnector extends AbstractConnector implements IConnector { } @Override - public UUID searchByGeocode(final cgBase base, String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final Handler handler) { + public cgSearch searchByGeocode(final cgBase base, String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final CancellableHandler handler) { final Parameters params = new Parameters("decrypt", "y"); if (StringUtils.isNotBlank(geocode)) { params.put("wp", geocode); @@ -102,7 +101,7 @@ public class GCConnector extends AbstractConnector implements IConnector { cacheList.clear(); - return search.getCurrentId(); + return search; } Log.e(Settings.tag, "cgeoBase.searchByGeocode: No data from server"); @@ -128,6 +127,6 @@ public class GCConnector extends AbstractConnector implements IConnector { final List<cgCache> cacheList = cgBase.filterSearchResults(search, caches, false, false, null); app.addSearch(search, cacheList, true, reason); - return search.getCurrentId(); + return search; } } diff --git a/main/src/cgeo/geocaching/connector/GeocachingAustraliaConnector.java b/main/src/cgeo/geocaching/connector/GeocachingAustraliaConnector.java index 58f4743..ef74f6a 100644 --- a/main/src/cgeo/geocaching/connector/GeocachingAustraliaConnector.java +++ b/main/src/cgeo/geocaching/connector/GeocachingAustraliaConnector.java @@ -13,7 +13,7 @@ public class GeocachingAustraliaConnector extends AbstractConnector implements I @Override public String getCacheUrl(final cgCache cache) { - return "http://" + getHost() + "/cache/" + cache.geocode; + return "http://" + getHost() + "/cache/" + cache.getGeocode(); } @Override diff --git a/main/src/cgeo/geocaching/connector/GeopeitusConnector.java b/main/src/cgeo/geocaching/connector/GeopeitusConnector.java index 6db0da6..be77705 100644 --- a/main/src/cgeo/geocaching/connector/GeopeitusConnector.java +++ b/main/src/cgeo/geocaching/connector/GeopeitusConnector.java @@ -13,7 +13,7 @@ public class GeopeitusConnector extends AbstractConnector implements IConnector @Override public String getCacheUrl(final cgCache cache) { - return "http://" + getHost() + "/aare/" + StringUtils.stripStart(cache.geocode.substring(2), "0"); + return "http://" + getHost() + "/aare/" + StringUtils.stripStart(cache.getGeocode().substring(2), "0"); } @Override diff --git a/main/src/cgeo/geocaching/connector/IConnector.java b/main/src/cgeo/geocaching/connector/IConnector.java index 68c9db6..89a94a1 100644 --- a/main/src/cgeo/geocaching/connector/IConnector.java +++ b/main/src/cgeo/geocaching/connector/IConnector.java @@ -4,10 +4,7 @@ import cgeo.geocaching.cgBase; import cgeo.geocaching.cgCache; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgeoapplication; - -import android.os.Handler; - -import java.util.UUID; +import cgeo.geocaching.utils.CancellableHandler; public interface IConnector { /** @@ -78,5 +75,5 @@ public interface IConnector { */ public boolean supportsCachesAround(); - public UUID searchByGeocode(final cgBase base, final String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final Handler handler); + public cgSearch searchByGeocode(final cgBase base, final String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final CancellableHandler handler); } diff --git a/main/src/cgeo/geocaching/connector/OXConnector.java b/main/src/cgeo/geocaching/connector/OXConnector.java index 78d60b7..9ffff5c 100644 --- a/main/src/cgeo/geocaching/connector/OXConnector.java +++ b/main/src/cgeo/geocaching/connector/OXConnector.java @@ -17,7 +17,7 @@ public class OXConnector extends AbstractConnector implements IConnector { @Override public String getCacheUrl(cgCache cache) { - return "http://www.opencaching.com/#!geocache/" + cache.geocode; + return "http://www.opencaching.com/#!geocache/" + cache.getGeocode(); } @Override diff --git a/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java b/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java index 6334973..8660d2a 100644 --- a/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java +++ b/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java @@ -7,12 +7,10 @@ import cgeo.geocaching.cgCacheWrap; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.connector.IConnector; +import cgeo.geocaching.utils.CancellableHandler; import cgeo.geocaching.utils.CryptUtils; -import android.os.Handler; - import java.util.List; -import java.util.UUID; public class ApiOpenCachingConnector extends OpenCachingConnector implements IConnector { @@ -39,7 +37,7 @@ public class ApiOpenCachingConnector extends OpenCachingConnector implements ICo } @Override - public UUID searchByGeocode(final cgBase base, final String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final Handler handler) { + public cgSearch searchByGeocode(final cgBase base, final String geocode, final String guid, final cgeoapplication app, final cgSearch search, final int reason, final CancellableHandler handler) { final cgCache cache = OkapiClient.getCache(geocode); if (cache == null) { return null; @@ -50,6 +48,6 @@ public class ApiOpenCachingConnector extends OpenCachingConnector implements ICo final List<cgCache> cacheList = cgBase.filterSearchResults(search, caches, false, false, null); app.addSearch(search, cacheList, true, reason); - return search.getCurrentId(); + return search; } } diff --git a/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java b/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java index 30c1673..7c35088 100644 --- a/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java +++ b/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java @@ -69,8 +69,8 @@ final public class OkapiClient { final cgCache cache = parseCache(data); - cache.updated = new Date().getTime(); - cache.detailedUpdate = new Date().getTime(); + cache.setUpdated(new Date().getTime()); + cache.setDetailedUpdate(new Date().getTime()); return cache; } @@ -78,34 +78,34 @@ final public class OkapiClient { private static cgCache parseCache(final JSONObject response) { final cgCache cache = new cgCache(); try { - cache.geocode = response.getString(CACHE_CODE); - cache.name = response.getString(CACHE_NAME); + cache.setGeocode(response.getString(CACHE_CODE)); + cache.setName(response.getString(CACHE_NAME)); // not used: names setLocation(cache, response.getString(CACHE_LOCATION)); - cache.type = getCacheType(response.getString(CACHE_TYPE)); + cache.setCacheType(CacheType.getById(getCacheType(response.getString(CACHE_TYPE)))); final String status = response.getString(CACHE_STATUS); - cache.disabled = status.equalsIgnoreCase("Temporarily unavailable"); - cache.archived = status.equalsIgnoreCase("Archived"); + cache.setDisabled(status.equalsIgnoreCase("Temporarily unavailable")); + cache.setArchived(status.equalsIgnoreCase("Archived")); // not used: url final JSONObject owner = response.getJSONObject(CACHE_OWNER); - cache.owner = parseUser(owner); + cache.setOwner(parseUser(owner)); - cache.logCounts.put(cgBase.LOG_FOUND_IT, response.getInt(CACHE_FOUNDS)); - cache.logCounts.put(cgBase.LOG_DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS)); - cache.size = getCacheSize(response); - cache.difficulty = (float) response.getDouble(CACHE_DIFFICULTY); - cache.terrain = (float) response.getDouble(CACHE_TERRAIN); + cache.getLogCounts().put(cgBase.LOG_FOUND_IT, response.getInt(CACHE_FOUNDS)); + cache.getLogCounts().put(cgBase.LOG_DIDNT_FIND_IT, response.getInt(CACHE_NOTFOUNDS)); + cache.setSize(getCacheSize(response)); + cache.setDifficulty((float) response.getDouble(CACHE_DIFFICULTY)); + cache.setTerrain((float) response.getDouble(CACHE_TERRAIN)); if (response.has(CACHE_RATING) && !isNull(response.getString(CACHE_RATING))) { - cache.rating = (float) response.getDouble(CACHE_RATING); + cache.setRating((float) response.getDouble(CACHE_RATING)); } - cache.votes = response.getInt(CACHE_VOTES); + cache.setVotes(response.getInt(CACHE_VOTES)); - cache.favouriteCnt = response.getInt(CACHE_RECOMMENDATIONS); + cache.setFavouriteCnt(response.getInt(CACHE_RECOMMENDATIONS)); // not used: req_password cache.setDescription(response.getString(CACHE_DESCRIPTION)); - cache.hint = Html.fromHtml(response.getString(CACHE_HINT)).toString(); + cache.setHint(Html.fromHtml(response.getString(CACHE_HINT)).toString()); // not used: hints final JSONArray images = response.getJSONArray(CACHE_IMAGES); @@ -117,18 +117,18 @@ final public class OkapiClient { if (imageResponse.getBoolean(CACHE_IMAGE_IS_SPOILER)) { image = new cgImage(); image.title = imageResponse.getString(CACHE_IMAGE_CAPTION); - image.url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.geocode); - if (cache.spoilers == null) { - cache.spoilers = new ArrayList<cgImage>(); + image.url = absoluteUrl(imageResponse.getString(CACHE_IMAGE_URL), cache.getGeocode()); + if (cache.getSpoilers() == null) { + cache.setSpoilers(new ArrayList<cgImage>()); } - cache.spoilers.add(image); + cache.getSpoilers().add(image); } } } // not used: attrnames - cache.logs = parseLogs(response.getJSONArray(CACHE_LATEST_LOGS)); - cache.hidden = parseDate(response.getString(CACHE_HIDDEN)); + cache.setLogs(parseLogs(response.getJSONArray(CACHE_LATEST_LOGS))); + cache.setHidden(parseDate(response.getString(CACHE_HIDDEN))); } catch (JSONException e) { // TODO Auto-generated catch block @@ -204,7 +204,7 @@ final public class OkapiClient { final String latitude = StringUtils.substringBefore(location, "|"); final String longitude = StringUtils.substringAfter(location, "|"); // FIXME: the next line should be a setter at cgCache - cache.coords = GeopointParser.parse(latitude, longitude); + cache.setCoords(GeopointParser.parse(latitude, longitude)); } private static CacheSize getCacheSize(final JSONObject response) { diff --git a/main/src/cgeo/geocaching/connector/opencaching/OpenCachingConnector.java b/main/src/cgeo/geocaching/connector/opencaching/OpenCachingConnector.java index 273c4cd..039a9e7 100644 --- a/main/src/cgeo/geocaching/connector/opencaching/OpenCachingConnector.java +++ b/main/src/cgeo/geocaching/connector/opencaching/OpenCachingConnector.java @@ -30,7 +30,7 @@ public class OpenCachingConnector extends AbstractConnector implements IConnecto @Override public String getCacheUrl(cgCache cache) { - return "http://" + host + "/viewcache.php?wp=" + cache.geocode; + return "http://" + host + "/viewcache.php?wp=" + cache.getGeocode(); } @Override diff --git a/main/src/cgeo/geocaching/enumerations/CacheType.java b/main/src/cgeo/geocaching/enumerations/CacheType.java index 1dc9cf1..e8f19cc 100644 --- a/main/src/cgeo/geocaching/enumerations/CacheType.java +++ b/main/src/cgeo/geocaching/enumerations/CacheType.java @@ -41,13 +41,33 @@ public enum CacheType { this.stringId = stringId; } - public final static Map<String, CacheType> FIND_BY_ID; + private final static Map<String, CacheType> FIND_BY_ID; + private final static Map<String, CacheType> FIND_BY_PATTERN; static { - final HashMap<String, CacheType> mapping = new HashMap<String, CacheType>(); + final HashMap<String, CacheType> mappingId = new HashMap<String, CacheType>(); + final HashMap<String, CacheType> mappingPattern = new HashMap<String, CacheType>(); for (CacheType ct : values()) { - mapping.put(ct.id, ct); + mappingId.put(ct.id, ct); + mappingPattern.put(ct.pattern, ct); } - FIND_BY_ID = Collections.unmodifiableMap(mapping); + FIND_BY_ID = Collections.unmodifiableMap(mappingId); + FIND_BY_PATTERN = Collections.unmodifiableMap(mappingPattern); + } + + public final static CacheType getById(final String id) { + final CacheType result = CacheType.FIND_BY_ID.get(id.toLowerCase().trim()); + if (result == null) { + return UNKNOWN; + } + return result; + } + + public final static CacheType getByPattern(final String pattern) { + final CacheType result = CacheType.FIND_BY_PATTERN.get(pattern.toLowerCase().trim()); + if (result == null) { + return UNKNOWN; + } + return result; } } diff --git a/main/src/cgeo/geocaching/files/FileParser.java b/main/src/cgeo/geocaching/files/FileParser.java index f697f07..1083c65 100644 --- a/main/src/cgeo/geocaching/files/FileParser.java +++ b/main/src/cgeo/geocaching/files/FileParser.java @@ -40,14 +40,14 @@ public abstract class FileParser { } protected static void fixCache(cgCache cache) { - if (cache.inventory != null) { - cache.inventoryItems = cache.inventory.size(); + if (cache.getInventory() != null) { + cache.setInventoryItems(cache.getInventory().size()); } else { - cache.inventoryItems = 0; + cache.setInventoryItems(0); } final long time = new Date().getTime(); - cache.updated = time; - cache.detailedUpdate = time; + cache.setUpdated(time); + cache.setDetailedUpdate(time); } } diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java index 5b4f7de..900c83b 100644 --- a/main/src/cgeo/geocaching/files/GPXParser.java +++ b/main/src/cgeo/geocaching/files/GPXParser.java @@ -41,7 +41,6 @@ import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; -import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -258,8 +257,8 @@ public abstract class GPXParser extends FileParser { public void start(Attributes attrs) { try { if (attrs.getIndex("lat") > -1 && attrs.getIndex("lon") > -1) { - cache.coords = new Geopoint(new Double(attrs.getValue("lat")), - new Double(attrs.getValue("lon"))); + cache.setCoords(new Geopoint(new Double(attrs.getValue("lat")), + new Double(attrs.getValue("lon")))); } } catch (Exception e) { Log.w(Settings.tag, "Failed to parse waypoint's latitude and/or longitude."); @@ -272,28 +271,28 @@ public abstract class GPXParser extends FileParser { @Override public void end() { - if (StringUtils.isBlank(cache.geocode)) { + if (StringUtils.isBlank(cache.getGeocode())) { // try to find geocode somewhere else findGeoCode(name); findGeoCode(desc); findGeoCode(cmt); } - if (StringUtils.isNotBlank(cache.geocode) - && cache.coords != null + if (StringUtils.isNotBlank(cache.getGeocode()) + && cache.getCoords() != null && ((type == null && sym == null) || StringUtils.contains(type, "geocache") || StringUtils.contains(sym, "geocache"))) { fixCache(cache); - cache.reason = listId; - cache.detailed = true; + cache.setReason(listId); + cache.setDetailed(true); createNoteFromGSAKUserdata(); - result.put(cache.geocode, cache); + result.put(cache.getGeocode(), cache); showCountMessage(handler, R.string.gpx_import_loading_caches, ++importedRecords, progressStream.getProgress()); - } else if (StringUtils.isNotBlank(cache.name) - && cache.coords != null + } else if (StringUtils.isNotBlank(cache.getName()) + && cache.getCoords() != null && StringUtils.contains(type, "waypoint")) { addWaypointToCache(); } @@ -304,27 +303,27 @@ public abstract class GPXParser extends FileParser { private void addWaypointToCache() { fixCache(cache); - if (cache.name.length() > 2) { - final String cacheGeocodeForWaypoint = "GC" + cache.name.substring(2); + if (cache.getName().length() > 2) { + final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2); // lookup cache for waypoint in already parsed caches final cgCache cacheForWaypoint = result.get(cacheGeocodeForWaypoint); if (cacheForWaypoint != null) { final cgWaypoint waypoint = new cgWaypoint(); - waypoint.id = -1; - waypoint.type = convertWaypointSym2Type(sym); - waypoint.geocode = cacheGeocodeForWaypoint; - waypoint.setPrefix(cache.name.substring(0, 2)); - waypoint.lookup = "---"; + waypoint.setId(-1); + waypoint.setWaypointType(convertWaypointSym2Type(sym)); + waypoint.setGeocode(cacheGeocodeForWaypoint); + waypoint.setPrefix(cache.getName().substring(0, 2)); + waypoint.setLookup("---"); // there is no lookup code in gpx file - waypoint.name = cache.shortdesc; - waypoint.coords = cache.coords; - waypoint.note = cache.getDescription(); + waypoint.setName(cache.getShortdesc()); + waypoint.setCoords(cache.getCoords()); + waypoint.setNote(cache.getDescription()); - if (cacheForWaypoint.waypoints == null) { - cacheForWaypoint.waypoints = new ArrayList<cgWaypoint>(); + if (cacheForWaypoint.getWaypoints() == null) { + cacheForWaypoint.setWaypoints(new ArrayList<cgWaypoint>()); } - cgWaypoint.mergeWayPoints(cacheForWaypoint.waypoints, Collections.singletonList(waypoint)); + cgWaypoint.mergeWayPoints(cacheForWaypoint.getWaypoints(), Collections.singletonList(waypoint)); result.put(cacheGeocodeForWaypoint, cacheForWaypoint); showCountMessage(handler, R.string.gpx_import_loading_waypoints, ++importedRecords, progressStream.getProgress()); } @@ -338,14 +337,14 @@ public abstract class GPXParser extends FileParser { @Override public void end(String body) { try { - cache.hidden = parseDate(body); + cache.setHidden(parseDate(body)); } catch (Exception e) { Log.w(Settings.tag, "Failed to parse cache date: " + e.toString()); } } }); - // waypoint.name + // waypoint.getName() waypoint.getChild(namespace, "name").setEndTextElementListener(new EndTextElementListener() { @Override @@ -353,9 +352,9 @@ public abstract class GPXParser extends FileParser { name = body; final String content = body.trim(); - cache.name = content; + cache.setName(content); - findGeoCode(cache.name); + findGeoCode(cache.getName()); } }); @@ -366,7 +365,7 @@ public abstract class GPXParser extends FileParser { public void end(String body) { desc = body; - cache.shortdesc = validate(body); + cache.setShortdesc(validate(body)); } }); @@ -381,7 +380,7 @@ public abstract class GPXParser extends FileParser { } }); - // waypoint.type + // waypoint.getType() waypoint.getChild(namespace, "type").setEndTextElementListener(new EndTextElementListener() { @Override @@ -400,7 +399,7 @@ public abstract class GPXParser extends FileParser { public void end(final String body) { sym = body.toLowerCase(); if (sym.contains("geocache") && sym.contains("found")) { - cache.found = true; + cache.setFound(true); } } }); @@ -414,7 +413,7 @@ public abstract class GPXParser extends FileParser { if (matcher.matches()) { final String guid = matcher.group(1); if (StringUtils.isNotBlank(guid)) { - cache.guid = guid; + cache.setGuid(guid); } } } @@ -430,7 +429,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String watchList) { - cache.onWatchlist = Boolean.valueOf(watchList.trim()); + cache.setOnWatchlist(Boolean.valueOf(watchList.trim())); } }); @@ -451,13 +450,13 @@ public abstract class GPXParser extends FileParser { public void start(Attributes attrs) { try { if (attrs.getIndex("id") > -1) { - cache.cacheId = attrs.getValue("id"); + cache.setCacheId(attrs.getValue("id")); } if (attrs.getIndex("archived") > -1) { - cache.archived = attrs.getValue("archived").equalsIgnoreCase("true"); + cache.setArchived(attrs.getValue("archived").equalsIgnoreCase("true")); } if (attrs.getIndex("available") > -1) { - cache.disabled = !attrs.getValue("available").equalsIgnoreCase("true"); + cache.setDisabled(!attrs.getValue("available").equalsIgnoreCase("true")); } } catch (Exception e) { Log.w(Settings.tag, "Failed to parse cache attributes."); @@ -465,30 +464,30 @@ public abstract class GPXParser extends FileParser { } }); - // waypoint.cache.name + // waypoint.cache.getName() gcCache.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String cacheName) { - cache.name = validate(cacheName); + cache.setName(validate(cacheName)); } }); - // waypoint.cache.owner + // waypoint.cache.getOwner() gcCache.getChild(nsGC, "owner").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String cacheOwner) { - cache.owner = validate(cacheOwner); + cache.setOwner(validate(cacheOwner)); } }); - // waypoint.cache.type + // waypoint.cache.getType() gcCache.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { - setType(validate(body.toLowerCase())); + cache.setCacheType(CacheType.getByPattern(validate(body.toLowerCase()))); } }); @@ -497,11 +496,11 @@ public abstract class GPXParser extends FileParser { @Override public void end(String body) { - cache.size = CacheSize.FIND_BY_ID.get(validate(body.toLowerCase())); + cache.setSize(CacheSize.FIND_BY_ID.get(validate(body.toLowerCase()))); } }); - // waypoint.cache.attributes + // waypoint.cache.getAttributes() // @see issue #299 // <groundspeak:attributes> @@ -523,10 +522,10 @@ public abstract class GPXParser extends FileParser { boolean attributeActive = Integer.parseInt(attrs.getValue("inc")) != 0; String internalId = CacheAttributeTranslator.getInternalId(attributeId, attributeActive); if (internalId != null) { - if (cache.attributes == null) { - cache.attributes = new ArrayList<String>(); + if (cache.getAttributes() == null) { + cache.setAttributes(new ArrayList<String>()); } - cache.attributes.add(internalId); + cache.getAttributes().add(internalId); } } } catch (NumberFormatException e) { @@ -535,26 +534,26 @@ public abstract class GPXParser extends FileParser { } }); - // waypoint.cache.difficulty + // waypoint.cache.getDifficulty() gcCache.getChild(nsGC, "difficulty").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { try { - cache.difficulty = new Float(body); + cache.setDifficulty(new Float(body)); } catch (Exception e) { Log.w(Settings.tag, "Failed to parse difficulty: " + e.toString()); } } }); - // waypoint.cache.terrain + // waypoint.cache.getTerrain() gcCache.getChild(nsGC, "terrain").setEndTextElementListener(new EndTextElementListener() { @Override public void end(String body) { try { - cache.terrain = new Float(body); + cache.setTerrain(new Float(body)); } catch (Exception e) { Log.w(Settings.tag, "Failed to parse terrain: " + e.toString()); } @@ -566,10 +565,10 @@ public abstract class GPXParser extends FileParser { @Override public void end(String country) { - if (StringUtils.isBlank(cache.location)) { - cache.location = validate(country); + if (StringUtils.isBlank(cache.getLocation())) { + cache.setLocation(validate(country)); } else { - cache.location += ", " + country.trim(); + cache.setLocation(cache.getLocation() + ", " + country.trim()); } } }); @@ -579,10 +578,10 @@ public abstract class GPXParser extends FileParser { @Override public void end(String state) { - if (StringUtils.isBlank(cache.location)) { - cache.location = validate(state); + if (StringUtils.isBlank(cache.getLocation())) { + cache.setLocation(validate(state)); } else { - cache.location = state.trim() + ", " + cache.location; + cache.setLocation(state.trim() + ", " + cache.getLocation()); } } }); @@ -592,7 +591,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String encoded) { - cache.hint = validate(encoded); + cache.setHint(validate(encoded)); } }); @@ -600,7 +599,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String shortDesc) { - cache.shortdesc = validate(shortDesc); + cache.setShortdesc(validate(shortDesc)); } }); @@ -640,15 +639,15 @@ public abstract class GPXParser extends FileParser { @Override public void end() { if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) { - if (cache.inventory == null) { - cache.inventory = new ArrayList<cgTrackable>(); + if (cache.getInventory() == null) { + cache.setInventory(new ArrayList<cgTrackable>()); } - cache.inventory.add(trackable); + cache.getInventory().add(trackable); } } }); - // waypoint.cache.travelbugs.travelbug.name + // waypoint.cache.travelbugs.travelbug.getName() gcTB.getChild(nsGC, "name").setEndTextElementListener(new EndTextElementListener() { @Override @@ -684,10 +683,10 @@ public abstract class GPXParser extends FileParser { @Override public void end() { if (StringUtils.isNotBlank(log.log)) { - if (cache.logs == null) { - cache.logs = new ArrayList<cgLog>(); + if (cache.getLogs() == null) { + cache.setLogs(new ArrayList<cgLog>()); } - cache.logs.add(log); + cache.getLogs().add(log); } } }); @@ -705,7 +704,7 @@ public abstract class GPXParser extends FileParser { } }); - // waypoint.cache.logs.log.type + // waypoint.cache.logs.log.getType() gcLog.getChild(nsGC, "type").setEndTextElementListener(new EndTextElementListener() { @Override @@ -794,19 +793,6 @@ public abstract class GPXParser extends FileParser { return input.trim(); } - private void setType(final String parsedString) { - final String lowercase = parsedString.toLowerCase().trim(); - final String knownType = cgBase.cacheTypes.get(lowercase); - if (knownType != null) { - cache.type = knownType; - } - else { - if (StringUtils.isBlank(cache.type)) { - cache.type = CacheType.UNKNOWN.id; - } - } - } - static WaypointType convertWaypointSym2Type(final String sym) { if ("parking area".equalsIgnoreCase(sym)) { return WaypointType.PARKING; @@ -824,14 +810,14 @@ public abstract class GPXParser extends FileParser { } private void findGeoCode(final String input) { - if (input == null || StringUtils.isNotBlank(cache.geocode)) { + if (input == null || StringUtils.isNotBlank(cache.getGeocode())) { return; } final Matcher matcherGeocode = patternGeocode.matcher(input); if (matcherGeocode.find()) { final String geocode = matcherGeocode.group(1); if (ConnectorFactory.canHandle(geocode)) { - cache.geocode = geocode; + cache.setGeocode(geocode); } } } @@ -856,7 +842,7 @@ public abstract class GPXParser extends FileParser { * create a cache note from the UserData1 to UserData4 fields supported by GSAK */ private void createNoteFromGSAKUserdata() { - if (StringUtils.isBlank(cache.personalNote)) { + if (StringUtils.isBlank(cache.getPersonalNote())) { final StringBuilder buffer = new StringBuilder(); for (int i = 0; i < userData.length; i++) { if (StringUtils.isNotBlank(userData[i])) { @@ -865,12 +851,12 @@ public abstract class GPXParser extends FileParser { } final String note = buffer.toString().trim(); if (StringUtils.isNotBlank(note)) { - cache.personalNote = note; + cache.setPersonalNote(note); } } } - public static UUID importGPX(File file, int listId, Handler handler) { + public static cgSearch importGPX(File file, int listId, Handler handler) { try { // parse cache file GPXParser parser = new GPX10Parser(listId); @@ -899,7 +885,7 @@ public abstract class GPXParser extends FileParser { return null; } - public static UUID importGPX(InputStream stream, int listId, Handler handler) { + public static cgSearch importGPX(InputStream stream, int listId, Handler handler) { try { // parse cache file GPXParser parser = new GPX10Parser(listId); @@ -920,18 +906,18 @@ public abstract class GPXParser extends FileParser { return null; } - private static UUID storeParsedCaches(Handler handler, GPXParser parser) { + private static cgSearch storeParsedCaches(Handler handler, GPXParser parser) { final cgSearch search = new cgSearch(); final cgeoapplication app = cgeoapplication.getInstance(); int storedCaches = 0; for (cgCache cache : parser.getParsedCaches()) { // remove from cache, cache can be re-imported - app.removeCacheFromCache(cache.geocode); + app.removeCacheFromCache(cache.getGeocode()); app.addCacheToSearch(search, cache); showCountMessage(handler, R.string.gpx_import_storing, ++storedCaches); } Log.i(Settings.tag, "Caches found in .gpx file: " + parser.getParsedCaches().size()); - return search.getCurrentId(); + return search; } // 1234567.gpx -> 1234567-wpts.gpx diff --git a/main/src/cgeo/geocaching/files/LocParser.java b/main/src/cgeo/geocaching/files/LocParser.java index ddd368a..5baaeac 100644 --- a/main/src/cgeo/geocaching/files/LocParser.java +++ b/main/src/cgeo/geocaching/files/LocParser.java @@ -20,7 +20,6 @@ import java.io.File; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; -import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -46,8 +45,8 @@ public final class LocParser extends FileParser { // save found cache coordinates for (cgCache cache : caches.cacheList) { - if (cidCoords.containsKey(cache.geocode)) { - cgCoord coord = cidCoords.get(cache.geocode); + if (cidCoords.containsKey(cache.getGeocode())) { + cgCoord coord = cidCoords.get(cache.getGeocode()); copyCoordToCache(coord, cache); } @@ -55,13 +54,13 @@ public final class LocParser extends FileParser { } private static void copyCoordToCache(final cgCoord coord, final cgCache cache) { - cache.coords = coord.coords; - cache.difficulty = coord.difficulty; - cache.terrain = coord.terrain; - cache.size = coord.size; - cache.geocode = coord.geocode.toUpperCase(); - if (StringUtils.isBlank(cache.name)) { - cache.name = coord.name; + cache.setCoords(coord.getCoords()); + cache.setDifficulty(coord.getDifficulty()); + cache.setTerrain(coord.getTerrain()); + cache.setSize(coord.getSize()); + cache.setGeocode(coord.getGeocode().toUpperCase()); + if (StringUtils.isBlank(cache.getName())) { + cache.setName(coord.getName()); } } @@ -82,29 +81,27 @@ public final class LocParser extends FileParser { final Matcher matcherGeocode = patternGeocode.matcher(pointString); if (matcherGeocode.find()) { String geocode = matcherGeocode.group(1).trim().toUpperCase(); - pointCoord.name = geocode; - pointCoord.geocode = geocode; + pointCoord.setName(geocode); + pointCoord.setGeocode(geocode); } final Matcher matcherName = patternName.matcher(pointString); if (matcherName.find()) { String name = matcherName.group(1).trim(); - pointCoord.name = StringUtils.substringBeforeLast(name, " by ").trim(); + pointCoord.setName(StringUtils.substringBeforeLast(name, " by ").trim()); // owner = StringUtils.substringAfterLast(" by ").trim(); } final Matcher matcherLat = patternLat.matcher(pointString); final Matcher matcherLon = patternLon.matcher(pointString); if (matcherLat.find() && matcherLon.find()) { - pointCoord.coords = - GeopointParser.parse(matcherLat.group(1).trim(), matcherLon.group(1).trim()); + pointCoord.setCoords(GeopointParser.parse(matcherLat.group(1).trim(), matcherLon.group(1).trim())); } final Matcher matcherDifficulty = patternDifficulty.matcher(pointString); if (matcherDifficulty.find()) { - pointCoord.difficulty = new Float(matcherDifficulty.group(1) - .trim()); + pointCoord.setDifficulty(new Float(matcherDifficulty.group(1).trim())); } final Matcher matcherTerrain = patternTerrain.matcher(pointString); if (matcherTerrain.find()) { - pointCoord.terrain = new Float(matcherTerrain.group(1).trim()); + pointCoord.setTerrain(new Float(matcherTerrain.group(1).trim())); } final Matcher matcherContainer = patternContainer.matcher(pointString); if (matcherContainer.find()) { @@ -112,26 +109,26 @@ public final class LocParser extends FileParser { .trim()); if (size == 1) { - pointCoord.size = CacheSize.NOT_CHOSEN; + pointCoord.setSize(CacheSize.NOT_CHOSEN); } else if (size == 2) { - pointCoord.size = CacheSize.MICRO; + pointCoord.setSize(CacheSize.MICRO); } else if (size == 3) { - pointCoord.size = CacheSize.REGULAR; + pointCoord.setSize(CacheSize.REGULAR); } else if (size == 4) { - pointCoord.size = CacheSize.LARGE; + pointCoord.setSize(CacheSize.LARGE); } else if (size == 5) { - pointCoord.size = CacheSize.VIRTUAL; + pointCoord.setSize(CacheSize.VIRTUAL); } else if (size == 6) { - pointCoord.size = CacheSize.OTHER; + pointCoord.setSize(CacheSize.OTHER); } else if (size == 8) { - pointCoord.size = CacheSize.SMALL; + pointCoord.setSize(CacheSize.SMALL); } else { - pointCoord.size = null; + pointCoord.setSize(null); } } - if (StringUtils.isNotBlank(pointCoord.geocode)) { - coords.put(pointCoord.geocode, pointCoord); + if (StringUtils.isNotBlank(pointCoord.getGeocode())) { + coords.put(pointCoord.getGeocode(), pointCoord); } } @@ -140,7 +137,7 @@ public final class LocParser extends FileParser { return coords; } - public static UUID parseLoc(File file, int listId, + public static cgSearch parseLoc(File file, int listId, Handler handler) { final cgSearch search = new cgSearch(); @@ -149,7 +146,7 @@ public final class LocParser extends FileParser { final cgCacheWrap caches = new cgCacheWrap(); for (Entry<String, cgCoord> entry : coords.entrySet()) { cgCoord coord = entry.getValue(); - if (StringUtils.isBlank(coord.geocode) || StringUtils.isBlank(coord.name)) { + if (StringUtils.isBlank(coord.getGeocode()) || StringUtils.isBlank(coord.getName())) { continue; } cgCache cache = new cgCache(); @@ -157,9 +154,9 @@ public final class LocParser extends FileParser { caches.cacheList.add(cache); fixCache(cache); - cache.type = CacheType.UNKNOWN.id; // type is not given in the LOC file - cache.reason = listId; - cache.detailed = true; + cache.setCacheType(CacheType.UNKNOWN); // type is not given in the LOC file + cache.setReason(listId); + cache.setDetailed(true); cgeoapplication.getInstance().addCacheToSearch(search, cache); } @@ -170,6 +167,6 @@ public final class LocParser extends FileParser { Log.e(Settings.tag, "LocParser.parseLoc: " + e.toString()); } - return search.getCurrentId(); + return search; } } diff --git a/main/src/cgeo/geocaching/filter/cgFilterBySize.java b/main/src/cgeo/geocaching/filter/cgFilterBySize.java index 1e9930c..dcb9875 100644 --- a/main/src/cgeo/geocaching/filter/cgFilterBySize.java +++ b/main/src/cgeo/geocaching/filter/cgFilterBySize.java @@ -14,7 +14,7 @@ public class cgFilterBySize extends cgFilter { @Override boolean applyFilter(cgCache cache) { - return this.size == cache.size; + return this.size == cache.getSize(); } @Override diff --git a/main/src/cgeo/geocaching/filter/cgFilterByType.java b/main/src/cgeo/geocaching/filter/cgFilterByType.java index c497777..6683988 100644 --- a/main/src/cgeo/geocaching/filter/cgFilterByType.java +++ b/main/src/cgeo/geocaching/filter/cgFilterByType.java @@ -14,7 +14,7 @@ public class cgFilterByType extends cgFilter { @Override boolean applyFilter(final cgCache cache) { - return cacheType.id.equals(cache.type); + return cacheType.id.equals(cache.getType()); } @Override diff --git a/main/src/cgeo/geocaching/geopoint/Geopoint.java b/main/src/cgeo/geocaching/geopoint/Geopoint.java index 8063d7b..07e3d38 100644 --- a/main/src/cgeo/geocaching/geopoint/Geopoint.java +++ b/main/src/cgeo/geocaching/geopoint/Geopoint.java @@ -71,7 +71,7 @@ public final class Geopoint /** * Creates new Geopoint with latitude and longitude parsed from strings. - * + * * @param latText * latitude string to parse * @param lonText @@ -267,7 +267,7 @@ public final class Geopoint /** * Returns formatted coordinates with default format. * Default format is decimalminutes, e.g. N 52° 36.123 E 010° 03.456 - * + * * @return formatted coordinates */ public String toString() diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index 840d7c9..f057fea 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -27,6 +27,7 @@ import cgeo.geocaching.maps.interfaces.MapFactory; import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnDragListener; import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl; +import cgeo.geocaching.utils.CancellableHandler; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; @@ -59,7 +60,6 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; -import java.util.UUID; /** * Class representing the Map in c:geo @@ -71,7 +71,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory private static final String EXTRAS_LATITUDE = "latitude"; private static final String EXTRAS_WPTTYPE = "wpttype"; private static final String EXTRAS_MAPSTATE = "mapstate"; - private static final String EXTRAS_SEARCHID = "searchid"; + private static final String EXTRAS_SEARCH = "search"; private static final String EXTRAS_DETAIL = "detail"; private static final int MENU_SELECT_MAPVIEW = 1; private static final int MENU_MAP_LIVE = 2; @@ -101,13 +101,13 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory private cgUpdateDir dirUpdate = new UpdateDir(); // from intent private boolean fromDetailIntent = false; - private String searchIdIntent = null; + private cgSearch searchIntent = null; private String geocodeIntent = null; private Geopoint coordsIntent = null; private WaypointType waypointTypeIntent = null; private int[] mapStateIntent = null; // status data - private UUID searchId = null; + private cgSearch search = null; private String token = null; private boolean noMapTokenShowed = false; // map status data @@ -189,7 +189,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory ActivityMixin.setTitle(activity, title.toString()); } else if (what == 1 && mapView != null) { - mapView.invalidate(); + mapView.repaintRequired(null); } } }; @@ -207,10 +207,11 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } } }; - final private Handler loadDetailsHandler = new Handler() { + + final private class LoadDetailsHandler extends CancellableHandler { @Override - public void handleMessage(Message msg) { + public void handleRegularMessage(Message msg) { if (msg.what == 0) { if (waitDialog != null) { int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); @@ -244,7 +245,22 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } } } - }; + + @Override + public void handleCancel(final Object extra) { + if (loadDetailsThread != null) { + loadDetailsThread.stopIt(); + } + + if (geo == null) { + geo = app.startGeo(activity, geoUpdate, base, 0, 0); + } + if (Settings.isUseCompass() && dir == null) { + dir = app.startDir(activity, dirUpdate); + } + } + } + final private Handler noMapTokenHandler = new Handler() { @Override @@ -322,7 +338,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory overlayScale = mapView.createAddScaleOverlay(activity); } - mapView.invalidate(); + mapView.repaintRequired(null); mapController = mapView.getMapController(); mapController.setZoom(Settings.getMapZoom()); @@ -339,7 +355,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory Bundle extras = activity.getIntent().getExtras(); if (extras != null) { fromDetailIntent = extras.getBoolean(EXTRAS_DETAIL); - searchIdIntent = extras.getString(EXTRAS_SEARCHID); + searchIntent = (cgSearch) extras.getParcelable(EXTRAS_SEARCH); geocodeIntent = extras.getString(EXTRAS_GEOCODE); final double latitudeIntent = extras.getDouble(EXTRAS_LATITUDE); final double longitudeIntent = extras.getDouble(EXTRAS_LONGITUDE); @@ -348,9 +364,6 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory mapStateIntent = extras.getIntArray(EXTRAS_MAPSTATE); mapTitle = extras.getString(EXTRAS_MAP_TITLE); - if ("".equals(searchIdIntent)) { - searchIdIntent = null; - } if (coordsIntent.getLatitude() == 0.0 || coordsIntent.getLongitude() == 0.0) { coordsIntent = null; } @@ -361,15 +374,15 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } // live map, if no arguments are given - live = (searchIdIntent == null && geocodeIntent == null && coordsIntent == null); + live = (searchIntent == null && geocodeIntent == null && coordsIntent == null); if (null == mapStateIntent) { followMyLocation = live; } else { followMyLocation = 1 == mapStateIntent[3] ? true : false; } - if (geocodeIntent != null || searchIdIntent != null || coordsIntent != null || mapStateIntent != null) { - centerMap(geocodeIntent, searchIdIntent, coordsIntent, mapStateIntent); + if (geocodeIntent != null || searchIntent != null || coordsIntent != null || mapStateIntent != null) { + centerMap(geocodeIntent, searchIntent, coordsIntent, mapStateIntent); } // prepare my location button @@ -551,7 +564,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory item.setTitle(res.getString(R.string.map_live_enable)); } - menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(searchId)); + menu.findItem(MENU_STORE_CACHES).setEnabled(live && !isLoading() && CollectionUtils.isNotEmpty(caches) && app.hasUnsavedCaches(search)); item = menu.findItem(MENU_CIRCLE_MODE); // show circles if (overlayCaches != null && overlayCaches.getCircles()) { @@ -584,8 +597,8 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory case MENU_MAP_LIVE: Settings.setLiveMap(!Settings.isLiveMap()); liveChanged = true; - searchId = null; - searchIdIntent = null; + search = null; + searchIntent = null; return true; case MENU_STORE_CACHES: if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { @@ -601,9 +614,9 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory final int mapSpanLon = mapView.getLongitudeSpan(); for (cgCache oneCache : cachesProtected) { - if (oneCache != null && oneCache.coords != null) { - if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.coords) && !app.isOffline(oneCache.geocode, null)) { - geocodes.add(oneCache.geocode); + if (oneCache != null && oneCache.getCoords() != null) { + if (cgBase.isCacheInViewPort(mapCenterLat, mapCenterLon, mapSpanLat, mapSpanLon, oneCache.getCoords()) && !app.isOffline(oneCache.getGeocode(), null)) { + geocodes.add(oneCache.getGeocode()); } } } @@ -621,9 +634,12 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory return true; } + final LoadDetailsHandler loadDetailsHandler = new LoadDetailsHandler(); + waitDialog = new ProgressDialog(activity); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); waitDialog.setCancelable(true); + waitDialog.setCancelMessage(loadDetailsHandler.cancelMessage()); waitDialog.setMax(detailTotal); waitDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @@ -667,16 +683,17 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } overlayCaches.switchCircles(); - mapView.invalidate(); + mapView.repaintRequired(overlayCaches); return true; - case MENU_AS_LIST: + case MENU_AS_LIST: { final cgSearch search = new cgSearch(); search.totalCnt = caches.size(); for (cgCache cache : caches) { - search.addGeocode(cache.geocode); + search.addGeocode(cache.getGeocode()); } cgeocaches.startActivityMap(activity, app.addSearch(search, caches, true, 0)); return true; + } default: if (SUBMENU_VIEW_GOOGLE_MAP <= id && SUBMENU_VIEW_MF_OFFLINE >= id) { item.setChecked(true); @@ -692,7 +709,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory Intent mapIntent = new Intent(activity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, fromDetailIntent); - mapIntent.putExtra(EXTRAS_SEARCHID, searchIdIntent); + mapIntent.putExtra(EXTRAS_SEARCH, searchIntent); mapIntent.putExtra(EXTRAS_GEOCODE, geocodeIntent); if (coordsIntent != null) { mapIntent.putExtra(EXTRAS_LATITUDE, coordsIntent.getLatitude()); @@ -713,9 +730,8 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } return true; - } - else { - NavigationAppFactory.onMenuItemSelected(item, geo, activity, res, caches != null && caches.size() > 0 ? caches.get(0) : null, searchId, null, coordsIntent); + } else { + NavigationAppFactory.onMenuItemSelected(item, geo, activity, res, caches != null && caches.size() > 0 ? caches.get(0) : null, search, null, coordsIntent); } break; } @@ -834,7 +850,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h overlayPosition.setHeading(dir.directionNow); - mapView.invalidate(); + mapView.repaintRequired(overlayPosition); } } } @@ -1118,17 +1134,17 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory // stage 1 - pull and render from the DB only - if (fromDetailIntent || StringUtils.isNotEmpty(searchIdIntent)) { - searchId = UUID.fromString(searchIdIntent); + if (fromDetailIntent || searchIntent != null) { + search = searchIntent; } else { if (!live || !Settings.isLiveMap()) { - searchId = app.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); + search = app.getStoredInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } else { - searchId = app.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); + search = app.getCachedInViewport(centerLat, centerLon, spanLat, spanLon, Settings.getCacheType()); } } - if (searchId != null) { + if (search != null) { downloaded = true; } @@ -1139,7 +1155,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory return; } - caches = app.getCaches(searchId, true); + caches = app.getCaches(search, true); //if in live map and stored caches are found / disables are also shown. if (live && Settings.isLiveMap()) { @@ -1148,7 +1164,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory for (int i = caches.size() - 1; i >= 0; i--) { cgCache cache = caches.get(i); - if ((cache.found && excludeMine) || (cache.own && excludeMine) || (cache.disabled && excludeDisabled)) { + if ((cache.isFound() && excludeMine) || (cache.isOwn() && excludeMine) || (cache.isDisabled() && excludeDisabled)) { caches.remove(i); } } @@ -1245,8 +1261,8 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory return; } - searchId = base.searchByViewport(token, latMin, latMax, lonMin, lonMax, 0); - if (searchId != null) { + search = base.searchByViewport(token, latMin, latMax, lonMin, lonMax, 0); + if (search != null) { downloaded = true; } @@ -1259,7 +1275,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory //TODO Portree Only overwrite if we got some. Otherwise maybe error icon //TODO Merge not to show locally found caches - caches = app.getCaches(searchId, centerLat, centerLon, spanLat, spanLon); + caches = app.getCaches(search, centerLat, centerLon, spanLat, spanLon); if (stop) { displayHandler.sendEmptyMessage(0); @@ -1317,25 +1333,25 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory return; } - if (cacheOne.coords == null) { + if (cacheOne.getCoords() == null) { continue; } // display cache waypoints - if (cacheOne.waypoints != null + if (cacheOne.getWaypoints() != null // Only show waypoints for single view or setting // when less than showWaypointsthreshold Caches shown && (cachesProtected.size() == 1 || (cachesProtected.size() < Settings.getWayPointsThreshold())) - && !cacheOne.waypoints.isEmpty()) { - for (cgWaypoint oneWaypoint : cacheOne.waypoints) { - if (oneWaypoint.coords == null) { + && !cacheOne.getWaypoints().isEmpty()) { + for (cgWaypoint oneWaypoint : cacheOne.getWaypoints()) { + if (oneWaypoint.getCoords() == null) { continue; } - items.add(getWaypointItem(new cgCoord(oneWaypoint), oneWaypoint.type)); + items.add(getWaypointItem(new cgCoord(oneWaypoint), oneWaypoint.getWaypointType())); } } - items.add(getCacheItem(new cgCoord(cacheOne), cacheOne.type, cacheOne.own, cacheOne.found, cacheOne.disabled)); + items.add(getCacheItem(new cgCoord(cacheOne), cacheOne.getType(), cacheOne.isOwn(), cacheOne.isFound(), cacheOne.isDisabled())); } overlayCaches.updateItems(items); @@ -1549,9 +1565,9 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory if (coordsIntent != null) { final cgCoord coord = new cgCoord(); - coord.type = "waypoint"; - coord.coords = coordsIntent; - coord.name = "some place"; + coord.setType("waypoint"); + coord.setCoords(coordsIntent); + coord.setName("some place"); coordinates.add(coord); final CachesOverlayItemImpl item = Settings.getMapFactory().getCachesOverlayItem(coord, null); @@ -1640,18 +1656,17 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory private class LoadDetails extends Thread { - private Handler handler = null; - private List<String> geocodes = null; - private volatile boolean stop = false; + final private CancellableHandler handler; + final private List<String> geocodes; private long last = 0L; - public LoadDetails(Handler handlerIn, List<String> geocodesIn) { - handler = handlerIn; - geocodes = geocodesIn; + public LoadDetails(final CancellableHandler handler, final List<String> geocodes) { + this.handler = handler; + this.geocodes = geocodes; } public void stopIt() { - stop = true; + handler.cancel(); } @Override @@ -1669,7 +1684,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory for (String geocode : geocodes) { try { - if (stop) { + if (handler.isCancelled()) { break; } @@ -1687,7 +1702,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } } - if (stop) { + if (handler.isCancelled()) { Log.i(Settings.tag, "Stopped storing process."); break; @@ -1703,6 +1718,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory handler.sendEmptyMessage(0); } + // FIXME: what does this yield() do here? yield(); last = System.currentTimeMillis(); @@ -1731,8 +1747,8 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } } - // move map to view results of searchIdIntent - private void centerMap(String geocodeCenter, String searchIdCenter, final Geopoint coordsCenter, int[] mapState) { + // move map to view results of searchIntent + private void centerMap(String geocodeCenter, final cgSearch searchCenter, final Geopoint coordsCenter, int[] mapState) { if (!centered && mapState != null) { try { @@ -1744,14 +1760,14 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory centered = true; alreadyCentered = true; - } else if (!centered && (geocodeCenter != null || searchIdIntent != null)) { + } else if (!centered && (geocodeCenter != null || searchIntent != null)) { try { List<Object> viewport = null; if (geocodeCenter != null) { viewport = app.getBounds(geocodeCenter); } else { - viewport = app.getBounds(UUID.fromString(searchIdCenter)); + viewport = app.getBounds(searchCenter); } if (viewport == null) { @@ -1851,11 +1867,13 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory } // close activity and open homescreen + @Override public void goHome(View view) { ActivityMixin.goHome(activity); } // open manual entry + @Override public void goManual(View view) { ActivityMixin.goManual(activity, "c:geo-live-map"); } @@ -1868,10 +1886,10 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory return imageView; } - public static void startActivitySearch(final Activity fromActivity, final UUID searchId, final String title, boolean detail) { + public static void startActivitySearch(final Activity fromActivity, final cgSearch search, final String title, boolean detail) { Intent mapIntent = new Intent(fromActivity, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, detail); - mapIntent.putExtra(EXTRAS_SEARCHID, searchId.toString()); + mapIntent.putExtra(EXTRAS_SEARCH, search); if (StringUtils.isNotBlank(title)) { mapIntent.putExtra(CGeoMap.EXTRAS_MAP_TITLE, title); } @@ -1882,7 +1900,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory context.startActivity(new Intent(context, Settings.getMapFactory().getMapClass())); } - public static void startActivityCoords(final Context context, final Geopoint coords, final WaypointType type) { + public static void startActivityCoords(final Context context, final Geopoint coords, final WaypointType type, final String title) { Intent mapIntent = new Intent(context, Settings.getMapFactory().getMapClass()); mapIntent.putExtra(EXTRAS_DETAIL, false); mapIntent.putExtra(EXTRAS_LATITUDE, coords.getLatitude()); @@ -1890,6 +1908,9 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory if (type != null) { mapIntent.putExtra(EXTRAS_WPTTYPE, type.id); } + if (StringUtils.isNotBlank(title)) { + mapIntent.putExtra(EXTRAS_MAP_TITLE, title); + } context.startActivity(mapIntent); } diff --git a/main/src/cgeo/geocaching/maps/CachesOverlay.java b/main/src/cgeo/geocaching/maps/CachesOverlay.java index 1a06ada..19f2bdc 100644 --- a/main/src/cgeo/geocaching/maps/CachesOverlay.java +++ b/main/src/cgeo/geocaching/maps/CachesOverlay.java @@ -11,7 +11,6 @@ import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.maps.interfaces.CachesOverlayItemImpl; -import cgeo.geocaching.maps.interfaces.GeneralOverlay; import cgeo.geocaching.maps.interfaces.GeoPointImpl; import cgeo.geocaching.maps.interfaces.ItemizedOverlayImpl; import cgeo.geocaching.maps.interfaces.MapFactory; @@ -39,7 +38,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOverlay { +public class CachesOverlay extends AbstractItemizedOverlay { private List<CachesOverlayItemImpl> items = new ArrayList<CachesOverlayItemImpl>(); private Context context = null; @@ -144,14 +143,14 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve final cgCoord itemCoord = item.getCoord(); float[] result = new float[1]; - Location.distanceBetween(itemCoord.coords.getLatitude(), itemCoord.coords.getLongitude(), - itemCoord.coords.getLatitude(), itemCoord.coords.getLongitude() + 1, result); + Location.distanceBetween(itemCoord.getCoords().getLatitude(), itemCoord.getCoords().getLongitude(), + itemCoord.getCoords().getLatitude(), itemCoord.getCoords().getLongitude() + 1, result); final float longitudeLineDistance = result[0]; - GeoPointImpl itemGeo = mapFactory.getGeoPointBase(itemCoord.coords); + GeoPointImpl itemGeo = mapFactory.getGeoPointBase(itemCoord.getCoords()); - final Geopoint leftCoords = new Geopoint(itemCoord.coords.getLatitude(), - itemCoord.coords.getLongitude() - 161 / longitudeLineDistance); + final Geopoint leftCoords = new Geopoint(itemCoord.getCoords().getLatitude(), + itemCoord.getCoords().getLongitude() - 161 / longitudeLineDistance); GeoPointImpl leftGeo = mapFactory.getGeoPointBase(leftCoords); projection.toPixels(itemGeo, center); @@ -213,18 +212,18 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve cgCoord coordinate = item.getCoord(); - if (StringUtils.isNotBlank(coordinate.type) && coordinate.type.equalsIgnoreCase("cache") && StringUtils.isNotBlank(coordinate.geocode)) { + if (StringUtils.isNotBlank(coordinate.getType()) && coordinate.getType().equalsIgnoreCase("cache") && StringUtils.isNotBlank(coordinate.getGeocode())) { Intent popupIntent = new Intent(context, cgeopopup.class); popupIntent.putExtra("fromdetail", fromDetail); - popupIntent.putExtra("geocode", coordinate.geocode); + popupIntent.putExtra("geocode", coordinate.getGeocode()); context.startActivity(popupIntent); - } else if (coordinate.type != null && coordinate.type.equalsIgnoreCase("waypoint") && coordinate.id != null && coordinate.id > 0) { + } else if (coordinate.getType() != null && coordinate.getType().equalsIgnoreCase("waypoint") && coordinate.getId() != null && coordinate.getId() > 0) { Intent popupIntent = new Intent(context, cgeowaypoint.class); - popupIntent.putExtra("waypoint", coordinate.id); - popupIntent.putExtra("geocode", coordinate.geocode); + popupIntent.putExtra("waypoint", coordinate.getId()); + popupIntent.putExtra("geocode", coordinate.getGeocode()); context.startActivity(popupIntent); } else { @@ -276,24 +275,24 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve AlertDialog.Builder dialog = new AlertDialog.Builder(context); dialog.setCancelable(true); - if (coordinate.type.equalsIgnoreCase("cache")) { + if (coordinate.getType().equalsIgnoreCase("cache")) { dialog.setTitle("cache"); String cacheType; - if (cgBase.cacheTypesInv.containsKey(coordinate.typeSpec)) { - cacheType = cgBase.cacheTypesInv.get(coordinate.typeSpec); + if (cgBase.cacheTypesInv.containsKey(coordinate.getTypeSpec())) { + cacheType = cgBase.cacheTypesInv.get(coordinate.getTypeSpec()); } else { cacheType = cgBase.cacheTypesInv.get(CacheType.MYSTERY.id); } - dialog.setMessage(Html.fromHtml(item.getTitle()) + "\n\ngeocode: " + coordinate.geocode.toUpperCase() + "\ntype: " + cacheType); + dialog.setMessage(Html.fromHtml(item.getTitle()) + "\n\ngeocode: " + coordinate.getGeocode().toUpperCase() + "\ntype: " + cacheType); if (fromDetail) { dialog.setPositiveButton("navigate", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { final Collection<cgCoord> coordinatesWithType = new ArrayList<cgCoord>(); coordinatesWithType.add(coordinate); - cgeonavigate.startActivity(context, coordinate.geocode.toUpperCase(), null, coordinate.coords, coordinatesWithType); + cgeonavigate.startActivity(context, coordinate.getGeocode().toUpperCase(), null, coordinate.getCoords(), coordinatesWithType); dialog.cancel(); } }); @@ -302,7 +301,7 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve public void onClick(DialogInterface dialog, int id) { Intent cachesIntent = new Intent(context, cgeodetail.class); - cachesIntent.putExtra("geocode", coordinate.geocode.toUpperCase()); + cachesIntent.putExtra("geocode", coordinate.getGeocode().toUpperCase()); context.startActivity(cachesIntent); dialog.cancel(); @@ -312,7 +311,7 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve } else { dialog.setTitle("waypoint"); - String waypointL10N = cgBase.waypointTypes.get(WaypointType.FIND_BY_ID.get(coordinate.typeSpec)); + String waypointL10N = cgBase.waypointTypes.get(WaypointType.FIND_BY_ID.get(coordinate.getTypeSpec())); if (waypointL10N == null) { waypointL10N = cgBase.waypointTypes.get(WaypointType.WAYPOINT); } @@ -323,7 +322,7 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve public void onClick(DialogInterface dialog, int id) { Collection<cgCoord> coordinatesWithType = new ArrayList<cgCoord>(); coordinatesWithType.add(coordinate); - cgeonavigate.startActivity(context, coordinate.name, null, coordinate.coords, coordinatesWithType); + cgeonavigate.startActivity(context, coordinate.getName(), null, coordinate.getCoords(), coordinatesWithType); dialog.cancel(); } }); diff --git a/main/src/cgeo/geocaching/maps/google/GoogleCacheOverlayItem.java b/main/src/cgeo/geocaching/maps/google/GoogleCacheOverlayItem.java index f138e90..2e6531f 100644 --- a/main/src/cgeo/geocaching/maps/google/GoogleCacheOverlayItem.java +++ b/main/src/cgeo/geocaching/maps/google/GoogleCacheOverlayItem.java @@ -11,7 +11,7 @@ public class GoogleCacheOverlayItem extends OverlayItem implements CachesOverlay private cgCoord coord; public GoogleCacheOverlayItem(cgCoord coordinate, String type) { - super(new GeoPoint(coordinate.coords.getLatitudeE6(), coordinate.coords.getLongitudeE6()), coordinate.name, ""); + super(new GeoPoint(coordinate.getCoords().getLatitudeE6(), coordinate.getCoords().getLongitudeE6()), coordinate.getName(), ""); this.cacheType = type; this.coord = coordinate; diff --git a/main/src/cgeo/geocaching/maps/interfaces/MapViewImpl.java b/main/src/cgeo/geocaching/maps/interfaces/MapViewImpl.java index 8231d92..1f4c304 100644 --- a/main/src/cgeo/geocaching/maps/interfaces/MapViewImpl.java +++ b/main/src/cgeo/geocaching/maps/interfaces/MapViewImpl.java @@ -18,8 +18,6 @@ import android.graphics.drawable.Drawable; */ public interface MapViewImpl { - void invalidate(); - void setBuiltInZoomControls(boolean b); void displayZoomControls(boolean b); @@ -61,6 +59,14 @@ public interface MapViewImpl { void setMapSource(); + /** + * Map-library unspecific method to request a repaint of either + * a specific overlay, that changed, or the mapview as a whole + * (if overlay is null) + * + * @param overlay + * Overlay to repaint or null if the mapview has changed + */ void repaintRequired(GeneralOverlay overlay); void setOnDragListener(OnDragListener onDragListener); diff --git a/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeCacheOverlayItem.java b/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeCacheOverlayItem.java index bb87941..c3d9d25 100644 --- a/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeCacheOverlayItem.java +++ b/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeCacheOverlayItem.java @@ -13,7 +13,7 @@ public class MapsforgeCacheOverlayItem extends OverlayItem implements CachesOver private cgCoord coord; public MapsforgeCacheOverlayItem(cgCoord coordinate, String type) { - super(new GeoPoint(coordinate.coords.getLatitudeE6(), coordinate.coords.getLongitudeE6()), coordinate.name, ""); + super(new GeoPoint(coordinate.getCoords().getLatitudeE6(), coordinate.getCoords().getLongitudeE6()), coordinate.getName(), ""); this.cacheType = type; this.coord = coordinate; diff --git a/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeMapView.java b/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeMapView.java index 2b24c0b..cfcdfb6 100644 --- a/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeMapView.java +++ b/main/src/cgeo/geocaching/maps/mapsforge/MapsforgeMapView.java @@ -188,15 +188,19 @@ public class MapsforgeMapView extends MapView implements MapViewImpl { @Override public void repaintRequired(GeneralOverlay overlay) { - try { - MapsforgeOverlay ovl = (MapsforgeOverlay) overlay.getOverlayImpl(); + if (null == overlay) { + invalidate(); + } else { + try { + Overlay ovl = (Overlay) overlay.getOverlayImpl(); + + if (ovl != null) { + ovl.requestRedraw(); + } - if (ovl != null) { - ovl.requestRedraw(); + } catch (Exception e) { + Log.e(Settings.tag, "mfMapView.repaintRequired: " + e.toString()); } - - } catch (Exception e) { - Log.e(Settings.tag, "mfMapView.repaintRequired: " + e.toString()); } } diff --git a/main/src/cgeo/geocaching/cgHtmlImg.java b/main/src/cgeo/geocaching/network/HtmlImage.java index f264c51..4e996e3 100644 --- a/main/src/cgeo/geocaching/cgHtmlImg.java +++ b/main/src/cgeo/geocaching/network/HtmlImage.java @@ -1,5 +1,8 @@ -package cgeo.geocaching; +package cgeo.geocaching.network; +import cgeo.geocaching.R; +import cgeo.geocaching.Settings; +import cgeo.geocaching.cgBase; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; @@ -7,7 +10,6 @@ import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.entity.BufferedHttpEntity; -import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; @@ -20,10 +22,9 @@ import android.view.Display; import android.view.WindowManager; import java.io.File; -import java.io.InputStream; import java.util.Date; -public class cgHtmlImg implements Html.ImageGetter { +public class HtmlImage implements Html.ImageGetter { private static final String[] BLOCKED = new String[] { "gccounter.de", @@ -36,33 +37,35 @@ public class cgHtmlImg implements Html.ImageGetter { }; final private Context context; final private String geocode; - final private boolean placement; + /** + * on error: return large error image, if <code>true</code>, otherwise empty 1x1 image + */ + final private boolean returnErrorImage; final private int reason; final private boolean onlySave; final private boolean save; final private BitmapFactory.Options bfOptions; - final private Display display; final private int maxWidth; final private int maxHeight; - public cgHtmlImg(Activity activityIn, String geocodeIn, boolean placementIn, int reasonIn, boolean onlySaveIn) { - this(activityIn, geocodeIn, placementIn, reasonIn, onlySaveIn, true); + public HtmlImage(final Context context, final String geocode, final boolean returnErrorImage, final int reason, final boolean onlySave) { + this(context, geocode, returnErrorImage, reason, onlySave, true); } - public cgHtmlImg(Context contextIn, String geocodeIn, boolean placementIn, int reasonIn, boolean onlySaveIn, boolean saveIn) { - context = contextIn; - geocode = geocodeIn; - placement = placementIn; - reason = reasonIn; - onlySave = onlySaveIn; - save = saveIn; + public HtmlImage(final Context contextIn, final String geocode, final boolean returnErrorImage, final int reason, final boolean onlySave, final boolean save) { + this.context = contextIn; + this.geocode = geocode; + this.returnErrorImage = returnErrorImage; + this.reason = reason; + this.onlySave = onlySave; + this.save = save; bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; - display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - maxWidth = display.getWidth() - 25; - maxHeight = display.getHeight() - 25; + final Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); + this.maxWidth = display.getWidth() - 25; + this.maxHeight = display.getHeight() - 25; } @Override @@ -72,21 +75,11 @@ public class cgHtmlImg implements Html.ImageGetter { return null; } - final File file = LocalStorage.getStorageFile(geocode, url, true); - final File fileSec = LocalStorage.getStorageSecFile(geocode, url, true); - Bitmap imagePre = null; // Load image from cache if (!onlySave) { - try { - imagePre = loadCachedImage(file); - if (imagePre == null) { - imagePre = loadCachedImage(fileSec); - } - } catch (Exception e) { - Log.w(Settings.tag, "cgHtmlImg.getDrawable (reading cache): " + e.toString()); - } + imagePre = loadImageFromStorage(url); } // Download image and save it to the cache @@ -99,13 +92,6 @@ public class cgHtmlImg implements Html.ImageGetter { final HttpResponse httpResponse = cgBase.request(absoluteURL, null, false); if (httpResponse != null) { bufferedEntity = new BufferedHttpEntity(httpResponse.getEntity()); - setSampleSize(bufferedEntity.getContentLength()); - final InputStream is = bufferedEntity.getContent(); - try { - imagePre = BitmapFactory.decodeStream(is, null, bfOptions); - } finally { - is.close(); - } } } catch (Exception e) { Log.e(Settings.tag, "cgHtmlImg.getDrawable (downloading from web)", e); @@ -113,6 +99,7 @@ public class cgHtmlImg implements Html.ImageGetter { } if (save) { + final File file = LocalStorage.getStorageFile(geocode, url, true); LocalStorage.saveEntityToFile(bufferedEntity, file); } } @@ -121,11 +108,16 @@ public class cgHtmlImg implements Html.ImageGetter { return null; } + // now load the newly downloaded image + if (imagePre == null) { + imagePre = loadImageFromStorage(url); + } + // get image and return if (imagePre == null) { Log.d(Settings.tag, "cgHtmlImg.getDrawable: Failed to obtain image"); - if (placement) { + if (returnErrorImage) { imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_not_loaded); } else { imagePre = BitmapFactory.decodeResource(context.getResources(), R.drawable.image_no_placement); @@ -139,13 +131,7 @@ public class cgHtmlImg implements Html.ImageGetter { int height; if (imgWidth > maxWidth || imgHeight > maxHeight) { - double ratio; - if ((maxWidth / imgWidth) > (maxHeight / imgHeight)) { - ratio = (double) maxHeight / (double) imgHeight; - } else { - ratio = (double) maxWidth / (double) imgWidth; - } - + final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); @@ -166,6 +152,21 @@ public class cgHtmlImg implements Html.ImageGetter { return image; } + private Bitmap loadImageFromStorage(final String url) { + try { + final File file = LocalStorage.getStorageFile(geocode, url, true); + final Bitmap image = loadCachedImage(file); + if (image != null) { + return image; + } + final File fileSec = LocalStorage.getStorageSecFile(geocode, url, true); + return loadCachedImage(fileSec); + } catch (Exception e) { + Log.w(Settings.tag, "cgHtmlImg.getDrawable (reading cache): " + e.toString()); + } + return null; + } + private final String makeAbsoluteURL(final String url) { try { // Check if uri is absolute or not, if not attach the connector hostname @@ -173,7 +174,7 @@ public class cgHtmlImg implements Html.ImageGetter { if (Uri.parse(url).isAbsolute()) { return url; } else { - String host = ConnectorFactory.getConnector(geocode).getHost(); + final String host = ConnectorFactory.getConnector(geocode).getHost(); if (StringUtils.isNotEmpty(host)) { return "http://" + host + url; } diff --git a/main/src/cgeo/geocaching/sorting/DateComparator.java b/main/src/cgeo/geocaching/sorting/DateComparator.java index b59e84e..7c8f7ed 100644 --- a/main/src/cgeo/geocaching/sorting/DateComparator.java +++ b/main/src/cgeo/geocaching/sorting/DateComparator.java @@ -19,8 +19,8 @@ public class DateComparator extends AbstractCacheComparator { @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - Date date1 = cache1.hidden; - Date date2 = cache2.hidden; + Date date1 = cache1.getHidden(); + Date date2 = cache2.getHidden(); if (date1 != null && date2 != null) { return date1.compareTo(date2); } diff --git a/main/src/cgeo/geocaching/sorting/DifficultyComparator.java b/main/src/cgeo/geocaching/sorting/DifficultyComparator.java index 846417c..c044598 100644 --- a/main/src/cgeo/geocaching/sorting/DifficultyComparator.java +++ b/main/src/cgeo/geocaching/sorting/DifficultyComparator.java @@ -10,14 +10,14 @@ public class DifficultyComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.difficulty != null && cache2.difficulty != null; + return cache1.getDifficulty() != null && cache2.getDifficulty() != null; } @Override protected int compareCaches(final cgCache cache1, final cgCache cache2) { - if (cache1.difficulty > cache2.difficulty) { + if (cache1.getDifficulty() > cache2.getDifficulty()) { return 1; - } else if (cache2.difficulty > cache1.difficulty) { + } else if (cache2.getDifficulty() > cache1.getDifficulty()) { return -1; } return 0; diff --git a/main/src/cgeo/geocaching/sorting/DistanceComparator.java b/main/src/cgeo/geocaching/sorting/DistanceComparator.java index 7051718..920d965 100644 --- a/main/src/cgeo/geocaching/sorting/DistanceComparator.java +++ b/main/src/cgeo/geocaching/sorting/DistanceComparator.java @@ -21,19 +21,19 @@ public class DistanceComparator extends AbstractCacheComparator { @Override protected int compareCaches(final cgCache cache1, final cgCache cache2) { - if ((cache1.coords == null || cache2.coords == null) - && cache1.distance != null && cache2.distance != null) { - return Double.compare(cache1.distance, cache2.distance); + if ((cache1.getCoords() == null || cache2.getCoords() == null) + && cache1.getDistance() != null && cache2.getDistance() != null) { + return Double.compare(cache1.getDistance(), cache2.getDistance()); } else { - if (cache1.coords == null) { + if (cache1.getCoords() == null) { return 1; } - if (cache2.coords == null) { + if (cache2.getCoords() == null) { return -1; } - return Float.compare(coords.distanceTo(cache1.coords), - coords.distanceTo(cache2.coords)); + return Float.compare(coords.distanceTo(cache1.getCoords()), + coords.distanceTo(cache2.getCoords())); } } diff --git a/main/src/cgeo/geocaching/sorting/FindsComparator.java b/main/src/cgeo/geocaching/sorting/FindsComparator.java index efde22d..2591102 100644 --- a/main/src/cgeo/geocaching/sorting/FindsComparator.java +++ b/main/src/cgeo/geocaching/sorting/FindsComparator.java @@ -15,7 +15,7 @@ public class FindsComparator extends AbstractCacheComparator implements @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.logCounts != null && cache2.logCounts != null; + return cache1.getLogCounts() != null && cache2.getLogCounts() != null; } @Override @@ -27,10 +27,10 @@ public class FindsComparator extends AbstractCacheComparator implements private int getFindsCount(cgCache cache) { int finds = 0; - if (cache.logCounts.isEmpty()) { - cache.logCounts = app.loadLogCounts(cache.geocode); + if (cache.getLogCounts().isEmpty()) { + cache.setLogCounts(app.loadLogCounts(cache.getGeocode())); } - Integer logged = cache.logCounts.get(cgBase.LOG_FOUND_IT); + Integer logged = cache.getLogCounts().get(cgBase.LOG_FOUND_IT); if (logged != null) { finds = logged; } diff --git a/main/src/cgeo/geocaching/sorting/GeocodeComparator.java b/main/src/cgeo/geocaching/sorting/GeocodeComparator.java index 136d7f5..1377cce 100644 --- a/main/src/cgeo/geocaching/sorting/GeocodeComparator.java +++ b/main/src/cgeo/geocaching/sorting/GeocodeComparator.java @@ -12,17 +12,17 @@ public class GeocodeComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return StringUtils.isNotBlank(cache1.geocode) - && StringUtils.isNotBlank(cache2.geocode); + return StringUtils.isNotBlank(cache1.getGeocode()) + && StringUtils.isNotBlank(cache2.getGeocode()); } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.geocode.length() > cache2.geocode.length()) { + if (cache1.getGeocode().length() > cache2.getGeocode().length()) { return 1; - } else if (cache2.geocode.length() > cache1.geocode.length()) { + } else if (cache2.getGeocode().length() > cache1.getGeocode().length()) { return -1; } - return cache1.geocode.compareToIgnoreCase(cache2.geocode); + return cache1.getGeocode().compareToIgnoreCase(cache2.getGeocode()); } } diff --git a/main/src/cgeo/geocaching/sorting/InventoryComparator.java b/main/src/cgeo/geocaching/sorting/InventoryComparator.java index 0833094..b1842d7 100644 --- a/main/src/cgeo/geocaching/sorting/InventoryComparator.java +++ b/main/src/cgeo/geocaching/sorting/InventoryComparator.java @@ -17,8 +17,8 @@ public class InventoryComparator extends AbstractCacheComparator { @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - int itemCount1 = cache1.inventoryItems; - int itemCount2 = cache2.inventoryItems; + int itemCount1 = cache1.getInventoryItems(); + int itemCount2 = cache2.getInventoryItems(); if (itemCount1 < itemCount2) { return 1; } else if (itemCount2 < itemCount1) { diff --git a/main/src/cgeo/geocaching/sorting/NameComparator.java b/main/src/cgeo/geocaching/sorting/NameComparator.java index bfc05c0..c32bc48 100644 --- a/main/src/cgeo/geocaching/sorting/NameComparator.java +++ b/main/src/cgeo/geocaching/sorting/NameComparator.java @@ -12,7 +12,7 @@ public class NameComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return StringUtils.isNotBlank(cache1.name) && StringUtils.isNotBlank(cache2.name); + return StringUtils.isNotBlank(cache1.getName()) && StringUtils.isNotBlank(cache2.getName()); } @Override diff --git a/main/src/cgeo/geocaching/sorting/PopularityComparator.java b/main/src/cgeo/geocaching/sorting/PopularityComparator.java index dbc418a..5d3507c 100644 --- a/main/src/cgeo/geocaching/sorting/PopularityComparator.java +++ b/main/src/cgeo/geocaching/sorting/PopularityComparator.java @@ -10,14 +10,14 @@ public class PopularityComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.favouriteCnt != null && cache2.favouriteCnt != null; + return cache1.getFavouriteCnt() != null && cache2.getFavouriteCnt() != null; } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.favouriteCnt < cache2.favouriteCnt) { + if (cache1.getFavouriteCnt() < cache2.getFavouriteCnt()) { return 1; - } else if (cache2.favouriteCnt < cache1.favouriteCnt) { + } else if (cache2.getFavouriteCnt() < cache1.getFavouriteCnt()) { return -1; } return 0; diff --git a/main/src/cgeo/geocaching/sorting/RatingComparator.java b/main/src/cgeo/geocaching/sorting/RatingComparator.java index b7140c6..3c0fc02 100644 --- a/main/src/cgeo/geocaching/sorting/RatingComparator.java +++ b/main/src/cgeo/geocaching/sorting/RatingComparator.java @@ -10,13 +10,13 @@ public class RatingComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.rating != null && cache2.rating != null; + return cache1.getRating() != null && cache2.getRating() != null; } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - Float rating1 = cache1.rating; - Float rating2 = cache2.rating; + Float rating1 = cache1.getRating(); + Float rating2 = cache2.getRating(); // voting can be disabled for caches, then assume an average rating instead if (rating1 == 0.0) { diff --git a/main/src/cgeo/geocaching/sorting/SizeComparator.java b/main/src/cgeo/geocaching/sorting/SizeComparator.java index a633a06..f946522 100644 --- a/main/src/cgeo/geocaching/sorting/SizeComparator.java +++ b/main/src/cgeo/geocaching/sorting/SizeComparator.java @@ -10,11 +10,11 @@ public class SizeComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.size != null && cache2.size != null; + return cache1.getSize() != null && cache2.getSize() != null; } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - return cache2.size.comparable - cache1.size.comparable; + return cache2.getSize().comparable - cache1.getSize().comparable; } }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/sorting/StateComparator.java b/main/src/cgeo/geocaching/sorting/StateComparator.java index f56d3fe..30d385c 100644 --- a/main/src/cgeo/geocaching/sorting/StateComparator.java +++ b/main/src/cgeo/geocaching/sorting/StateComparator.java @@ -20,10 +20,10 @@ public class StateComparator extends AbstractCacheComparator implements } private static int getState(final cgCache cache) { - if (cache.disabled) { + if (cache.isDisabled()) { return 1; } - if (cache.archived) { + if (cache.isArchived()) { return 2; } return 0; diff --git a/main/src/cgeo/geocaching/sorting/TerrainComparator.java b/main/src/cgeo/geocaching/sorting/TerrainComparator.java index 88c75e4..2da5971 100644 --- a/main/src/cgeo/geocaching/sorting/TerrainComparator.java +++ b/main/src/cgeo/geocaching/sorting/TerrainComparator.java @@ -10,14 +10,14 @@ public class TerrainComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.terrain != null && cache2.terrain != null; + return cache1.getTerrain() != null && cache2.getTerrain() != null; } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.terrain > cache2.terrain) { + if (cache1.getTerrain() > cache2.getTerrain()) { return 1; - } else if (cache2.terrain > cache1.terrain) { + } else if (cache2.getTerrain() > cache1.getTerrain()) { return -1; } return 0; diff --git a/main/src/cgeo/geocaching/sorting/VisitComparator.java b/main/src/cgeo/geocaching/sorting/VisitComparator.java index 597efb5..ba5e07f 100644 --- a/main/src/cgeo/geocaching/sorting/VisitComparator.java +++ b/main/src/cgeo/geocaching/sorting/VisitComparator.java @@ -10,15 +10,15 @@ public class VisitComparator extends AbstractCacheComparator { @Override protected boolean canCompare(cgCache cache1, cgCache cache2) { - return cache1.visitedDate != null && cache1.visitedDate > 0 - && cache2.visitedDate != null && cache2.visitedDate > 0; + return cache1.getVisitedDate() != null && cache1.getVisitedDate() > 0 + && cache2.getVisitedDate() != null && cache2.getVisitedDate() > 0; } @Override protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.visitedDate > cache2.visitedDate) { + if (cache1.getVisitedDate() > cache2.getVisitedDate()) { return -1; - } else if (cache1.visitedDate < cache2.visitedDate) { + } else if (cache1.getVisitedDate() < cache2.getVisitedDate()) { return 1; } return 0; diff --git a/main/src/cgeo/geocaching/sorting/VoteComparator.java b/main/src/cgeo/geocaching/sorting/VoteComparator.java index 2a4b4ac..2145361 100644 --- a/main/src/cgeo/geocaching/sorting/VoteComparator.java +++ b/main/src/cgeo/geocaching/sorting/VoteComparator.java @@ -19,13 +19,13 @@ public class VoteComparator extends AbstractCacheComparator { protected int compareCaches(cgCache cache1, cgCache cache2) { // if there is no vote available, put that cache at the end of the list float vote1 = 0; - if (cache1.myVote != null) { - vote1 = cache1.myVote; + if (cache1.getMyVote() != null) { + vote1 = cache1.getMyVote(); } float vote2 = 0; - if (cache2.myVote != null) { - vote2 = cache2.myVote; + if (cache2.getMyVote() != null) { + vote2 = cache2.getMyVote(); } // compare diff --git a/main/src/cgeo/geocaching/utils/CancellableHandler.java b/main/src/cgeo/geocaching/utils/CancellableHandler.java new file mode 100644 index 0000000..0b490d8 --- /dev/null +++ b/main/src/cgeo/geocaching/utils/CancellableHandler.java @@ -0,0 +1,112 @@ +package cgeo.geocaching.utils; + +import android.os.Handler; +import android.os.Message; + +/** + * Handler with a cancel policy. Once cancelled, the handler will not handle + * any more cancel or regular message. + */ +public abstract class CancellableHandler extends Handler { + + private boolean cancelled = false; + + private static class CancelHolder { + final Object payload; + + CancelHolder(final Object payload) { + this.payload = payload; + } + } + + @Override + final public void handleMessage(final Message message) { + if (cancelled) { + return; + } + + if (message.obj instanceof CancelHolder) { + cancelled = true; + handleCancel(((CancelHolder) message.obj).payload); + } else { + handleRegularMessage(message); + } + } + + /** + * Handle a non-cancel message.<br> + * Subclasses must implement this to handle messages. + * + * @param message + * the message to handle + */ + abstract protected void handleRegularMessage(final Message message); + + /** + * Handle a cancel message. + * + * @param extra + * the additional payload given by the canceller + */ + protected void handleCancel(final Object extra) { + } + + /** + * Get a cancel message that can later be sent to this handler to cancel it. + * + * @return a cancel message + */ + public Message cancelMessage() { + return cancelMessage(null); + } + + /** + * Get a cancel message with an additional parameter that can later be sent to + * this handler to cancel it. + * + * @param extra + * the extra parameter to give to the cancel handler + * @return a cancel message + */ + public Message cancelMessage(final Object extra) { + return this.obtainMessage(0, new CancelHolder(extra)); + } + + /** + * Cancel the current handler. This can be called from any thread. + */ + public void cancel() { + cancel(null); + } + + /** + * Cancel the current handler. This can be called from any thread. + * + * @param extra + * the extra parameter to give to the cancel handler + */ + public void cancel(final Object extra) { + cancelMessage(extra).sendToTarget(); + } + + /** + * Check if the current handler has been cancelled. + * + * @return true if the handler has been cancelled + */ + public boolean isCancelled() { + return cancelled; + } + + /** + * Check if a handler has been cancelled. + * + * @param handler + * a handler, or null + * @return true if the handler is not null and has been cancelled + */ + public static boolean isCancelled(final CancellableHandler handler) { + return handler != null && handler.isCancelled(); + } + +} diff --git a/main/src/cgeo/geocaching/utils/StopWatch.java b/main/src/cgeo/geocaching/utils/StopWatch.java new file mode 100644 index 0000000..bd53e14 --- /dev/null +++ b/main/src/cgeo/geocaching/utils/StopWatch.java @@ -0,0 +1,38 @@ +/** +* +*/ +package cgeo.geocaching.utils; + + +/** + * Stop watch + * + * @author blafoo + */ +public final class StopWatch { + + private long start; + + public StopWatch() { + reset(); + } + + public void reset() { + start = System.currentTimeMillis(); + } + + /** + * @return difference in ms from the start to "now" + */ + public String getTimeAsString() { + return String.format("%d ms", getTime()); + } + + /** + * @return difference in ms from the start to "now" + */ + public long getTime() { + return System.currentTimeMillis() - start; + } + +}
\ No newline at end of file diff --git a/tests/project.properties b/tests/project.properties new file mode 100644 index 0000000..b00386b --- /dev/null +++ b/tests/project.properties @@ -0,0 +1,11 @@ +# This file is automatically generated by Android Tools. +# Do not modify this file -- YOUR CHANGES WILL BE ERASED! +# +# This file must be checked in Version Control Systems. +# +# To customize properties used by the Ant build system use, +# "ant.properties", and override values to adapt the script to your +# project structure. + +# Project target. +target=Google Inc.:Google APIs:8 diff --git a/tests/src/cgeo/geocaching/ParserTest.java b/tests/src/cgeo/geocaching/ParserTest.java index 1f61554..ca4a171 100644 --- a/tests/src/cgeo/geocaching/ParserTest.java +++ b/tests/src/cgeo/geocaching/ParserTest.java @@ -18,6 +18,6 @@ public class ParserTest extends InstrumentationTestCase { cgCacheWrap caches = cgBase.parseCacheFromText(getFileContent(R.raw.gc1zxez), 0, null); assertEquals(1, caches.cacheList.size()); final cgCache cache = caches.cacheList.get(0); - assertEquals("Ms.Marple/Mr.Stringer", cache.ownerReal); + assertEquals("Ms.Marple/Mr.Stringer", cache.getOwnerReal()); } }
\ No newline at end of file diff --git a/tests/src/cgeo/geocaching/activity/ProgressTest.java b/tests/src/cgeo/geocaching/activity/ProgressTest.java index 5df5272..1910885 100644 --- a/tests/src/cgeo/geocaching/activity/ProgressTest.java +++ b/tests/src/cgeo/geocaching/activity/ProgressTest.java @@ -14,7 +14,7 @@ public class ProgressTest extends ActivityInstrumentationTestCase2<cgeo> { assertFalse(progress.isShowing()); // nothing shown initially - progress.show(getActivity(), "Title", "Message", true, false); + progress.show(getActivity(), "Title", "Message", true, null); assertTrue(progress.isShowing()); progress.setMessage("Test"); diff --git a/tests/src/cgeo/geocaching/cgWaypointTest.java b/tests/src/cgeo/geocaching/cgWaypointTest.java index 84f8f9d..241b349 100644 --- a/tests/src/cgeo/geocaching/cgWaypointTest.java +++ b/tests/src/cgeo/geocaching/cgWaypointTest.java @@ -8,22 +8,22 @@ public class cgWaypointTest extends AndroidTestCase { public static void testOrder() { final cgWaypoint cache = new cgWaypoint(); - cache.type = WaypointType.FINAL; + cache.setWaypointType(WaypointType.FINAL); final cgWaypoint trailhead = new cgWaypoint(); - trailhead.type = WaypointType.TRAILHEAD; + trailhead.setWaypointType(WaypointType.TRAILHEAD); final cgWaypoint stage = new cgWaypoint(); - stage.type = WaypointType.STAGE; + stage.setWaypointType(WaypointType.STAGE); final cgWaypoint puzzle = new cgWaypoint(); - puzzle.type = WaypointType.PUZZLE; + puzzle.setWaypointType(WaypointType.PUZZLE); final cgWaypoint own = new cgWaypoint(); - own.type = WaypointType.OWN; + own.setWaypointType(WaypointType.OWN); final cgWaypoint parking = new cgWaypoint(); - parking.type = WaypointType.PARKING; + parking.setWaypointType(WaypointType.PARKING); assertTrue(trailhead.compareTo(puzzle) < 0); assertTrue(trailhead.compareTo(stage) < 0); diff --git a/tests/src/cgeo/geocaching/cgeoApplicationTest.java b/tests/src/cgeo/geocaching/cgeoApplicationTest.java index 20743f1..3dcf2e3 100644 --- a/tests/src/cgeo/geocaching/cgeoApplicationTest.java +++ b/tests/src/cgeo/geocaching/cgeoApplicationTest.java @@ -9,7 +9,6 @@ import android.test.suitebuilder.annotation.SmallTest; import java.util.Date; import java.util.HashMap; -import java.util.UUID; import junit.framework.Assert; @@ -54,8 +53,8 @@ public class cgeoApplicationTest extends ApplicationTestCase<cgeoapplication> { */ @MediumTest public void testSearchByGeocode() { - final UUID id = base.searchByGeocode("GC1RMM2", null, 0, true, null); - Assert.assertNotNull(id); + final cgSearch search = base.searchByGeocode("GC1RMM2", null, 0, true, null); + Assert.assertNotNull(search); } /** @@ -68,7 +67,7 @@ public class cgeoApplicationTest extends ApplicationTestCase<cgeoapplication> { cgCacheWrap caches = cgBase.parseCacheFromText(cache.getData(), 0, null); cgCache cacheParsed = caches.cacheList.get(0); Assert.assertEquals(cache.getGeocode(), cacheParsed.getGeocode()); - Assert.assertEquals(cache.getType(), cacheParsed.getType()); + Assert.assertEquals(cache.getCacheType(), cacheParsed.getCacheType()); Assert.assertEquals(cache.getOwner(), cacheParsed.getOwner()); Assert.assertEquals(cache.getDifficulty(), cacheParsed.getDifficulty()); Assert.assertEquals(cache.getTerrain(), cacheParsed.getTerrain()); @@ -118,22 +117,25 @@ public class cgeoApplicationTest extends ApplicationTestCase<cgeoapplication> { public void testSearchTrackable() { cgTrackable tb = base.searchTrackable("TB2J1VZ", null, null); + // fix data assertEquals("aefffb86-099f-444f-b132-605436163aa8", tb.getGuid()); assertEquals("TB2J1VZ", tb.getGeocode()); assertEquals("http://www.geocaching.com/images/wpttypes/21.gif", tb.getIconUrl()); assertEquals("blafoo's Children Music CD", tb.getName()); assertEquals("Travel Bug Dog Tag", tb.getType()); assertEquals(new Date(2009 - 1900, 8 - 1, 24), tb.getReleased()); - assertEquals(10617.8f, tb.getDistance()); assertEquals("Niedersachsen, Germany", tb.getOrigin()); assertEquals("blafoo", tb.getOwner()); assertEquals("0564a940-8311-40ee-8e76-7e91b2cf6284", tb.getOwnerGuid()); - assertEquals("Nice place for a break cache", tb.getSpottedName()); - assertEquals(cgTrackable.SPOTTED_CACHE, tb.getSpottedType()); - assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); assertEquals("Kinder erfreuen.<br/><br/>Make children happy.", tb.getGoal()); assertTrue(tb.getDetails().startsWith("Auf der CD sind")); assertEquals("http://img.geocaching.com/track/display/38382780-87a7-4393-8393-78841678ee8c.jpg", tb.getImage()); - assertEquals(10, tb.getLogs().size()); + // changing data + assertTrue(tb.getDistance() >= 10617.8f); + assertTrue(tb.getLogs().size() >= 10); + assertTrue(cgTrackable.SPOTTED_CACHE == tb.getSpottedType() || cgTrackable.SPOTTED_OWNER == tb.getSpottedType()); + // no assumption possible: assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); + // no assumption possible: assertEquals("Nice place for a break cache", tb.getSpottedName()); + } } diff --git a/tests/src/cgeo/geocaching/files/GPXParserTest.java b/tests/src/cgeo/geocaching/files/GPXParserTest.java index 8a229ef..bc795e2 100644 --- a/tests/src/cgeo/geocaching/files/GPXParserTest.java +++ b/tests/src/cgeo/geocaching/files/GPXParserTest.java @@ -35,43 +35,43 @@ public class GPXParserTest extends InstrumentationTestCase { assertNotNull(caches); assertEquals(1, caches.size()); final cgCache cache = caches.get(0); - assertEquals("GC1BKP3", cache.geocode); - assertEquals("9946f030-a514-46d8-a050-a60e92fd2e1a", cache.guid); - assertEquals(CacheType.TRADITIONAL.id, cache.type); - assertEquals(false, cache.archived); - assertEquals(false, cache.disabled); - assertEquals("Die Schatzinsel / treasure island", cache.name); - assertEquals("Die unbesiegbaren Geo - Geparden", cache.owner); - assertEquals(CacheSize.MICRO, cache.size); - assertEquals(1.0f, cache.difficulty.floatValue()); - assertEquals(5.0f, cache.terrain.floatValue()); - assertEquals("Baden-Württemberg, Germany", cache.location); - assertEquals("Ein alter Kindheitstraum, ein Schatz auf einer unbewohnten Insel.\nA old dream of my childhood, a treasure on a lonely island.", cache.shortdesc); - assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(cache.coords)); + assertEquals("GC1BKP3", cache.getGeocode()); + assertEquals("9946f030-a514-46d8-a050-a60e92fd2e1a", cache.getGuid()); + assertEquals(CacheType.TRADITIONAL.id, cache.getType()); + assertEquals(false, cache.isArchived()); + assertEquals(false, cache.isDisabled()); + assertEquals("Die Schatzinsel / treasure island", cache.getName()); + assertEquals("Die unbesiegbaren Geo - Geparden", cache.getOwner()); + assertEquals(CacheSize.MICRO, cache.getSize()); + assertEquals(1.0f, cache.getDifficulty().floatValue()); + assertEquals(5.0f, cache.getTerrain().floatValue()); + assertEquals("Baden-Württemberg, Germany", cache.getLocation()); + assertEquals("Ein alter Kindheitstraum, ein Schatz auf einer unbewohnten Insel.\nA old dream of my childhood, a treasure on a lonely island.", cache.getShortdesc()); + assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(cache.getCoords())); return cache; } public void testGPXVersion101() throws IOException { final cgCache cache = testGPXVersion(R.raw.gc1bkp3_gpx101); - assertNotNull(cache.attributes); - assertEquals(10, cache.attributes.size()); + assertNotNull(cache.getAttributes()); + assertEquals(10, cache.getAttributes().size()); } public void testOC() throws IOException { final List<cgCache> caches = readGPX(R.raw.oc5952_gpx); final cgCache cache = caches.get(0); - assertEquals("OC5952", cache.geocode); - assertEquals(CacheType.TRADITIONAL.id, cache.type); - assertEquals(false, cache.archived); - assertEquals(false, cache.disabled); - assertEquals("Die Schatzinsel / treasure island", cache.name); - assertEquals("Die unbesiegbaren Geo - Geparden", cache.owner); - assertEquals(CacheSize.SMALL, cache.size); - assertEquals(1.0f, cache.difficulty.floatValue()); - assertEquals(4.0f, cache.terrain.floatValue()); - assertEquals("Baden-Württemberg, Germany", cache.location); - assertEquals("Ein alter Kindheitstraum, ein Schatz auf einer unbewohnten Insel. A old dream of my childhood, a treasure on a lonely is", cache.shortdesc); - assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(cache.coords)); + assertEquals("OC5952", cache.getGeocode()); + assertEquals(CacheType.TRADITIONAL.id, cache.getType()); + assertEquals(false, cache.isArchived()); + assertEquals(false, cache.isDisabled()); + assertEquals("Die Schatzinsel / treasure island", cache.getName()); + assertEquals("Die unbesiegbaren Geo - Geparden", cache.getOwner()); + assertEquals(CacheSize.SMALL, cache.getSize()); + assertEquals(1.0f, cache.getDifficulty().floatValue()); + assertEquals(4.0f, cache.getTerrain().floatValue()); + assertEquals("Baden-Württemberg, Germany", cache.getLocation()); + assertEquals("Ein alter Kindheitstraum, ein Schatz auf einer unbewohnten Insel. A old dream of my childhood, a treasure on a lonely is", cache.getShortdesc()); + assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(cache.getCoords())); } public void testGc31j2h() throws IOException { @@ -83,7 +83,7 @@ public class GPXParserTest extends InstrumentationTestCase { assertSame(cache, caches.get(0)); // no waypoints without importing waypoint file - assertNull(cache.waypoints); + assertNull(cache.getWaypoints()); } public void testGc31j2hWpts() throws IOException { @@ -129,18 +129,18 @@ public class GPXParserTest extends InstrumentationTestCase { assertFalse(cache.isEventCache()); assertFalse(cache.isMembersOnly()); assertFalse(cache.isOwn()); - assertTrue(cache.found); + assertTrue(cache.isFound()); assertEquals("Station3: Der zerbrochene Stein zählt doppelt.\nFinal: Oben neben dem Tor", cache.getHint()); // logs - assertEquals(6, cache.logs.size()); - final cgLog log = cache.logs.get(5); + assertEquals(6, cache.getLogs().size()); + final cgLog log = cache.getLogs().get(5); assertEquals("Geoteufel", log.author); assertEquals(parseTime("2011-09-11T07:00:00Z"), log.date); assertEquals(-1, log.found); assertEquals("Sehr schöne Runde und wir haben wieder etwas Neues über Hockenheim gelernt. Super Tarnung.\nTFTC, Geoteufel", log.log); // following info is not contained in pocket query gpx file - assertNull(cache.attributes); + assertNull(cache.getAttributes()); } private static long parseTime(final String time) { @@ -152,27 +152,27 @@ public class GPXParserTest extends InstrumentationTestCase { } private static void assertGc31j2hWaypoints(final cgCache cache) { - assertNotNull(cache.waypoints); - assertEquals(2, cache.waypoints.size()); - cgWaypoint wp = cache.waypoints.get(0); - assertEquals("GC31J2H", wp.geocode); + assertNotNull(cache.getWaypoints()); + assertEquals(2, cache.getWaypoints().size()); + cgWaypoint wp = cache.getWaypoints().get(0); + assertEquals("GC31J2H", wp.getGeocode()); assertEquals("00", wp.getPrefix()); - assertEquals("---", wp.lookup); - assertEquals("Parkplatz", wp.name); - assertEquals("Kostenfreies Parken (je nach Parkreihe Parkscheibe erforderlich)", wp.note); - assertEquals(WaypointType.PARKING, wp.type); - assertEquals(49.317517, wp.coords.getLatitude(), 0.000001); - assertEquals(8.545083, wp.coords.getLongitude(), 0.000001); - - wp = cache.waypoints.get(1); - assertEquals("GC31J2H", wp.geocode); + assertEquals("---", wp.getLookup()); + assertEquals("Parkplatz", wp.getName()); + assertEquals("Kostenfreies Parken (je nach Parkreihe Parkscheibe erforderlich)", wp.getNote()); + assertEquals(WaypointType.PARKING, wp.getWaypointType()); + assertEquals(49.317517, wp.getCoords().getLatitude(), 0.000001); + assertEquals(8.545083, wp.getCoords().getLongitude(), 0.000001); + + wp = cache.getWaypoints().get(1); + assertEquals("GC31J2H", wp.getGeocode()); assertEquals("S1", wp.getPrefix()); - assertEquals("---", wp.lookup); - assertEquals("Station 1", wp.name); - assertEquals("Ein zweiter Wegpunkt, der nicht wirklich existiert sondern nur zum Testen gedacht ist.", wp.note); - assertEquals(WaypointType.STAGE, wp.type); - assertEquals(49.317500, wp.coords.getLatitude(), 0.000001); - assertEquals(8.545100, wp.coords.getLongitude(), 0.000001); + assertEquals("---", wp.getLookup()); + assertEquals("Station 1", wp.getName()); + assertEquals("Ein zweiter Wegpunkt, der nicht wirklich existiert sondern nur zum Testen gedacht ist.", wp.getNote()); + assertEquals(WaypointType.STAGE, wp.getWaypointType()); + assertEquals(49.317500, wp.getCoords().getLatitude(), 0.000001); + assertEquals(8.545100, wp.getCoords().getLongitude(), 0.000001); } public static void testGetWaypointsFileForGpx() { diff --git a/tests/src/cgeo/geocaching/files/LocParserTest.java b/tests/src/cgeo/geocaching/files/LocParserTest.java index 9d90ef4..6e74061 100644 --- a/tests/src/cgeo/geocaching/files/LocParserTest.java +++ b/tests/src/cgeo/geocaching/files/LocParserTest.java @@ -44,21 +44,21 @@ public class LocParserTest extends InstrumentationTestCase { final Map<String, cgCoord> coords = readLoc(R.raw.oc5952_loc); final cgCoord coord = coords.get("OC5952"); assertNotNull(coord); - assertEquals("OC5952", coord.geocode); - assertEquals("Die Schatzinsel / treasure island", coord.name); - assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(coord.coords)); + assertEquals("OC5952", coord.getGeocode()); + assertEquals("Die Schatzinsel / treasure island", coord.getName()); + assertTrue(new Geopoint(48.85968, 9.18740).isEqualTo(coord.getCoords())); } public void testGCLoc() { final Map<String, cgCoord> coords = readLoc(R.raw.gc1bkp3_loc); final cgCoord coord = coords.get("GC1BKP3"); assertNotNull(coord); - assertEquals("GC1BKP3", coord.geocode); - assertEquals("Die Schatzinsel / treasure island", coord.name); - assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(coord.coords)); - assertEquals(1.0f, coord.difficulty.floatValue()); - assertEquals(5.0f, coord.terrain.floatValue()); - assertEquals(CacheSize.MICRO, coord.size); + assertEquals("GC1BKP3", coord.getGeocode()); + assertEquals("Die Schatzinsel / treasure island", coord.getName()); + assertTrue(new Geopoint(48.859683, 9.1874).isEqualTo(coord.getCoords())); + assertEquals(1.0f, coord.getDifficulty().floatValue()); + assertEquals(5.0f, coord.getTerrain().floatValue()); + assertEquals(CacheSize.MICRO, coord.getSize()); } } diff --git a/tests/src/cgeo/geocaching/geopoint/DistanceParserTest.java b/tests/src/cgeo/geocaching/geopoint/DistanceParserTest.java index 357d34c..52a1080 100644 --- a/tests/src/cgeo/geocaching/geopoint/DistanceParserTest.java +++ b/tests/src/cgeo/geocaching/geopoint/DistanceParserTest.java @@ -1,7 +1,5 @@ package cgeo.geocaching.geopoint; -import cgeo.geocaching.geopoint.DistanceParser; - import android.test.AndroidTestCase; import junit.framework.Assert; diff --git a/tests/src/cgeo/geocaching/sorting/NameComparatorTest.java b/tests/src/cgeo/geocaching/sorting/NameComparatorTest.java index eb496e4..fa3b16c 100644 --- a/tests/src/cgeo/geocaching/sorting/NameComparatorTest.java +++ b/tests/src/cgeo/geocaching/sorting/NameComparatorTest.java @@ -9,7 +9,7 @@ public class NameComparatorTest extends AndroidTestCase { private static class NamedCache extends cgCache { public NamedCache(final String name) { - this.name = name; + this.setName(name); } } diff --git a/tests/src/cgeo/geocaching/test/mock/GC1ZXX2.java b/tests/src/cgeo/geocaching/test/mock/GC1ZXX2.java index 6d63b18..e7abb48 100644 --- a/tests/src/cgeo/geocaching/test/mock/GC1ZXX2.java +++ b/tests/src/cgeo/geocaching/test/mock/GC1ZXX2.java @@ -50,8 +50,8 @@ public class GC1ZXX2 extends MockedCache { } @Override - public String getType() { - return CacheType.TRADITIONAL.id; + public CacheType getCacheType() { + return CacheType.TRADITIONAL; } @Override diff --git a/tests/src/cgeo/geocaching/test/mock/GC2CJPF.java b/tests/src/cgeo/geocaching/test/mock/GC2CJPF.java index 6ef2406..f44f560 100644 --- a/tests/src/cgeo/geocaching/test/mock/GC2CJPF.java +++ b/tests/src/cgeo/geocaching/test/mock/GC2CJPF.java @@ -54,8 +54,8 @@ public class GC2CJPF extends MockedCache { } @Override - public String getType() { - return CacheType.MULTI.id; + public CacheType getCacheType() { + return CacheType.MULTI; } @Override diff --git a/tests/src/cgeo/geocaching/test/mock/GC2JVEH.java b/tests/src/cgeo/geocaching/test/mock/GC2JVEH.java index 38bce01..faf3ca8 100644 --- a/tests/src/cgeo/geocaching/test/mock/GC2JVEH.java +++ b/tests/src/cgeo/geocaching/test/mock/GC2JVEH.java @@ -67,8 +67,8 @@ public class GC2JVEH extends MockedCache { } @Override - public String getType() { - return CacheType.MYSTERY.id; + public CacheType getCacheType() { + return CacheType.MYSTERY; } @Override |
