diff options
| author | koem <koem@petoria.de> | 2011-10-10 17:18:49 +0200 |
|---|---|---|
| committer | koem <koem@petoria.de> | 2011-10-10 17:25:02 +0200 |
| commit | bfa29b4962bee99f7b16b6900e424915fa2201e2 (patch) | |
| tree | 0c3c48efd6716e1470fb740b66ef140a8dc3f987 | |
| parent | 6e950c529ab6d1df27841e88b4237180a2465b79 (diff) | |
| parent | 6a775b8c3381470ae31c0f618070bd4d3d269262 (diff) | |
| download | cgeo-bfa29b4962bee99f7b16b6900e424915fa2201e2.zip cgeo-bfa29b4962bee99f7b16b6900e424915fa2201e2.tar.gz cgeo-bfa29b4962bee99f7b16b6900e424915fa2201e2.tar.bz2 | |
Merge remote branch 'upstream/master' into enums
Conflicts:
main/src/cgeo/geocaching/cgData.java
main/src/cgeo/geocaching/cgeodetail.java
57 files changed, 1095 insertions, 1137 deletions
diff --git a/main/.classpath b/main/.classpath index 93696c3..9a2bd80 100644 --- a/main/.classpath +++ b/main/.classpath @@ -6,5 +6,6 @@ <classpathentry exported="true" kind="lib" path="libs/commons-lang3-3.0.1.jar"/> <classpathentry kind="lib" path="libs/locus-api-4.0.jar"/> <classpathentry kind="lib" path="libs/mapsforge-map-0.2.4.jar"/> + <classpathentry kind="lib" path="libs/commons-collections-3.2.1.jar"/> <classpathentry kind="output" path="bin"/> </classpath> diff --git a/main/AndroidManifest.xml b/main/AndroidManifest.xml index cc06ffc..deb72e1 100644 --- a/main/AndroidManifest.xml +++ b/main/AndroidManifest.xml @@ -1,7 +1,7 @@ <?xml version="1.0" encoding="UTF-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" - android:versionName="06.10.2011a" - android:versionCode="20111007" + android:versionName="09.10.2011" + android:versionCode="20111009" package="cgeo.geocaching" name="c:geo" android:installLocation="auto"> diff --git a/main/libs/commons-collections-3.2.1.jar b/main/libs/commons-collections-3.2.1.jar Binary files differnew file mode 100644 index 0000000..c35fa1f --- /dev/null +++ b/main/libs/commons-collections-3.2.1.jar diff --git a/main/proguard.cfg b/main/proguard.cfg index fa8f1ae..02ab774 100644 --- a/main/proguard.cfg +++ b/main/proguard.cfg @@ -4,6 +4,7 @@ -allowaccessmodification -optimizations !code/simplification/arithmetic,!code/allocation/variable +-dontwarn java.beans.* -dontwarn org.mapsforge.android.maps.Test* -keep public class * extends android.app.Activity diff --git a/main/project/localization/findextratranslations.sh b/main/project/localization/findextratranslations.sh index 4200de6..8e2898d 100755 --- a/main/project/localization/findextratranslations.sh +++ b/main/project/localization/findextratranslations.sh @@ -8,9 +8,9 @@ sourcedir=../../src/cgeo/geocaching sourcefiles=`cd $sourcedir && find . -name '*.java'` xmlfiles=`echo ../../res/*/*.xml ../../AndroidManifest.xml` first=true -if [ x$1 == x-f ]; then +if [ x$1 = x-f ]; then remove=true -elif [ x$1 == x-n ]; then +elif [ x$1 = x-n ]; then remove=false else echo "Usage: findextratranslations.sh [ -n | -f]" >&2 diff --git a/main/res/values-de/strings.xml b/main/res/values-de/strings.xml index c426acb..720ac2b 100644 --- a/main/res/values-de/strings.xml +++ b/main/res/values-de/strings.xml @@ -11,6 +11,8 @@ <string name="helpers">Nützliche Apps</string> <string name="about">Über c:geo</string> <string name="helper">Du willst mehr über <b>c:geo</b> erfahren?\nSchaue in die Bedienungsanleitung.</string> + <string name="latitude">Breitengrad</string> + <string name="longitude">Längengrad</string> <!-- actionbar --> <string name="action_bar_share_title">Link versenden</string> @@ -123,6 +125,8 @@ <string name="err_missing_auth">Benutzername oder Passwort nicht gesetzt.</string> <string name="err_wrong">Falsche Anmeldedaten</string> <string name="err_license">Die Geocaching.com Nutzungsbedingungen wurden nicht akzeptiert. c:geo kann deshalb keine Koordinaten laden.</string> + <string name="err_unpublished">Der aufgerufene Cache ist noch nicht veröffentlicht</string> + <string name="err_premium_only">Der Cache ist nur für Premium Mitglieder von Geocaching.com verfügbar</string> <string name="err_store">c:geo konnte den Cache nicht speichern.</string> <string name="err_drop">c:geo konnte den Cache nicht löschen.</string> <string name="err_detail_open">c:geo konnte die Cache-Details nicht öffnen.</string> @@ -165,6 +169,7 @@ <string name="err_tb_forgot_saw">c:geo hat vergessen, welchen Trackable du gesehen hast.</string> <string name="err_tb_find">c:geo findet den Trackable nicht</string> <string name="err_tb_find_that">c:geo konnte diesen Trackable nicht finden.</string> + <string name="err_cache_inventory_load_fail">c:geo konnte das Inventar nicht laden.</string> <string name="err_waypoint_cache_unknown">c:geo weiß nicht, zu welchem Cache der Wegpunkt hinzugefügt werden soll.</string> <string name="err_waypoint_unknown">c:geo hat vergessen, welchen Wegpunkt du ansehen wolltest.</string> @@ -240,6 +245,7 @@ <string name="advanced_search_button">Suche</string> <string name="stored_caches_button">Gespeichert</string> <string name="any_button">Überall</string> + <string name="unknown_scan">Konnte keinen GC-Code im Scan finden.</string> <!-- caches --> <string name="caches_no_cache">Kein Cache</string> @@ -336,6 +342,8 @@ <string name="list_dialog_remove">Entfernen</string> <string name="list_dialog_remove_ok">Liste wurde gelöscht</string> <string name="list_dialog_remove_err">c:geo konnte die Liste nicht löschen</string> + <string name="list_dialog_rename_title">Liste umbenennen</string> + <string name="list_dialog_rename">Umbenennen</string> <!-- about --> <string name="about_changelog">Änderungen</string> @@ -395,12 +403,15 @@ <string name="init_cleared">c:geo hat die Anmeldedaten gelöscht.</string> <string name="init_backup">Sicherung</string> <string name="init_backup_backup">Sicherung</string> + <string name="init_backup_running">Erzeuge Sicherung der Cache-Datenbank…</string> <string name="init_backup_note">Hinweis: Diese Option sichert die Datenbank von c:geo. Nur Caches und Wegpunkte werden gesichert, keine Einstellungen. Login-Daten und Passwörter werden die App nicht verlassen.</string> <string name="init_backup_restore">Wiederherstellung</string> <string name="init_backup_success">Datenbank von c:geo wurde erfolgreich in Datei geschrieben</string> <string name="init_backup_failed">Sicherung der Datenbank fehlgeschlagen.</string> + <string name="init_backup_unnecessary">Datenbank ist leer, keine Sicherung notwendig.</string> <string name="init_restore_success">Wiederherstellung beendet.</string> <string name="init_restore_failed">Wiederherstellung fehlgeschlagen.</string> + <string name="init_restore_running">Wiederherstellung der Cache-Datenbank…</string> <string name="init_backup_last">Backup verfügbar von</string> <string name="init_backup_last_no">Keine Datei mit Datenbanksicherung gefunden.</string> <string name="init_mapsources">Kartenherkunft</string> <!-- since: 2.26 RC3 --> @@ -458,6 +469,7 @@ <string name="cache_attributes">Attribute</string> <string name="cache_attributes_no_icons">(aktualisiere den Cache um die Attribut-Icons anzuzeigen)</string> <string name="cache_inventory">Inventar</string> + <string name="cache_inventory_loading">Lade Inventar…</string> <string name="cache_log_offline">Offline-Log</string> <string name="cache_log_images_loading">Lade Logbild …</string> <string name="cache_log_images_title">Logbild</string> @@ -481,7 +493,7 @@ <string name="cache_dialog_loading_details_status_logs">Lade Logs</string> <string name="cache_dialog_loading_details_status_waypoints">Verarbeite Wegpunkte</string> <string name="cache_dialog_loading_details_status_gcvote">Lade GCVote</string> - <string name="cache_dialog_loading_details_status_render">Generiere Ansicht</string> + <string name="cache_dialog_loading_details_status_render">Erzeuge Darstellung</string> <string name="cache_dialog_loading_description">Lade Cache-Beschreibung…</string> <string name="cache_dialog_offline_save_title">Offline-Verwendung</string> <string name="cache_dialog_offline_save_message">Speichere Cache für Offline-Verwendung…</string> @@ -540,6 +552,7 @@ <string name="cache_export_fieldnote">Exportiere als Field-Notes</string> <string name="cache_clear_history">Verlauf leeren</string> <string name="cache_remove_from_history">Aus Verlauf löschen</string> + <string name="cache_license">Lizenz</string> <!-- file list base --> <string name="file_searching_in">Suche nach Dateien\nin</string> diff --git a/main/res/values-fr/strings.xml b/main/res/values-fr/strings.xml index 4e0eaef..a0c2ca3 100644 --- a/main/res/values-fr/strings.xml +++ b/main/res/values-fr/strings.xml @@ -445,7 +445,7 @@ <string name="auth_authorize">autorisation de c:geo</string> <string name="auth_start">début d\'autorisation</string> <string name="auth_again">redémarre</string> - <string name="auth_pin_hint">code pin attribué par twitter</string> + <string name="auth_pin_hint">code donné par Twitter</string> <string name="auth_finish">terminé</string> <string name="auth_dialog_wait">en attente de Twitter…</string> <string name="auth_dialog_pin_title">code PIN</string> @@ -654,7 +654,7 @@ <string name="search_hbu_prefill">Propriétaire</string> <string name="search_hbu_button">Recherche par propriétaire</string> <string name="search_tb">Objet voyageur</string> - <string name="search_tb_hint">Identification de l\'objet voyageur</string> + <string name="search_tb_hint">Identifiant de l\'objet</string> <string name="search_tb_button">Recherche par objet voyageur</string> <string name="search_destination">Destination</string> <string name="search_some_destination">Destination arbitraire</string> @@ -868,5 +868,5 @@ <string name="about_go4cache">Le service <b>Go 4 cache</b> vous permet de voir en temps réel d\'autres géocacheurs sur une carte (dans <b>c:geo</b> ou dans le navigateur). Il peut afficher les caches en cours de recherche. En vous connectant sur <b>Go 4 cache</b> vous permettez à <b>c:geo</b> de publier votre publication (seulement si <b>c:geo</b> fonctionne).</string> <string name="about_twitter">Voulez-vous publier un nouveau statut sur Twitter à chaque nouvelle cache découverte sous <b>c:geo</b>?</string> <string name="about_auth_1">Le processus suivant permet à <b>c:geo</b> d\'accéder à votre compte Twitter - si vous acceptez.</string> - <string name="about_auth_2">Cliquer sur le bouton \"autoriser c:geo\" pour démarrer. Une fenêtre de navigateur va s\'ouvrir pour vous connecter sur Twitter. Accepter pour que <b>c:geo</b> accéde à votre compte. Twitter vous affichera alors une code PIN composé de chiffres. Merci de coller ce code dans <b>c:geo</b> puis confirmer. C\'est tout!</string> + <string name="about_auth_2">Cliquer sur le bouton \"début d\'autorisation\" pour démarrer. Une fenêtre de navigateur va s\'ouvrir pour vous connecter sur Twitter. Accepter pour que <b>c:geo</b> accéde à votre compte. Twitter vous affichera alors une code PIN composé de chiffres. Merci de coller ce code dans <b>c:geo</b> puis confirmer. C\'est tout!</string> </resources> diff --git a/main/res/values-sk/strings.xml b/main/res/values-sk/strings.xml index 627d63c..92ba4bc 100644 --- a/main/res/values-sk/strings.xml +++ b/main/res/values-sk/strings.xml @@ -328,6 +328,7 @@ <string name="list_menu_create">Vytvoriť nový zoznam</string> <string name="list_menu_drop">Zahodiť aktuálny zoznam</string> <string name="list_menu_change">Zmeniť zoznam</string> <!-- since: 2.2 --> + <string name="list_menu_rename">Premenovať tento zoznam</string> <string name="list_title">Výber zoznamu</string> <string name="list_inbox">Uložené</string> <string name="list_wpt">Body trasy</string> @@ -341,6 +342,8 @@ <string name="list_dialog_remove">Odstrániť</string> <string name="list_dialog_remove_ok">Zoznam bol odstránený</string> <string name="list_dialog_remove_err">c:geo sa nepodarilo odstrániť aktuálny zoznam</string> + <string name="list_dialog_rename_title">Premenovať zoznam</string> + <string name="list_dialog_rename">Premenovať</string> <!-- about --> <string name="about_changelog">Zmeny</string> diff --git a/main/res/values/strings.xml b/main/res/values/strings.xml index 37fa17d..c3a8fcf 100644 --- a/main/res/values/strings.xml +++ b/main/res/values/strings.xml @@ -140,9 +140,7 @@ <string name="err_detail_no_spoiler">c:geo found no spoiler images for this cache.</string> <string name="err_detail_no_map_static">c:geo found no static maps for this cache.</string> <string name="err_detail_not_load_map_static">Sorry, c:geo failed to load static maps.</string> - <string name="err_detail_still_removing">Still removing this cache.</string> - <string name="err_detail_still_saving">Still saving this cache.</string> - <string name="err_detail_still_refreshing">Still reloading this cache.</string> + <string name="err_detail_still_working">Still working on another task.</string> <string name="err_watchlist_still_managing">Still managing your watchlist.</string> <string name="err_watchlist_failed">Changing your watchlist failed.</string> <string name="err_navigation_no">c:geo can\'t find any supported navigation.</string> @@ -938,6 +936,9 @@ · new: cleanup the cgeo private cache directory when caches are removed from database\n · new: display user avatar when checking login/password from geocaching.com\n \n\n + <b>09.10.2011</b>\n + · fix: small bugs due to GC.com change\n + \n\n <b>06.10.2011</b>\n · new: import waypoint files from pocket query\n · new: automatically filter out counter images from cache description\n diff --git a/main/src/cgeo/geocaching/GCVote.java b/main/src/cgeo/geocaching/GCVote.java index 73e08a6..3404f60 100644 --- a/main/src/cgeo/geocaching/GCVote.java +++ b/main/src/cgeo/geocaching/GCVote.java @@ -1,7 +1,6 @@ package cgeo.geocaching; -import cgeo.geocaching.utils.CollectionUtils; - +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.util.Log; @@ -91,7 +90,7 @@ public final class GCVote { final Matcher matcherGuid = patternGuid.matcher(voteData); if (matcherGuid.find()) { if (matcherGuid.groupCount() > 0) { - guid = (String) matcherGuid.group(1); + guid = matcherGuid.group(1); } } } catch (Exception e) { diff --git a/main/src/cgeo/geocaching/StaticMapsProvider.java b/main/src/cgeo/geocaching/StaticMapsProvider.java index 1bf5655..48aace6 100644 --- a/main/src/cgeo/geocaching/StaticMapsProvider.java +++ b/main/src/cgeo/geocaching/StaticMapsProvider.java @@ -1,8 +1,8 @@ package cgeo.geocaching; import cgeo.geocaching.files.LocalStorage; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; diff --git a/main/src/cgeo/geocaching/Twitter.java b/main/src/cgeo/geocaching/Twitter.java index 2f3119d..28da23e 100644 --- a/main/src/cgeo/geocaching/Twitter.java +++ b/main/src/cgeo/geocaching/Twitter.java @@ -1,26 +1,16 @@ package cgeo.geocaching; import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.network.OAuth; -import android.util.Log; +import org.apache.http.HttpResponse; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; -import java.util.zip.GZIPInputStream; -import java.util.zip.Inflater; -import java.util.zip.InflaterInputStream; +import android.util.Log; public final class Twitter { public static final int MAX_TWEET_SIZE = 140; - public static void postTweet(cgeoapplication app, String status, final Geopoint coords) { + public static void postTweet(final cgeoapplication app, final String status, final Geopoint coords) { if (app == null) { return; } @@ -37,83 +27,18 @@ public final class Twitter { "display_coordinates", "true"); } - final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false, parameters, Settings.getTokenPublic(), Settings.getTokenSecret()); - - HttpURLConnection connection = null; - try { - final StringBuffer buffer = new StringBuffer(); - final URL u = new URL("http://api.twitter.com/1/statuses/update.json"); - final URLConnection uc = u.openConnection(); - - uc.setRequestProperty("Host", "api.twitter.com"); - - connection = (HttpURLConnection) uc; - connection.setReadTimeout(30000); - connection.setRequestMethod("POST"); - HttpURLConnection.setFollowRedirects(true); - connection.setDoInput(true); - connection.setDoOutput(true); - - final OutputStream out = connection.getOutputStream(); - final OutputStreamWriter wr = new OutputStreamWriter(out); - wr.write(paramsDone); - wr.flush(); - wr.close(); - - Log.i(Settings.tag, "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage()); - - InputStream ins; - final String encoding = connection.getContentEncoding(); - - if (encoding != null && encoding.equalsIgnoreCase("gzip")) { - ins = new GZIPInputStream(connection.getInputStream()); - } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { - ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true)); - } else { - ins = connection.getInputStream(); - } - - final InputStreamReader inr = new InputStreamReader(ins); - final BufferedReader br = new BufferedReader(inr); - - readIntoBuffer(br, buffer); - - br.close(); - ins.close(); - inr.close(); - connection.disconnect(); - } catch (IOException e) { - Log.e(Settings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": " + connection.getResponseMessage() + " ~ " + e.toString()); - - final InputStream ins = connection.getErrorStream(); - final StringBuffer buffer = new StringBuffer(); - final InputStreamReader inr = new InputStreamReader(ins); - final BufferedReader br = new BufferedReader(inr); - - readIntoBuffer(br, buffer); - - br.close(); - ins.close(); - inr.close(); - } catch (Exception e) { - Log.e(Settings.tag, "cgBase.postTweet.inner: " + e.toString()); + OAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false, parameters, Settings.getTokenPublic(), Settings.getTokenSecret()); + final HttpResponse httpResponse = cgBase.postRequest("http://api.twitter.com/1/statuses/update.json", parameters); + if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) { + Log.i(Settings.tag, "Tweet posted"); + } else { + Log.e(Settings.tag, "Tweet could not be posted"); } - - connection.disconnect(); } catch (Exception e) { Log.e(Settings.tag, "cgBase.postTweet: " + e.toString()); } } - private static void readIntoBuffer(BufferedReader br, StringBuffer buffer) throws IOException { - final int bufferSize = 1024 * 16; - final char[] bytes = new char[bufferSize]; - int bytesRead; - while ((bytesRead = br.read(bytes)) > 0) { - buffer.append(bytes, 0, bytesRead); - } - } - public static String appendHashTag(final String status, final String tag) { String result = status; if (result.length() + 2 + tag.length() <= 140) { diff --git a/main/src/cgeo/geocaching/activity/Progress.java b/main/src/cgeo/geocaching/activity/Progress.java new file mode 100644 index 0000000..78fa92f --- /dev/null +++ b/main/src/cgeo/geocaching/activity/Progress.java @@ -0,0 +1,37 @@ +package cgeo.geocaching.activity; + +import android.app.ProgressDialog; +import android.content.Context; + +/** + * progress dialog wrapper for easier management of resources + */ +public class Progress { + + private static ProgressDialog dialog; + + public static void dismiss() { + if (dialog != null && dialog.isShowing()) { + dialog.dismiss(); + dialog = null; + } + } + + public static ProgressDialog show(Context context, String title, String message, boolean indeterminate, boolean cancelable) { + if (dialog == null) { + dialog = ProgressDialog.show(context, title, message, indeterminate, cancelable); + } + return dialog; + } + + public static void setMessage(final String message) { + if (dialog != null && dialog.isShowing()) { + dialog.setMessage(message); + } + } + + public static boolean isShowing() { + return dialog != null && dialog.isShowing(); + } + +} diff --git a/main/src/cgeo/geocaching/apps/AbstractApp.java b/main/src/cgeo/geocaching/apps/AbstractApp.java index 1a166c6..7cf0b7f 100644 --- a/main/src/cgeo/geocaching/apps/AbstractApp.java +++ b/main/src/cgeo/geocaching/apps/AbstractApp.java @@ -1,6 +1,6 @@ package cgeo.geocaching.apps; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import android.content.Context; import android.content.Intent; diff --git a/main/src/cgeo/geocaching/apps/LocusDataStorageProvider.java b/main/src/cgeo/geocaching/apps/LocusDataStorageProvider.java index 69a5e5b..6897f95 100644 --- a/main/src/cgeo/geocaching/apps/LocusDataStorageProvider.java +++ b/main/src/cgeo/geocaching/apps/LocusDataStorageProvider.java @@ -4,6 +4,8 @@ import menion.android.locus.addon.publiclib.geoData.PointsData; import menion.android.locus.addon.publiclib.utils.DataCursor; import menion.android.locus.addon.publiclib.utils.DataStorage; +import org.apache.commons.collections.CollectionUtils; + import android.content.ContentProvider; import android.content.ContentValues; import android.database.Cursor; @@ -24,7 +26,7 @@ public class LocusDataStorageProvider extends ContentProvider { DataCursor cursor = new DataCursor(new String[] { "data" }); ArrayList<PointsData> data = DataStorage.getData(); - if (data == null || data.size() == 0) { + if (CollectionUtils.isEmpty(data)) { return cursor; } diff --git a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java index c08122a..e4afc31 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java @@ -4,6 +4,8 @@ import cgeo.geocaching.cgCache; import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.AbstractLocusApp; +import org.apache.commons.collections.CollectionUtils; + import android.app.Activity; import android.content.res.Resources; @@ -25,7 +27,7 @@ class LocusCacheListApp extends AbstractLocusApp implements CacheListApp { @Override public boolean invoke(cgGeo geo, List<cgCache> cacheList, Activity activity, Resources res, final UUID searchId) { - if (cacheList == null || cacheList.isEmpty()) + if (CollectionUtils.isEmpty(cacheList)) return false; showInLocus((List<? extends Object>) cacheList, false, activity); diff --git a/main/src/cgeo/geocaching/cgBase.java b/main/src/cgeo/geocaching/cgBase.java index 1e44873..8ad0006 100644 --- a/main/src/cgeo/geocaching/cgBase.java +++ b/main/src/cgeo/geocaching/cgBase.java @@ -11,8 +11,9 @@ import cgeo.geocaching.files.LocParser; import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.BaseUtils; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.ImmutablePair; @@ -114,8 +115,8 @@ public class cgBase { private final static Pattern PATTERN_TRACKABLE_SpottedUser = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">In the hands of ([^<]+).</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE); private final static Pattern PATTERN_TRACKABLE_SpottedUnknown = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">Unknown Location[^<]*</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE); private final static Pattern PATTERN_TRACKABLE_SpottedOwner = Pattern.compile("<dt>\\W*Recently Spotted:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugLocation\">In the hands of the owner[^<]*</a>[^<]*</dd>", Pattern.CASE_INSENSITIVE); - private final static Pattern PATTERN_TRACKABLE_Goal = Pattern.compile("<h3>\\W*Current GOAL[^<]*</h3>[^<]*<p[^>]*>(.*)</p>[^<]*<h3>\\W*About This Item[^<]*</h3>", Pattern.CASE_INSENSITIVE); - private final static Pattern PATTERN_TRACKABLE_DetailsImage = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*<div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">", Pattern.CASE_INSENSITIVE); + private final static Pattern PATTERN_TRACKABLE_GOAL = Pattern.compile("<h3>\\W*Current GOAL[^<]*</h3>[^<]*<div id=\"TrackableGoal\">[^<]*<p>(.*?)</p>[^<]*</div>[^<]*<h3>"); + private final static Pattern PATTERN_TRACKABLE_DETAILSIMAGE = Pattern.compile("<h3>\\W*About This Item[^<]*</h3>[^<]*<div id=\"TrackableDetails\">([^<]*<p>([^<]*<img id=\"ctl00_ContentBody_BugDetails_BugImage\" class=\"[^\"]+\" src=\"([^\"]+)\"[^>]*>)?[^<]*</p>)?[^<]*<p[^>]*>(.*)</p>[^<]*</div> <div id=\"ctl00_ContentBody_BugDetails_uxAbuseReport\">"); private final static Pattern PATTERN_TRACKABLE_Icon = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE); private final static Pattern PATTERN_TRACKABLE_Type = Pattern.compile("<img id=\"ctl00_ContentBody_BugTypeImage\" class=\"TravelBugHeaderIcon\" src=\"[^\"]+\" alt=\"([^\"]+)\"[^>]*>", Pattern.CASE_INSENSITIVE); private final static Pattern PATTERN_TRACKABLE_Distance = Pattern.compile("<h4[^>]*\\W*Tracking History \\(([0-9.,]+(km|mi))[^\\)]*\\)", Pattern.CASE_INSENSITIVE); @@ -238,7 +239,9 @@ public class cgBase { // waypoint types for (WaypointType wt : WaypointType.values()) { - waypointTypees.put(wt, res.getString(wt.stringId)); + if (wt != WaypointType.OWN) { + waypointTypees.put(wt, res.getString(wt.stringId)); + } } // log types @@ -943,7 +946,7 @@ public class cgBase { try { final Map<String, cgRating> ratings = GCVote.getRating(guids, null); - if (CollectionUtils.isNotEmpty(ratings)) { + if (MapUtils.isNotEmpty(ratings)) { // save found cache coordinates for (cgCache oneCache : caches.cacheList) { if (ratings.containsKey(oneCache.guid)) { @@ -1206,11 +1209,15 @@ public class cgBase { Log.w(Settings.tag, "cgeoBase.parseCache: Failed to parse watchlist state"); } - // latitude and logitude + // latitude and longitude cache.latlon = BaseUtils.getMatch(page, Constants.PATTERN_LATLON, 1, cache.latlon); if (StringUtils.isNotEmpty(cache.latlon)) { - cache.coords = new Geopoint(cache.latlon); - cache.reliableLatLon = true; + try { + cache.coords = new Geopoint(cache.latlon); + cache.reliableLatLon = true; + } catch (Geopoint.GeopointException e) { + Log.w(Settings.tag, "cgeoBase.parseCache: Failed to parse cache coordinates: " + e.toString()); + } } // cache location @@ -1324,8 +1331,8 @@ public class cgBase { while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final cgTrackable inventoryItem = new cgTrackable(); - inventoryItem.guid = matcherInventoryInside.group(1); - inventoryItem.name = matcherInventoryInside.group(2); + inventoryItem.setGuid(matcherInventoryInside.group(1)); + inventoryItem.setName(matcherInventoryInside.group(2)); cache.inventory.add(inventoryItem); cache.inventoryItems++; @@ -1728,7 +1735,7 @@ public class cgBase { try { final Matcher matcherGeocode = PATTERN_TRACKABLE_Geocode.matcher(page); if (matcherGeocode.find() && matcherGeocode.groupCount() > 0) { - trackable.geocode = matcherGeocode.group(1).toUpperCase(); + trackable.setGeocode(matcherGeocode.group(1).trim().toUpperCase()); } } catch (Exception e) { // failed to parse trackable geocode @@ -1739,7 +1746,7 @@ public class cgBase { try { final Matcher matcherTrackableId = PATTERN_TRACKABLE_TrackableId.matcher(page); if (matcherTrackableId.find() && matcherTrackableId.groupCount() > 0) { - trackable.guid = matcherTrackableId.group(1); + trackable.setGuid(matcherTrackableId.group(1).trim()); } } catch (Exception e) { // failed to parse trackable id @@ -1750,7 +1757,7 @@ public class cgBase { try { final Matcher matcherTrackableIcon = PATTERN_TRACKABLE_Icon.matcher(page); if (matcherTrackableIcon.find() && matcherTrackableIcon.groupCount() > 0) { - trackable.iconUrl = matcherTrackableIcon.group(1); + trackable.setIconUrl(matcherTrackableIcon.group(1).trim()); } } catch (Exception e) { // failed to parse trackable icon @@ -1761,7 +1768,7 @@ public class cgBase { try { final Matcher matcherName = PATTERN_TRACKABLE_Name.matcher(page); if (matcherName.find() && matcherName.groupCount() > 1) { - trackable.name = matcherName.group(2); + trackable.setName(matcherName.group(2).trim()); } } catch (Exception e) { // failed to parse trackable name @@ -1769,11 +1776,11 @@ public class cgBase { } // trackable type - if (StringUtils.isNotBlank(trackable.name)) { + if (StringUtils.isNotBlank(trackable.getName())) { try { final Matcher matcherType = PATTERN_TRACKABLE_Type.matcher(page); if (matcherType.find() && matcherType.groupCount() > 0) { - trackable.type = matcherType.group(1); + trackable.setType(matcherType.group(1).trim()); } } catch (Exception e) { // failed to parse trackable type @@ -1785,8 +1792,8 @@ public class cgBase { try { final Matcher matcherOwner = PATTERN_TRACKABLE_Owner.matcher(page); if (matcherOwner.find() && matcherOwner.groupCount() > 0) { - trackable.ownerGuid = matcherOwner.group(1); - trackable.owner = matcherOwner.group(2); + trackable.setOwnerGuid(matcherOwner.group(1)); + trackable.setOwner(matcherOwner.group(2).trim()); } } catch (Exception e) { // failed to parse trackable owner name @@ -1797,7 +1804,7 @@ public class cgBase { try { final Matcher matcherOrigin = PATTERN_TRACKABLE_Origin.matcher(page); if (matcherOrigin.find() && matcherOrigin.groupCount() > 0) { - trackable.origin = matcherOrigin.group(1); + trackable.setOrigin(matcherOrigin.group(1).trim()); } } catch (Exception e) { // failed to parse trackable origin @@ -1808,26 +1815,26 @@ public class cgBase { try { final Matcher matcherSpottedCache = PATTERN_TRACKABLE_SpottedCache.matcher(page); if (matcherSpottedCache.find() && matcherSpottedCache.groupCount() > 0) { - trackable.spottedGuid = matcherSpottedCache.group(1); - trackable.spottedName = matcherSpottedCache.group(2); - trackable.spottedType = cgTrackable.SPOTTED_CACHE; + trackable.setSpottedGuid(matcherSpottedCache.group(1)); + trackable.setSpottedName(matcherSpottedCache.group(2).trim()); + trackable.setSpottedType(cgTrackable.SPOTTED_CACHE); } final Matcher matcherSpottedUser = PATTERN_TRACKABLE_SpottedUser.matcher(page); if (matcherSpottedUser.find() && matcherSpottedUser.groupCount() > 0) { - trackable.spottedGuid = matcherSpottedUser.group(1); - trackable.spottedName = matcherSpottedUser.group(2); - trackable.spottedType = cgTrackable.SPOTTED_USER; + trackable.setSpottedGuid(matcherSpottedUser.group(1)); + trackable.setSpottedName(matcherSpottedUser.group(2).trim()); + trackable.setSpottedType(cgTrackable.SPOTTED_USER); } final Matcher matcherSpottedUnknown = PATTERN_TRACKABLE_SpottedUnknown.matcher(page); if (matcherSpottedUnknown.find()) { - trackable.spottedType = cgTrackable.SPOTTED_UNKNOWN; + trackable.setSpottedType(cgTrackable.SPOTTED_UNKNOWN); } final Matcher matcherSpottedOwner = PATTERN_TRACKABLE_SpottedOwner.matcher(page); if (matcherSpottedOwner.find()) { - trackable.spottedType = cgTrackable.SPOTTED_OWNER; + trackable.setSpottedType(cgTrackable.SPOTTED_OWNER); } } catch (Exception e) { // failed to parse trackable last known place @@ -1839,16 +1846,16 @@ public class cgBase { final Matcher matcherReleased = PATTERN_TRACKABLE_Released.matcher(page); if (matcherReleased.find() && matcherReleased.groupCount() > 0 && matcherReleased.group(1) != null) { try { - if (trackable.released == null) { - trackable.released = dateTbIn1.parse(matcherReleased.group(1)); + if (trackable.getReleased() == null) { + trackable.setReleased(dateTbIn1.parse(matcherReleased.group(1))); } } catch (Exception e) { // } try { - if (trackable.released == null) { - trackable.released = dateTbIn2.parse(matcherReleased.group(1)); + if (trackable.getReleased() == null) { + trackable.setReleased(dateTbIn2.parse(matcherReleased.group(1))); } } catch (Exception e) { // @@ -1864,9 +1871,9 @@ public class cgBase { final Matcher matcherDistance = PATTERN_TRACKABLE_Distance.matcher(page); if (matcherDistance.find() && matcherDistance.groupCount() > 0) { try { - trackable.distance = DistanceParser.parseDistance(matcherDistance.group(1), Settings.isUseMetricUnits()); + trackable.setDistance(DistanceParser.parseDistance(matcherDistance.group(1), Settings.isUseMetricUnits())); } catch (NumberFormatException e) { - trackable.distance = null; + trackable.setDistance(null); throw e; } } @@ -1877,9 +1884,9 @@ public class cgBase { // trackable goal try { - final Matcher matcherGoal = PATTERN_TRACKABLE_Goal.matcher(page); + final Matcher matcherGoal = PATTERN_TRACKABLE_GOAL.matcher(page); if (matcherGoal.find() && matcherGoal.groupCount() > 0) { - trackable.goal = matcherGoal.group(1); + trackable.setGoal(matcherGoal.group(1).trim()); } } catch (Exception e) { // failed to parse trackable goal @@ -1888,16 +1895,16 @@ public class cgBase { // trackable details & image try { - final Matcher matcherDetailsImage = PATTERN_TRACKABLE_DetailsImage.matcher(page); + final Matcher matcherDetailsImage = PATTERN_TRACKABLE_DETAILSIMAGE.matcher(page); if (matcherDetailsImage.find() && matcherDetailsImage.groupCount() > 0) { - final String image = matcherDetailsImage.group(3); - final String details = matcherDetailsImage.group(4); + final String image = matcherDetailsImage.group(3).trim(); + final String details = matcherDetailsImage.group(4).trim(); if (image != null) { - trackable.image = image; + trackable.setImage(image); } - if (details != null) { - trackable.details = details; + if (details != null && !details.equals("No additional details available.")) { + trackable.setDetails(details); } } } catch (Exception e) { @@ -1923,14 +1930,14 @@ public class cgBase { if (logTypes.containsKey(matcherLogs.group(1).toLowerCase())) { - logDone.type = logTypes.get(matcherLogs.group(1).toLowerCase()); + logDone.type = logTypes.get(matcherLogs.group(1).toLowerCase().trim()); } else { logDone.type = logTypes.get("icon_note"); } - logDone.author = Html.fromHtml(matcherLogs.group(3)).toString(); + logDone.author = Html.fromHtml(matcherLogs.group(3)).toString().trim(); try { @@ -1946,7 +1953,7 @@ public class cgBase { logDone.cacheName = matcherLogs.group(5); } - trackable.logs.add(logDone); + trackable.getLogs().add(logDone); } } catch (Exception e) { // failed to parse logs @@ -2021,32 +2028,32 @@ public class cgBase { final Matcher trackableMatcher = trackablePattern.matcher(page); while (trackableMatcher.find()) { if (trackableMatcher.groupCount() > 0) { - final cgTrackableLog trackable = new cgTrackableLog(); + final cgTrackableLog trackableLog = new cgTrackableLog(); if (trackableMatcher.group(1) != null) { - trackable.trackCode = trackableMatcher.group(1); + trackableLog.trackCode = trackableMatcher.group(1); } else { continue; } if (trackableMatcher.group(2) != null) { - trackable.name = Html.fromHtml(trackableMatcher.group(2)).toString(); + trackableLog.name = Html.fromHtml(trackableMatcher.group(2)).toString(); } else { continue; } if (trackableMatcher.group(3) != null) { - trackable.ctl = Integer.valueOf(trackableMatcher.group(3)); + trackableLog.ctl = Integer.valueOf(trackableMatcher.group(3)); } else { continue; } if (trackableMatcher.group(5) != null) { - trackable.id = Integer.valueOf(trackableMatcher.group(5)); + trackableLog.id = Integer.valueOf(trackableMatcher.group(5)); } else { continue; } - Log.i(Settings.tag, "Trackable in inventory (#" + trackable.ctl + "/" + trackable.id + "): " + trackable.trackCode + " - " + trackable.name); + Log.i(Settings.tag, "Trackable in inventory (#" + trackableLog.ctl + "/" + trackableLog.id + "): " + trackableLog.trackCode + " - " + trackableLog.name); - trackables.add(trackable); + trackables.add(trackableLog); } } @@ -2164,7 +2171,7 @@ public class cgBase { setViewstates(viewstates, params); String page = getResponseData(postRequest(uri, params)); - if (checkLogin(page) == false) { + if (!checkLogin(page)) { final StatusCode loginState = login(); if (loginState == StatusCode.NO_ERROR) { page = getResponseData(postRequest(uri, params)); @@ -2183,7 +2190,7 @@ public class cgBase { } final cgCacheWrap caches = parseSearch(thread, url, page, showCaptcha); - if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) { + if (caches == null || CollectionUtils.isEmpty(caches.cacheList)) { Log.e(Settings.tag, "cgeoBase.searchByNextPage: No cache parsed"); return searchId; } @@ -2211,7 +2218,7 @@ public class cgBase { return null; } - if (forceReload == false && reason == 0 && (app.isOffline(geocode, guid) || app.isThere(geocode, guid, true, true))) { + if (!forceReload && reason == 0 && (app.isOffline(geocode, guid) || app.isThere(geocode, guid, true, true))) { final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : app.getGeocode(guid); List<cgCache> cacheList = new ArrayList<cgCache>(); @@ -2275,7 +2282,7 @@ public class cgBase { } final cgCacheWrap caches = parseSearch(thread, fullUri, page, showCaptcha); - if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) { + if (caches == null || CollectionUtils.isEmpty(caches.cacheList)) { Log.e(Settings.tag, "cgeoBase.searchByAny: No cache parsed"); } @@ -2284,7 +2291,7 @@ public class cgBase { return null; } - List<cgCache> cacheList = processSearchResults(search, caches, Settings.isExcludeDisabledCaches(), false, null); + List<cgCache> cacheList = filterSearchResults(search, caches, Settings.isExcludeDisabledCaches(), false, null); app.addSearch(search, cacheList, true, reason); @@ -2349,7 +2356,7 @@ public class cgBase { } final cgCacheWrap caches = parseMapJSON(Uri.parse(uri).buildUpon().encodedQuery(params).build().toString(), page); - if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) { + if (caches == null || CollectionUtils.isEmpty(caches.cacheList)) { Log.e(Settings.tag, "cgeoBase.searchByViewport: No cache parsed"); } @@ -2358,7 +2365,7 @@ public class cgBase { return null; } - List<cgCache> cacheList = processSearchResults(search, caches, Settings.isExcludeDisabledCaches(), Settings.isExcludeMyCaches(), Settings.getCacheType()); + List<cgCache> cacheList = filterSearchResults(search, caches, Settings.isExcludeDisabledCaches(), Settings.isExcludeMyCaches(), Settings.getCacheType()); app.addSearch(search, cacheList, true, reason); @@ -2441,7 +2448,7 @@ public class cgBase { return users; } - public static List<cgCache> processSearchResults(final cgSearch search, final cgCacheWrap caches, final boolean excludeDisabled, final boolean excludeMine, final String cacheType) { + public static List<cgCache> filterSearchResults(final cgSearch search, final cgCacheWrap caches, final boolean excludeDisabled, final boolean excludeMine, final String cacheType) { List<cgCache> cacheList = new ArrayList<cgCache>(); if (caches != null) { if (caches.error != null) { @@ -2454,11 +2461,12 @@ public class cgBase { search.totalCnt = caches.totalCnt; if (CollectionUtils.isNotEmpty(caches.cacheList)) { - for (cgCache cache : caches.cacheList) { - if ((!excludeDisabled || (excludeDisabled && cache.disabled == false)) - && (!excludeMine || (excludeMine && cache.own == false)) - && (!excludeMine || (excludeMine && cache.found == false)) - && (cacheType == null || (cacheType.equals(cache.type)))) { + 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)); + if (!excludeCache) { search.addGeocode(cache.geocode); cacheList.add(cache); } @@ -2509,7 +2517,7 @@ public class cgBase { return StatusCode.LOG_POST_ERROR; } - if (logTypes2.containsKey(logType) == false) { + if (!logTypes2.containsKey(logType)) { Log.e(Settings.tag, "cgeoBase.postLog: Unknown logtype"); return StatusCode.LOG_POST_ERROR; } @@ -2556,7 +2564,7 @@ public class cgBase { "ctl00$ContentBody$LogBookPanel1$LogButton", "Submit Log Entry", "ctl00$ContentBody$uxVistOtherListingGC", ""); setViewstates(viewstates, params); - if (trackables != null && trackables.isEmpty() == false) { // we have some trackables to proceed + if (CollectionUtils.isNotEmpty(trackables)) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (cgTrackableLog tb : trackables) { @@ -2610,7 +2618,7 @@ public class cgBase { params.put("ctl00$ContentBody$LogBookPanel1$btnConfirm", "Yes"); params.put("ctl00$ContentBody$LogBookPanel1$uxLogInfo", logInfo); params.put("ctl00$ContentBody$uxVistOtherListingGC", ""); - if (trackables != null && trackables.isEmpty() == false) { // we have some trackables to proceed + if (CollectionUtils.isNotEmpty(trackables)) { // we have some trackables to proceed final StringBuilder hdnSelected = new StringBuilder(); for (cgTrackableLog tb : trackables) { @@ -2667,7 +2675,7 @@ public class cgBase { return StatusCode.LOG_POST_ERROR; } - if (logTypes2.containsKey(logType) == false) { + if (!logTypes2.containsKey(logType)) { Log.e(Settings.tag, "cgeoBase.postLogTrackable: Unknown logtype"); return StatusCode.LOG_POST_ERROR; } @@ -2704,7 +2712,7 @@ public class cgBase { final String uri = new Uri.Builder().scheme("http").authority("www.geocaching.com").path("/track/log.aspx").encodedQuery("wid=" + tbid).build().toString(); String page = getResponseData(postRequest(uri, params)); - if (checkLogin(page) == false) { + if (!checkLogin(page)) { final StatusCode loginState = login(); if (loginState == StatusCode.NO_ERROR) { page = getResponseData(postRequest(uri, params)); @@ -2824,7 +2832,7 @@ public class cgBase { public static void postTweetTrackable(cgeoapplication app, String geocode) { final cgTrackable trackable = app.getTrackableByGeocode(geocode); - String name = trackable.name; + String name = trackable.getName(); if (name.length() > 82) { name = name.substring(0, 79) + "..."; } @@ -2917,7 +2925,7 @@ public class cgBase { HttpResponse response = request(uri, params, xContentType, my, addF); String data = getResponseData(response); - if (checkLogin(data) == false) { + if (!checkLogin(data)) { if (login() == StatusCode.NO_ERROR) { response = request(uri, params, xContentType, my, addF); data = getResponseData(response); @@ -3486,9 +3494,7 @@ public class cgBase { return null; } - String status = response.getString("status"); - - if (status == null || status.equalsIgnoreCase("OK") == false) { + if (!StringUtils.equalsIgnoreCase(response.getString("status"), "OK")) { return null; } diff --git a/main/src/cgeo/geocaching/cgCache.java b/main/src/cgeo/geocaching/cgCache.java index 3515286..e800600 100644 --- a/main/src/cgeo/geocaching/cgCache.java +++ b/main/src/cgeo/geocaching/cgCache.java @@ -6,6 +6,7 @@ import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.geopoint.Geopoint; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; @@ -96,7 +97,7 @@ public class cgCache implements ICache { } updated = System.currentTimeMillis(); - if (detailed == false && other.detailed) { + if (!detailed && other.detailed) { detailed = true; detailedUpdate = updated; } @@ -164,7 +165,7 @@ public class cgCache implements ICache { if (elevation == null) { elevation = other.elevation; } - if (StringUtils.isBlank(personalNote)) { + if (personalNote == null) { // don't use StringUtils.isBlank. Otherwise we cannot recognize a note which was deleted on GC personalNote = other.personalNote; } if (StringUtils.isBlank(shortdesc)) { @@ -205,7 +206,7 @@ public class cgCache implements ICache { inventory = other.inventory; inventoryItems = other.inventoryItems; } - if (logs == null || logs.isEmpty()) { // keep last known logs if none + if (CollectionUtils.isEmpty(logs)) { // keep last known logs if none logs = other.logs; } } diff --git a/main/src/cgeo/geocaching/cgCacheListAdapter.java b/main/src/cgeo/geocaching/cgCacheListAdapter.java index 9d27491..b941d33 100644 --- a/main/src/cgeo/geocaching/cgCacheListAdapter.java +++ b/main/src/cgeo/geocaching/cgCacheListAdapter.java @@ -5,8 +5,8 @@ import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.sorting.CacheComparator; import cgeo.geocaching.sorting.DistanceComparator; import cgeo.geocaching.sorting.VisitComparator; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; @@ -39,18 +39,19 @@ import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; public class cgCacheListAdapter extends ArrayAdapter<cgCache> { - private Resources res = null; - private List<cgCache> list = null; + final private Resources res; + final private List<cgCache> list; private cgCacheView holder = null; private LayoutInflater inflater = null; - private Activity activity = null; - private cgBase base = null; + final private cgBase base; private CacheComparator statComparator = null; private boolean historic = false; private Geopoint coords = null; @@ -59,11 +60,11 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { private boolean sort = true; private int checked = 0; private boolean selectMode = false; - private static Map<String, Drawable> gcIconDrawables = new HashMap<String, Drawable>(); - private List<cgCompassMini> compasses = new ArrayList<cgCompassMini>(); - private List<cgDistanceView> distances = new ArrayList<cgDistanceView>(); - private int[] ratingBcgs = new int[3]; - private float pixelDensity = 1f; + final private static Map<String, Drawable> gcIconDrawables = new HashMap<String, Drawable>(); + final private Set<cgCompassMini> compasses = new LinkedHashSet<cgCompassMini>(); + final private Set<cgDistanceView> distances = new LinkedHashSet<cgDistanceView>(); + final private int[] ratingBcgs = new int[3]; + final private float pixelDensity; private static final int SWIPE_MIN_DISTANCE = 60; private static final int SWIPE_MAX_OFF_PATH = 100; private static final int SWIPE_DISTANCE = 80; @@ -71,22 +72,19 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { private cgFilter currentFilter = null; private List<cgCache> originalList = null; - public cgCacheListAdapter(Activity activityIn, List<cgCache> listIn, cgBase baseIn) { - super(activityIn, 0, listIn); + public cgCacheListAdapter(final Activity activity, final List<cgCache> list, final cgBase base) { + super(activity, 0, list); - res = activityIn.getResources(); - activity = activityIn; - list = listIn; - base = baseIn; + this.res = activity.getResources(); + this.list = list; + this.base = base; - DisplayMetrics metrics = new DisplayMetrics(); + final DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); pixelDensity = metrics.density; - if (gcIconDrawables == null || gcIconDrawables.isEmpty()) { - for (String cacheType : cgBase.cacheTypesInv.keySet()) { - gcIconDrawables.put(cacheType, (Drawable) activity.getResources().getDrawable(cgBase.getCacheIcon(cacheType))); - } + for (final String cacheType : cgBase.cacheTypesInv.keySet()) { + gcIconDrawables.put(cacheType, activity.getResources().getDrawable(cgBase.getCacheIcon(cacheType))); } if (Settings.isLightSkin()) { @@ -155,11 +153,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } public boolean isFilter() { - if (currentFilter != null) { - return true; - } else { - return false; - } + return currentFilter != null; } public String getFilterName() { @@ -180,17 +174,17 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return checked; } - public boolean setSelectMode(boolean status, boolean clear) { + public boolean setSelectMode(final boolean status, final boolean clear) { selectMode = status; - if (selectMode == false && clear) { - for (cgCache cache : list) { + if (!selectMode && clear) { + for (final cgCache cache : list) { cache.statusChecked = false; cache.statusCheckedView = false; } checked = 0; } else if (selectMode) { - for (cgCache cache : list) { + for (final cgCache cache : list) { cache.statusCheckedView = false; } } @@ -208,14 +202,14 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { public void switchSelectMode() { selectMode = !selectMode; - if (selectMode == false) { - for (cgCache cache : list) { + if (!selectMode) { + for (final cgCache cache : list) { cache.statusChecked = false; cache.statusCheckedView = false; } checked = 0; - } else if (selectMode) { - for (cgCache cache : list) { + } else { + for (final cgCache cache : list) { cache.statusCheckedView = false; } } @@ -244,28 +238,21 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } public void forceSort(final Geopoint coordsIn) { - if (list == null || list.isEmpty()) { - return; - } - if (sort == false) { + if (CollectionUtils.isEmpty(list) || !sort) { return; } - try { - if (statComparator != null) { - Collections.sort((List<cgCache>) list, statComparator); - } else { - if (coordsIn == null) { - return; - } - - final DistanceComparator dstComparator = new DistanceComparator(coordsIn); - Collections.sort((List<cgCache>) list, dstComparator); + if (statComparator != null) { + Collections.sort(list, statComparator); + } else { + if (coordsIn == null) { + return; } - notifyDataSetChanged(); - } catch (Exception e) { - Log.w(Settings.tag, "cgCacheListAdapter.setActualCoordinates: failed to sort caches in list"); + + final DistanceComparator dstComparator = new DistanceComparator(coordsIn); + Collections.sort(list, dstComparator); } + notifyDataSetChanged(); } public void setActualCoordinates(final Geopoint coordsIn) { @@ -275,32 +262,18 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { coords = coordsIn; - if (list != null && list.isEmpty() == false && (System.currentTimeMillis() - lastSort) > 1000 && sort) { - try { - if (statComparator != null) { - Collections.sort((List<cgCache>) list, statComparator); - } else { - final DistanceComparator dstComparator = new DistanceComparator(coordsIn); - Collections.sort((List<cgCache>) list, dstComparator); - } - notifyDataSetChanged(); - } catch (Exception e) { - Log.w(Settings.tag, "cgCacheListAdapter.setActualCoordinates: failed to sort caches in list"); - } - + if (CollectionUtils.isNotEmpty(list) && (System.currentTimeMillis() - lastSort) > 1000 && sort) { + Collections.sort(list, statComparator != null ? statComparator : new DistanceComparator(coordsIn)); + notifyDataSetChanged(); lastSort = System.currentTimeMillis(); } - if (CollectionUtils.isNotEmpty(distances)) { - for (cgDistanceView distance : distances) { - distance.update(coordsIn); - } + for (final cgDistanceView distance : distances) { + distance.update(coordsIn); } - if (CollectionUtils.isNotEmpty(compasses)) { - for (cgCompassMini compass : compasses) { - compass.updateCoords(coordsIn); - } + for (final cgCompassMini compass : compasses) { + compass.updateCoords(coordsIn); } } @@ -344,11 +317,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { setSelectMode(false, false); notifyDataSetChanged(); - if (cleared > 0 || status) { - return true; - } else { - return false; - } + return cleared > 0 || status; } @Override @@ -367,7 +336,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { View v = rowView; if (v == null) { - v = (View) inflater.inflate(R.layout.cache, null); + v = inflater.inflate(R.layout.cache, null); holder = new cgCacheView(); holder.oneCache = (RelativeLayout) v.findViewById(R.id.one_cache); @@ -430,22 +399,18 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { } } else { holder.checkbox.setChecked(false); - if (cache.statusCheckedView == false) { - holder.oneInfo.clearAnimation(); - } else { + if (cache.statusCheckedView) { moveLeft(holder, cache, false); + } else { + holder.oneInfo.clearAnimation(); } } holder.checkbox.setOnClickListener(new checkBoxListener(cache)); - if (distances.contains(holder.distance) == false) { - distances.add(holder.distance); - } + distances.add(holder.distance); holder.distance.setContent(base, cache.coords); - if (compasses.contains(holder.direction) == false) { - compasses.add(holder.direction); - } + compasses.add(holder.direction); holder.direction.setContent(cache.coords); if (cache.found && cache.logOffline) { @@ -519,17 +484,9 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { holder.directionLayout.setVisibility(View.GONE); holder.distance.clear(); - Bitmap dirImgPre = null; - Bitmap dirImg = null; - try { - dirImgPre = BitmapFactory.decodeFile(cgDirectionImg.getDirectionFile(cache.geocode).getPath()); - dirImg = dirImgPre.copy(Bitmap.Config.ARGB_8888, true); - - dirImgPre.recycle(); - dirImgPre = null; - } catch (Exception e) { - // nothing - } + final Bitmap dirImgPre = BitmapFactory.decodeFile(cgDirectionImg.getDirectionFile(cache.geocode).getPath()); + final Bitmap dirImg = dirImgPre.copy(Bitmap.Config.ARGB_8888, true); + dirImgPre.recycle(); if (dirImg != null) { if (!Settings.isLightSkin()) { @@ -686,9 +643,8 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { // tap on item public void onClick(View view) { - if (touch == false) { + if (!touch) { touch = true; - return; } @@ -705,9 +661,8 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { // long tap on item public boolean onLongClick(View view) { - if (touch == false) { + if (!touch) { touch = true; - return true; } @@ -718,7 +673,6 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { public boolean onTouch(View view, MotionEvent event) { if (gestureDetector.onTouchEvent(event)) { touch = false; - return true; } @@ -763,7 +717,7 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return true; } else if ((e1.getX() - e2.getX()) > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > Math.abs(velocityY)) { // right to left swipe - if (cache.statusChecked == false) { + if (!cache.statusChecked) { return true; } @@ -790,27 +744,8 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { private void checkChecked(int cnt) { // check how many caches are selected, if any block sorting of list - boolean statusChecked = false; - boolean statusSort = false; checked += cnt; - - if (checked > 0) { - statusChecked = false; - } else { - statusChecked = true; - } - - if (getSelectMode()) { - statusSort = false; - } else { - statusSort = true; - } - - if (statusChecked == false || statusSort == false) { - sort = false; - } else { - sort = true; - } + sort = !(checked > 0 || getSelectMode()); if (sort) { forceSort(coords); @@ -822,46 +757,34 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return; } - try { - holder.checkbox.setChecked(cache.statusChecked); + holder.checkbox.setChecked(cache.statusChecked); - // slide cache info - Animation showCheckbox = new TranslateAnimation(0, (int) (SWIPE_DISTANCE * pixelDensity), 0, 0); - showCheckbox.setRepeatCount(0); - if (force) { - showCheckbox.setDuration(0); - } else { - showCheckbox.setDuration(400); - } - showCheckbox.setFillEnabled(true); - showCheckbox.setFillAfter(true); - showCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); + // slide cache info + final Animation showCheckbox = new TranslateAnimation(0, (int) (SWIPE_DISTANCE * pixelDensity), 0, 0); + showCheckbox.setRepeatCount(0); + showCheckbox.setDuration(force ? 0 : 400); + showCheckbox.setFillEnabled(true); + showCheckbox.setFillAfter(true); + showCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); - // dim cache info - Animation dimInfo = new AlphaAnimation(1.0f, SWIPE_OPACITY); - dimInfo.setRepeatCount(0); - if (force) { - dimInfo.setDuration(0); - } else { - dimInfo.setDuration(400); - } - dimInfo.setFillEnabled(true); - dimInfo.setFillAfter(true); - dimInfo.setInterpolator(new AccelerateDecelerateInterpolator()); + // dim cache info + final Animation dimInfo = new AlphaAnimation(1.0f, SWIPE_OPACITY); + dimInfo.setRepeatCount(0); + dimInfo.setDuration(force ? 0 : 400); + dimInfo.setFillEnabled(true); + dimInfo.setFillAfter(true); + dimInfo.setInterpolator(new AccelerateDecelerateInterpolator()); - // animation set (container) - AnimationSet selectAnimation = new AnimationSet(true); - selectAnimation.setFillEnabled(true); - selectAnimation.setFillAfter(true); + // animation set (container) + final AnimationSet selectAnimation = new AnimationSet(true); + selectAnimation.setFillEnabled(true); + selectAnimation.setFillAfter(true); - selectAnimation.addAnimation(showCheckbox); - selectAnimation.addAnimation(dimInfo); + selectAnimation.addAnimation(showCheckbox); + selectAnimation.addAnimation(dimInfo); - holder.oneInfo.startAnimation(selectAnimation); - cache.statusCheckedView = true; - } catch (Exception e) { - // nothing - } + holder.oneInfo.startAnimation(selectAnimation); + cache.statusCheckedView = true; } private void moveLeft(cgCacheView holder, cgCache cache, boolean force) { @@ -869,45 +792,33 @@ public class cgCacheListAdapter extends ArrayAdapter<cgCache> { return; } - try { - holder.checkbox.setChecked(cache.statusChecked); + holder.checkbox.setChecked(cache.statusChecked); - // slide cache info - Animation hideCheckbox = new TranslateAnimation((int) (SWIPE_DISTANCE * pixelDensity), 0, 0, 0); - hideCheckbox.setRepeatCount(0); - if (force) { - hideCheckbox.setDuration(0); - } else { - hideCheckbox.setDuration(400); - } - hideCheckbox.setFillEnabled(true); - hideCheckbox.setFillAfter(true); - hideCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); + // slide cache info + final Animation hideCheckbox = new TranslateAnimation((int) (SWIPE_DISTANCE * pixelDensity), 0, 0, 0); + hideCheckbox.setRepeatCount(0); + hideCheckbox.setDuration(force ? 0 : 400); + hideCheckbox.setFillEnabled(true); + hideCheckbox.setFillAfter(true); + hideCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); - // brighten cache info - Animation brightenInfo = new AlphaAnimation(SWIPE_OPACITY, 1.0f); - brightenInfo.setRepeatCount(0); - if (force) { - brightenInfo.setDuration(0); - } else { - brightenInfo.setDuration(400); - } - brightenInfo.setFillEnabled(true); - brightenInfo.setFillAfter(true); - brightenInfo.setInterpolator(new AccelerateDecelerateInterpolator()); + // brighten cache info + final Animation brightenInfo = new AlphaAnimation(SWIPE_OPACITY, 1.0f); + brightenInfo.setRepeatCount(0); + brightenInfo.setDuration(force ? 0 : 400); + brightenInfo.setFillEnabled(true); + brightenInfo.setFillAfter(true); + brightenInfo.setInterpolator(new AccelerateDecelerateInterpolator()); - // animation set (container) - AnimationSet selectAnimation = new AnimationSet(true); - selectAnimation.setFillEnabled(true); - selectAnimation.setFillAfter(true); + // animation set (container) + final AnimationSet selectAnimation = new AnimationSet(true); + selectAnimation.setFillEnabled(true); + selectAnimation.setFillAfter(true); - selectAnimation.addAnimation(hideCheckbox); - selectAnimation.addAnimation(brightenInfo); + selectAnimation.addAnimation(hideCheckbox); + selectAnimation.addAnimation(brightenInfo); - holder.oneInfo.startAnimation(selectAnimation); - cache.statusCheckedView = false; - } catch (Exception e) { - // nothing - } + holder.oneInfo.startAnimation(selectAnimation); + cache.statusCheckedView = false; } } diff --git a/main/src/cgeo/geocaching/cgCompass.java b/main/src/cgeo/geocaching/cgCompass.java index 81fd655..eac6fac 100644 --- a/main/src/cgeo/geocaching/cgCompass.java +++ b/main/src/cgeo/geocaching/cgCompass.java @@ -153,7 +153,7 @@ public class cgCompass extends View { @Override public void run() { - while (wantStop == false) { + while (!wantStop) { try { sleep(50); } catch (Exception e) { diff --git a/main/src/cgeo/geocaching/cgCoord.java b/main/src/cgeo/geocaching/cgCoord.java index a8e6349..8f1d9cf 100644 --- a/main/src/cgeo/geocaching/cgCoord.java +++ b/main/src/cgeo/geocaching/cgCoord.java @@ -8,7 +8,7 @@ public class cgCoord { public Integer id = null; public String geocode = ""; public String type = "cache"; - public String typeSpec = "traditional"; + public String typeeSpec = "traditional"; public String name = ""; public boolean found = false; public boolean disabled = false; @@ -27,7 +27,7 @@ public class cgCoord { coords = cache.coords; name = cache.name; type = "cache"; - typeSpec = cache.type; + typeeSpec = cache.type; difficulty = cache.difficulty; terrain = cache.terrain; size = cache.size; @@ -41,6 +41,6 @@ public class cgCoord { coords = waypoint.coords; name = waypoint.name; type = "waypoint"; - typeSpec = waypoint.type; + typeeSpec = waypoint.typee.id; } } diff --git a/main/src/cgeo/geocaching/cgData.java b/main/src/cgeo/geocaching/cgData.java index 6d07c64..5687a15 100644 --- a/main/src/cgeo/geocaching/cgData.java +++ b/main/src/cgeo/geocaching/cgData.java @@ -5,8 +5,9 @@ import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Geopoint.MalformedCoordinateException; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import android.content.ContentValues; @@ -18,7 +19,6 @@ import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDoneException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteStatement; -import android.os.Environment; import android.util.Log; import java.io.File; @@ -224,7 +224,7 @@ public class cgData { } public synchronized void init() { - if (databaseRW == null || databaseRW.isOpen() == false) { + if (databaseRW == null || !databaseRW.isOpen()) { try { if (dbHelper == null) { dbHelper = new cgDbHelper(context); @@ -324,7 +324,7 @@ public class cgData { } public String backupDatabase() { - if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == false) { + if (!LocalStorage.isExternalStorageAvailable()) { Log.w(Settings.tag, "Database wasn't backed up: no external memory"); return null; } @@ -353,7 +353,7 @@ public class cgData { } public boolean restoreDatabase() { - if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) == false) { + if (!LocalStorage.isExternalStorageAvailable()) { Log.w(Settings.tag, "Database wasn't restored: no external memory"); return false; } @@ -951,7 +951,7 @@ public class cgData { index = cursor.getColumnIndex("geocode"); do { - list.add((String) cursor.getString(index)); + list.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); @@ -1012,11 +1012,11 @@ public class cgData { cursor.moveToFirst(); index = cursor.getColumnIndex("updated"); - dataUpdated = (long) cursor.getLong(index); + dataUpdated = cursor.getLong(index); index = cursor.getColumnIndex("detailedupdate"); - dataDetailedUpdate = (long) cursor.getLong(index); + dataDetailedUpdate = cursor.getLong(index); index = cursor.getColumnIndex("detailed"); - dataDetailed = (int) cursor.getInt(index); + dataDetailed = cursor.getInt(index); } } } catch (Exception e) { @@ -1038,7 +1038,7 @@ public class cgData { return false; } - if (checkTime && detailed == false && dataUpdated < (System.currentTimeMillis() - (3 * 24 * 60 * 60 * 1000))) { + if (checkTime && !detailed && dataUpdated < (System.currentTimeMillis() - (3 * 24 * 60 * 60 * 1000))) { // we want to check time for short cache, but data are older than 3 hours return false; } @@ -1090,7 +1090,7 @@ public class cgData { cursor.moveToFirst(); index = cursor.getColumnIndex("reason"); - reason = (long) cursor.getLong(index); + reason = cursor.getLong(index); } cursor.close(); @@ -1099,11 +1099,7 @@ public class cgData { Log.e(Settings.tag, "cgData.isOffline: " + e.toString()); } - if (reason >= 1) { - return true; - } else { - return false; - } + return reason >= 1; } public String getGeocodeForGuid(String guid) { @@ -1134,7 +1130,7 @@ public class cgData { cursor.moveToFirst(); index = cursor.getColumnIndex("geocode"); - geocode = (String) cursor.getString(index); + geocode = cursor.getString(index); } } } catch (Exception e) { @@ -1176,7 +1172,7 @@ public class cgData { cursor.moveToFirst(); index = cursor.getColumnIndex("cacheid"); - cacheid = (String) cursor.getString(index); + cacheid = cursor.getString(index); } } } catch (Exception e) { @@ -1272,7 +1268,7 @@ public class cgData { } } - if (cache.logCounts != null && cache.logCounts.isEmpty() == false) { + if (MapUtils.isNotEmpty(cache.logCounts)) { if (!saveLogCount(cache.geocode, cache.logCounts)) { statusOk = false; } @@ -1284,7 +1280,7 @@ public class cgData { } } - if (statusOk == false) { + if (!statusOk) { cache.detailed = false; cache.detailedUpdate = 0L; } @@ -1637,7 +1633,7 @@ public class cgData { public boolean saveLogCount(String geocode, Map<Integer, Integer> logCounts, boolean drop) { init(); - if (StringUtils.isBlank(geocode) || CollectionUtils.isEmpty(logCounts)) { + if (StringUtils.isBlank(geocode) || MapUtils.isEmpty(logCounts)) { return false; } @@ -1690,21 +1686,21 @@ public class cgData { values.put("geocode", geocode); } values.put("updated", timeStamp); - values.put("tbcode", oneTrackable.geocode); - values.put("guid", oneTrackable.guid); - values.put("title", oneTrackable.name); - values.put("owner", oneTrackable.owner); - if (oneTrackable.released != null) { - values.put("released", oneTrackable.released.getTime()); + values.put("tbcode", oneTrackable.getGeocode()); + values.put("guid", oneTrackable.getGuid()); + values.put("title", oneTrackable.getName()); + values.put("owner", oneTrackable.getOwner()); + if (oneTrackable.getReleased() != null) { + values.put("released", oneTrackable.getReleased().getTime()); } else { values.put("released", 0L); } - values.put("goal", oneTrackable.goal); - values.put("description", oneTrackable.details); + values.put("goal", oneTrackable.getGoal()); + values.put("description", oneTrackable.getDetails()); databaseRW.insert(dbTableTrackables, null, values); - saveLogs(oneTrackable.geocode, oneTrackable.logs); + saveLogs(oneTrackable.getGeocode(), oneTrackable.getLogs()); } } databaseRW.setTransactionSuccessful(); @@ -1814,7 +1810,7 @@ public class cgData { } List<cgCache> caches = loadCaches(geocodes, null, null, null, null, null, loadA, loadW, loadS, loadL, loadI, loadO); - if (caches != null && caches.isEmpty() == false) { + if (CollectionUtils.isNotEmpty(caches)) { return caches.get(0); } @@ -1939,9 +1935,13 @@ public class cgData { //Extracted Method cgCache cache = createCacheFromDatabaseContent(cursor); + // FIXME: in the following code (and similar blocks below), the + // cache.attributes entity probably does not need to be preserved, + // and the resolution of the "if" statement could be simply + // cache.attributes = attributes if (loadA) { - List<String> attributes = loadAttributes(cache.geocode); - if (attributes != null && attributes.isEmpty() == false) { + final List<String> attributes = loadAttributes(cache.geocode); + if (CollectionUtils.isNotEmpty(attributes)) { if (cache.attributes == null) { cache.attributes = new ArrayList<String>(); } else { @@ -1952,8 +1952,8 @@ public class cgData { } if (loadW) { - List<cgWaypoint> waypoints = loadWaypoints(cache.geocode); - if (waypoints != null && waypoints.isEmpty() == false) { + final List<cgWaypoint> waypoints = loadWaypoints(cache.geocode); + if (CollectionUtils.isNotEmpty(waypoints)) { if (cache.waypoints == null) { cache.waypoints = new ArrayList<cgWaypoint>(); } else { @@ -1964,8 +1964,8 @@ public class cgData { } if (loadS) { - List<cgImage> spoilers = loadSpoilers(cache.geocode); - if (spoilers != null && spoilers.isEmpty() == false) { + final List<cgImage> spoilers = loadSpoilers(cache.geocode); + if (CollectionUtils.isNotEmpty(spoilers)) { if (cache.spoilers == null) { cache.spoilers = new ArrayList<cgImage>(); } else { @@ -1976,8 +1976,8 @@ public class cgData { } if (loadL) { - List<cgLog> logs = loadLogs(cache.geocode); - if (logs != null && logs.isEmpty() == false) { + final List<cgLog> logs = loadLogs(cache.geocode); + if (CollectionUtils.isNotEmpty(logs)) { if (cache.logs == null) { cache.logs = new ArrayList<cgLog>(); } else { @@ -1985,16 +1985,16 @@ public class cgData { } cache.logs.addAll(logs); } - Map<Integer, Integer> logCounts = loadLogCounts(cache.geocode); - if (logCounts != null && logCounts.isEmpty() == false) { + final Map<Integer, Integer> logCounts = loadLogCounts(cache.geocode); + if (MapUtils.isNotEmpty(logCounts)) { cache.logCounts.clear(); cache.logCounts.putAll(logCounts); } } if (loadI) { - List<cgTrackable> inventory = loadInventory(cache.geocode); - if (inventory != null && inventory.isEmpty() == false) { + final List<cgTrackable> inventory = loadInventory(cache.geocode); + if (CollectionUtils.isNotEmpty(inventory)) { if (cache.inventory == null) { cache.inventory = new ArrayList<cgTrackable>(); } else { @@ -2037,22 +2037,22 @@ public class cgData { int index; cgCache cache = new cgCache(); - cache.updated = (long) cursor.getLong(cursor.getColumnIndex("updated")); - cache.reason = (int) cursor.getInt(cursor.getColumnIndex("reason")); + cache.updated = cursor.getLong(cursor.getColumnIndex("updated")); + cache.reason = cursor.getInt(cursor.getColumnIndex("reason")); cache.detailed = cursor.getInt(cursor.getColumnIndex("detailed")) == 1; cache.detailedUpdate = (Long) cursor.getLong(cursor.getColumnIndex("detailedupdate")); cache.visitedDate = (Long) cursor.getLong(cursor.getColumnIndex("visiteddate")); - cache.geocode = (String) cursor.getString(cursor.getColumnIndex("geocode")); - cache.cacheId = (String) cursor.getString(cursor.getColumnIndex("cacheid")); - cache.guid = (String) cursor.getString(cursor.getColumnIndex("guid")); - cache.type = (String) cursor.getString(cursor.getColumnIndex("type")); - cache.name = (String) cursor.getString(cursor.getColumnIndex("name")); + cache.geocode = cursor.getString(cursor.getColumnIndex("geocode")); + cache.cacheId = cursor.getString(cursor.getColumnIndex("cacheid")); + cache.guid = cursor.getString(cursor.getColumnIndex("guid")); + cache.type = cursor.getString(cursor.getColumnIndex("type")); + cache.name = cursor.getString(cursor.getColumnIndex("name")); cache.own = cursor.getInt(cursor.getColumnIndex("own")) == 1; - cache.owner = (String) cursor.getString(cursor.getColumnIndex("owner")); - cache.ownerReal = (String) cursor.getString(cursor.getColumnIndex("owner_real")); - cache.hidden = new Date((long) cursor.getLong(cursor.getColumnIndex("hidden"))); - cache.hint = (String) cursor.getString(cursor.getColumnIndex("hint")); - cache.size = CacheSize.FIND_BY_ID.get((String) cursor.getString(cursor.getColumnIndex("size"))); + cache.owner = cursor.getString(cursor.getColumnIndex("owner")); + cache.ownerReal = cursor.getString(cursor.getColumnIndex("owner_real")); + cache.hidden = new Date(cursor.getLong(cursor.getColumnIndex("hidden"))); + cache.hint = cursor.getString(cursor.getColumnIndex("hint")); + cache.size = CacheSize.FIND_BY_ID.get(cursor.getString(cursor.getColumnIndex("size"))); cache.difficulty = (Float) cursor.getFloat(cursor.getColumnIndex("difficulty")); index = cursor.getColumnIndex("direction"); if (cursor.isNull(index)) { @@ -2067,8 +2067,8 @@ public class cgData { cache.distance = cursor.getFloat(index); } cache.terrain = (Float) cursor.getFloat(cursor.getColumnIndex("terrain")); - cache.latlon = (String) cursor.getString(cursor.getColumnIndex("latlon")); - cache.location = (String) cursor.getString(cursor.getColumnIndex("location")); + cache.latlon = cursor.getString(cursor.getColumnIndex("latlon")); + cache.location = cursor.getString(cursor.getColumnIndex("location")); cache.coords = getCoords(cursor); index = cursor.getColumnIndex("elevation"); if (cursor.isNull(index)) { @@ -2076,8 +2076,8 @@ public class cgData { } else { cache.elevation = (Double) cursor.getDouble(index); } - cache.personalNote = (String) cursor.getString(cursor.getColumnIndex("personal_note")); - cache.shortdesc = (String) cursor.getString(cursor.getColumnIndex("shortdesc")); + cache.personalNote = cursor.getString(cursor.getColumnIndex("personal_note")); + cache.shortdesc = cursor.getString(cursor.getColumnIndex("shortdesc")); // do not set cache.description ! cache.favouriteCnt = (Integer) cursor.getInt(cursor.getColumnIndex("favourite_cnt")); cache.rating = (Float) cursor.getFloat(cursor.getColumnIndex("rating")); @@ -2118,7 +2118,7 @@ public class cgData { int index = cursor.getColumnIndex("attribute"); do { - attributes.add((String) cursor.getString(index)); + attributes.add(cursor.getString(index)); } while (cursor.moveToNext()); } @@ -2200,15 +2200,16 @@ public class cgData { private static cgWaypoint createWaypointFromDatabaseContent(Cursor cursor) { cgWaypoint waypoint = new cgWaypoint(); - waypoint.id = (int) cursor.getInt(cursor.getColumnIndex("_id")); - waypoint.geocode = (String) cursor.getString(cursor.getColumnIndex("geocode")); - waypoint.typee = WaypointType.FIND_BY_ID.get((String) cursor.getString(cursor.getColumnIndex("type"))); - waypoint.setPrefix((String) cursor.getString(cursor.getColumnIndex("prefix"))); - waypoint.lookup = (String) cursor.getString(cursor.getColumnIndex("lookup")); - waypoint.name = (String) cursor.getString(cursor.getColumnIndex("name")); - waypoint.latlon = (String) cursor.getString(cursor.getColumnIndex("latlon")); + + waypoint.id = cursor.getInt(cursor.getColumnIndex("_id")); + waypoint.geocode = cursor.getString(cursor.getColumnIndex("geocode")); + waypoint.typee = 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 = (String) cursor.getString(cursor.getColumnIndex("note")); + waypoint.note = cursor.getString(cursor.getColumnIndex("note")); return waypoint; } @@ -2240,9 +2241,9 @@ public class cgData { do { cgImage spoiler = new cgImage(); - spoiler.url = (String) cursor.getString(indexUrl); - spoiler.title = (String) cursor.getString(indexTitle); - spoiler.description = (String) cursor.getString(indexDescription); + spoiler.url = cursor.getString(indexUrl); + spoiler.title = cursor.getString(indexTitle); + spoiler.description = cursor.getString(indexDescription); spoilers.add(spoiler); } while (cursor.moveToNext()); @@ -2284,8 +2285,8 @@ public class cgData { do { final cgDestination dest = new cgDestination(); - dest.setId((long) cursor.getLong(indexId)); - dest.setDate((long) cursor.getLong(indexDate)); + dest.setId(cursor.getLong(indexId)); + dest.setDate(cursor.getLong(indexDate)); dest.setCoords(getCoords(cursor, indexLatitude, indexLongitude)); // If coordinates are non-existent or invalid, do not consider @@ -2349,21 +2350,21 @@ public class cgData { while (cursor.moveToNext() && logs.size() < 100) { if (log == null || log.id != cursor.getInt(indexLogsId)) { log = new cgLog(); - log.id = (int) cursor.getInt(indexLogsId); - log.type = (int) cursor.getInt(indexType); - log.author = (String) cursor.getString(indexAuthor); - log.log = (String) cursor.getString(indexLog); - log.date = (long) cursor.getLong(indexDate); - log.found = (int) cursor.getInt(indexFound); + log.id = cursor.getInt(indexLogsId); + log.type = cursor.getInt(indexType); + log.author = cursor.getString(indexAuthor); + log.log = cursor.getString(indexLog); + log.date = cursor.getLong(indexDate); + log.found = cursor.getInt(indexFound); logs.add(log); } if (!cursor.isNull(indexLogImagesId)) { final cgImage log_img = new cgImage(); - log_img.title = (String) cursor.getString(indexTitle); + log_img.title = cursor.getString(indexTitle); if (log_img.title == null) { log_img.title = ""; } - log_img.url = (String) cursor.getString(indexUrl); + log_img.url = cursor.getString(indexUrl); if (log_img.url == null) { log_img.url = ""; } @@ -2490,19 +2491,19 @@ public class cgData { private cgTrackable createTrackableFromDatabaseContent(Cursor cursor) { cgTrackable trackable = new cgTrackable(); - trackable.geocode = (String) cursor.getString(cursor.getColumnIndex("tbcode")); - trackable.guid = (String) cursor.getString(cursor.getColumnIndex("guid")); - trackable.name = (String) cursor.getString(cursor.getColumnIndex("title")); - trackable.owner = (String) cursor.getString(cursor.getColumnIndex("owner")); + trackable.setGeocode(cursor.getString(cursor.getColumnIndex("tbcode"))); + trackable.setGuid(cursor.getString(cursor.getColumnIndex("guid"))); + trackable.setName(cursor.getString(cursor.getColumnIndex("title"))); + trackable.setOwner(cursor.getString(cursor.getColumnIndex("owner"))); String releasedPre = cursor.getString(cursor.getColumnIndex("released")); if (releasedPre != null && Long.getLong(releasedPre) != null) { - trackable.released = new Date(Long.getLong(releasedPre)); + trackable.setReleased(new Date(Long.getLong(releasedPre))); } else { - trackable.released = null; + trackable.setReleased(null); } - trackable.goal = (String) cursor.getString(cursor.getColumnIndex("goal")); - trackable.details = (String) cursor.getString(cursor.getColumnIndex("description")); - trackable.logs = loadLogs(trackable.geocode); + trackable.setGoal(cursor.getString(cursor.getColumnIndex("goal"))); + trackable.setDetails(cursor.getString(cursor.getColumnIndex("description"))); + trackable.setLogs(loadLogs(trackable.getGeocode())); return trackable; } @@ -2522,7 +2523,7 @@ public class cgData { int count = 0; try { String sql = "select count(_id) from " + dbTableCaches; // this default is not used, but we like to have variables initialized - if (detailedOnly == false) { + if (!detailedOnly) { if (cachetype == null) { sql = "select count(_id) from " + dbTableCaches + listSql; } else { @@ -2599,7 +2600,7 @@ public class cgData { int index = cursor.getColumnIndex("geocode"); do { - geocodes.add((String) cursor.getString(index)); + geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); @@ -2650,7 +2651,7 @@ public class cgData { int index = cursor.getColumnIndex("geocode"); do { - geocodes.add((String) cursor.getString(index)); + geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); @@ -2740,7 +2741,7 @@ public class cgData { int index = cursor.getColumnIndex("geocode"); do { - geocodes.add((String) cursor.getString(index)); + geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); @@ -2792,7 +2793,7 @@ public class cgData { int index = cursor.getColumnIndex("geocode"); do { - geocodes.add((String) cursor.getString(index)); + geocodes.add(cursor.getString(index)); } while (cursor.moveToNext()); } else { cursor.close(); @@ -3043,10 +3044,10 @@ public class cgData { cursor.moveToFirst(); log = new cgLog(); - log.id = (int) cursor.getInt(cursor.getColumnIndex("_id")); - log.type = (int) cursor.getInt(cursor.getColumnIndex("type")); - log.log = (String) cursor.getString(cursor.getColumnIndex("log")); - log.date = (long) cursor.getLong(cursor.getColumnIndex("date")); + log.id = cursor.getInt(cursor.getColumnIndex("_id")); + log.type = cursor.getInt(cursor.getColumnIndex("type")); + log.log = cursor.getString(cursor.getColumnIndex("log")); + log.date = cursor.getLong(cursor.getColumnIndex("date")); } if (cursor != null) { @@ -3164,8 +3165,8 @@ public class cgData { do { cgList list = new cgList(false); - list.id = ((int) cursor.getInt(indexId)) + 10; - list.title = (String) cursor.getString(indexTitle); + list.id = (cursor.getInt(indexId)) + 10; + list.title = cursor.getString(indexTitle); list.updated = (Long) cursor.getLong(indexUpdated); list.coords = getCoords(cursor, indexLatitude, indexLongitude); @@ -3239,7 +3240,7 @@ public class cgData { values.put("title", name); values.put("updated", System.currentTimeMillis()); - count = (int) databaseRW.update(dbTableLists, values, "_id = " + (listId - 10), null); + count = databaseRW.update(dbTableLists, values, "_id = " + (listId - 10), null); databaseRW.setTransactionSuccessful(); } finally { databaseRW.endTransaction(); @@ -3294,7 +3295,7 @@ public class cgData { } public synchronized boolean status() { - if (databaseRO == null || databaseRW == null || initialized == false) { + if (databaseRO == null || databaseRW == null || !initialized) { return false; } diff --git a/main/src/cgeo/geocaching/cgGPXListAdapter.java b/main/src/cgeo/geocaching/cgGPXListAdapter.java index 92d701f..786d1f2 100644 --- a/main/src/cgeo/geocaching/cgGPXListAdapter.java +++ b/main/src/cgeo/geocaching/cgGPXListAdapter.java @@ -37,7 +37,7 @@ public class cgGPXListAdapter extends ArrayAdapter<File> { View v = rowView; if (v == null) { - v = (View) inflater.inflate(R.layout.gpx_item, null); + v = inflater.inflate(R.layout.gpx_item, null); holder = new cgGPXView(); holder.filepath = (TextView) v.findViewById(R.id.filepath); @@ -57,11 +57,6 @@ public class cgGPXListAdapter extends ArrayAdapter<File> { return v; } - @Override - public void notifyDataSetChanged() { - super.notifyDataSetChanged(); - } - private class touchListener implements View.OnClickListener { private File file = null; diff --git a/main/src/cgeo/geocaching/cgGeo.java b/main/src/cgeo/geocaching/cgGeo.java index f54ece2..3a2c09d 100644 --- a/main/src/cgeo/geocaching/cgGeo.java +++ b/main/src/cgeo/geocaching/cgGeo.java @@ -126,7 +126,7 @@ public class cgGeo { } final SharedPreferences.Editor prefsEdit = context.getSharedPreferences(Settings.preferences, 0).edit(); - if (prefsEdit != null && Double.isNaN(distanceNow) == false) { + if (prefsEdit != null && !Double.isNaN(distanceNow)) { prefsEdit.putFloat("dst", (float) distanceNow); prefsEdit.commit(); } diff --git a/main/src/cgeo/geocaching/cgMapfileListAdapter.java b/main/src/cgeo/geocaching/cgMapfileListAdapter.java index e52e517..dbac179 100644 --- a/main/src/cgeo/geocaching/cgMapfileListAdapter.java +++ b/main/src/cgeo/geocaching/cgMapfileListAdapter.java @@ -39,7 +39,7 @@ public class cgMapfileListAdapter extends ArrayAdapter<File> { View v = rowView; if (v == null) { - v = (View) inflater.inflate(R.layout.mapfile_item, null); + v = inflater.inflate(R.layout.mapfile_item, null); holder = new MapfileView(); holder.filepath = (TextView) v.findViewById(R.id.mapfilepath); @@ -67,11 +67,6 @@ public class cgMapfileListAdapter extends ArrayAdapter<File> { return v; } - @Override - public void notifyDataSetChanged() { - super.notifyDataSetChanged(); - } - private class touchListener implements View.OnClickListener { private File file = null; diff --git a/main/src/cgeo/geocaching/cgSearchThread.java b/main/src/cgeo/geocaching/cgSearchThread.java index 0d802f3..3daddc5 100644 --- a/main/src/cgeo/geocaching/cgSearchThread.java +++ b/main/src/cgeo/geocaching/cgSearchThread.java @@ -3,7 +3,7 @@ package cgeo.geocaching; import android.os.Handler; import android.util.Log; -public class cgSearchThread extends Thread { +abstract public class cgSearchThread extends Thread { private Handler recaptchaHandler = null; private String recaptchaChallenge = null; private String recaptchaText = null; diff --git a/main/src/cgeo/geocaching/cgTrackable.java b/main/src/cgeo/geocaching/cgTrackable.java index 2a46ed2..29001a8 100644 --- a/main/src/cgeo/geocaching/cgTrackable.java +++ b/main/src/cgeo/geocaching/cgTrackable.java @@ -2,8 +2,6 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.StatusCode; -import android.text.Spannable; - import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -15,29 +13,185 @@ public class cgTrackable { static final public int SPOTTED_UNKNOWN = 3; static final public int SPOTTED_OWNER = 4; - public StatusCode errorRetrieve = null; - public String error = ""; - public String guid = ""; - public String geocode = ""; - public String iconUrl = ""; - public String name = ""; - public String nameString = null; - public Spannable nameSp = null; - public String type = null; - public Date released = null; - public Float distance = null; - public String origin = null; - public String owner = null; - public String ownerGuid = null; - public String spottedName = null; - public int spottedType = SPOTTED_UNSET; - public String spottedGuid = null; - public String goal = null; - public String details = null; - public String image = null; - public List<cgLog> logs = new ArrayList<cgLog>(); + private StatusCode errorRetrieve = null; + private String error = ""; + private String guid = ""; + private String geocode = ""; + private String iconUrl = ""; + private String name = ""; + private String type = null; + private Date released = null; + private Float distance = null; + private String origin = null; + private String owner = null; + private String ownerGuid = null; + private String spottedName = null; + private int spottedType = SPOTTED_UNSET; + private String spottedGuid = null; + private String goal = null; + private String details = null; + private String image = null; + private List<cgLog> logs = new ArrayList<cgLog>(); public String getUrl() { return "http://coord.info/" + geocode.toUpperCase(); } + + public StatusCode getErrorRetrieve() { + return errorRetrieve; + } + + /* + * unused + * public void setErrorRetrieve(StatusCode errorRetrieve) { + * this.errorRetrieve = errorRetrieve; + * } + */ + + public String getError() { + return error; + } + + /* + * Unused + * public void setError(String error) { + * this.error = error; + * } + */ + + public String getGuid() { + return guid; + } + + public void setGuid(String guid) { + this.guid = guid; + } + + public String getGeocode() { + return geocode; + } + + public void setGeocode(String geocode) { + this.geocode = geocode; + } + + public String getIconUrl() { + return iconUrl; + } + + public void setIconUrl(String iconUrl) { + this.iconUrl = iconUrl; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public Date getReleased() { + return released; + } + + public void setReleased(Date released) { + this.released = released; + } + + public Float getDistance() { + return distance; + } + + public void setDistance(Float distance) { + this.distance = distance; + } + + public String getOrigin() { + return origin; + } + + public void setOrigin(String origin) { + this.origin = origin; + } + + public String getOwner() { + return owner; + } + + public void setOwner(String owner) { + this.owner = owner; + } + + public String getOwnerGuid() { + return ownerGuid; + } + + public void setOwnerGuid(String ownerGuid) { + this.ownerGuid = ownerGuid; + } + + public String getSpottedName() { + return spottedName; + } + + public void setSpottedName(String spottedName) { + this.spottedName = spottedName; + } + + public int getSpottedType() { + return spottedType; + } + + public void setSpottedType(int spottedType) { + this.spottedType = spottedType; + } + + public String getSpottedGuid() { + return spottedGuid; + } + + public void setSpottedGuid(String spottedGuid) { + this.spottedGuid = spottedGuid; + } + + public String getGoal() { + return goal; + } + + public void setGoal(String goal) { + this.goal = goal; + } + + public String getDetails() { + return details; + } + + public void setDetails(String details) { + this.details = details; + } + + public String getImage() { + return image; + } + + public void setImage(String image) { + this.image = image; + } + + public List<cgLog> getLogs() { + return logs; + } + + public void setLogs(List<cgLog> logs) { + this.logs = logs; + } } diff --git a/main/src/cgeo/geocaching/cgeo.java b/main/src/cgeo/geocaching/cgeo.java index 5c8c9f1..6893f34 100644 --- a/main/src/cgeo/geocaching/cgeo.java +++ b/main/src/cgeo/geocaching/cgeo.java @@ -4,8 +4,8 @@ import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.content.Context; @@ -285,9 +285,7 @@ public class cgeo extends AbstractActivity { context.startActivity(new Intent(context, cgeoinit.class)); return true; case MENU_HISTORY: - final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra("type", "history"); - context.startActivity(cachesIntent); + cgeocaches.startActivityHistory(context); return true; case MENU_SCAN: Intent intent = new Intent(SCAN_INTENT); @@ -450,7 +448,7 @@ public class cgeo extends AbstractActivity { (new countBubbleUpdate()).start(); (new cleanDatabase()).start(); - if (Settings.getCacheType() != null && cgBase.cacheTypesInv.containsKey(Settings.getCacheType()) == false) { + if (Settings.getCacheType() != null && !cgBase.cacheTypesInv.containsKey(Settings.getCacheType())) { Settings.setCacheType(null); } @@ -567,7 +565,7 @@ public class cgeo extends AbstractActivity { if (addCoords == null) { navLocation.setText(res.getString(R.string.loc_no_addr)); } - if (addCoords == null || (geo.coordsNow.distanceTo(addCoords) > 0.5 && addressObtaining == false)) { + if (addCoords == null || (geo.coordsNow.distanceTo(addCoords) > 0.5 && !addressObtaining)) { (new obtainAddress()).start(); } } else { @@ -619,12 +617,7 @@ public class cgeo extends AbstractActivity { } findViewById(R.id.nearest).setPressed(true); - final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra("type", "nearest"); - cachesIntent.putExtra("latitude", geo.coordsNow.getLatitude()); - cachesIntent.putExtra("longitude", geo.coordsNow.getLongitude()); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - context.startActivity(cachesIntent); + cgeocaches.startActivityNearest(context, geo.coordsNow); } /** @@ -633,9 +626,7 @@ public class cgeo extends AbstractActivity { */ public void cgeoFindByOffline(View v) { findViewById(R.id.search_offline).setPressed(true); - final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra("type", "offline"); - context.startActivity(cachesIntent); + cgeocaches.startActivityOffline(context); } /** @@ -674,7 +665,7 @@ public class cgeo extends AbstractActivity { } int checks = 0; - while (app.storageStatus() == false) { + while (!app.storageStatus()) { try { wait(500); checks++; diff --git a/main/src/cgeo/geocaching/cgeoaddresses.java b/main/src/cgeo/geocaching/cgeoaddresses.java index 8941fe2..8cf68fe 100644 --- a/main/src/cgeo/geocaching/cgeoaddresses.java +++ b/main/src/cgeo/geocaching/cgeoaddresses.java @@ -2,8 +2,9 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; +import org.apache.commons.collections.CollectionUtils; + import android.app.ProgressDialog; -import android.content.Intent; import android.location.Address; import android.location.Geocoder; import android.os.AsyncTask; @@ -72,7 +73,7 @@ public class cgeoaddresses extends AbstractActivity { addList = (LinearLayout) findViewById(R.id.address_list); } - if (addresses == null || addresses.isEmpty()) { + if (CollectionUtils.isEmpty(addresses)) { showToast(res.getString(R.string.err_search_address_no_match)); finish(); return; @@ -134,14 +135,7 @@ public class cgeoaddresses extends AbstractActivity { } public void onClick(View arg0) { - Intent addressIntent = new Intent(cgeoaddresses.this, cgeocaches.class); - addressIntent.putExtra("type", "address"); - addressIntent.putExtra("latitude", (Double) latitude); - addressIntent.putExtra("longitude", (Double) longitude); - addressIntent.putExtra("address", (String) address); - addressIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(addressIntent); - + cgeocaches.startActivityAddress(cgeoaddresses.this, latitude, longitude, address); finish(); return; } diff --git a/main/src/cgeo/geocaching/cgeoadvsearch.java b/main/src/cgeo/geocaching/cgeoadvsearch.java index 8caf67d..2a03ff4 100644 --- a/main/src/cgeo/geocaching/cgeoadvsearch.java +++ b/main/src/cgeo/geocaching/cgeoadvsearch.java @@ -129,12 +129,7 @@ public class cgeoadvsearch extends AbstractActivity { found = true; } else { // keyword (fallback) - final Intent cachesIntent = new Intent(this, cgeocaches.class); - cachesIntent.putExtra("type", "keyword"); - cachesIntent.putExtra("keyword", query); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(cachesIntent); - + cgeocaches.startActivityKeyword(this, query); found = true; } } catch (Exception e) { @@ -147,7 +142,7 @@ public class cgeoadvsearch extends AbstractActivity { private void init() { Settings.getLogin(); - if (Settings.getCacheType() != null && cgBase.cacheTypesInv.containsKey(Settings.getCacheType()) == false) { + if (Settings.getCacheType() != null && !cgBase.cacheTypesInv.containsKey(Settings.getCacheType())) { Settings.setCacheType(null); } @@ -268,12 +263,7 @@ public class cgeoadvsearch extends AbstractActivity { } } else { try { - final Intent cachesIntent = new Intent(this, cgeocaches.class); - cachesIntent.putExtra("latitude", GeopointParser.parseLatitude(latText)); - cachesIntent.putExtra("longitude", GeopointParser.parseLongitude(lonText)); - cachesIntent.putExtra("type", "coordinate"); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(cachesIntent); + cgeocaches.startActivityCoordinates(this, GeopointParser.parseLatitude(latText), GeopointParser.parseLongitude(lonText)); } catch (GeopointParser.ParseException e) { showToast(res.getString(e.resource)); } @@ -309,11 +299,7 @@ public class cgeoadvsearch extends AbstractActivity { return; } - final Intent cachesIntent = new Intent(this, cgeocaches.class); - cachesIntent.putExtra("type", "keyword"); - cachesIntent.putExtra("keyword", keyText); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(cachesIntent); + cgeocaches.startActivityKeyword(this, keyText); } private class findByAddressAction implements TextView.OnEditorActionListener { @@ -377,11 +363,7 @@ public class cgeoadvsearch extends AbstractActivity { return; } - final Intent cachesIntent = new Intent(this, cgeocaches.class); - cachesIntent.putExtra("type", "username"); - cachesIntent.putExtra("username", usernameText); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(cachesIntent); + cgeocaches.startActivityUserName(this, usernameText); } private class findByOwnerAction implements TextView.OnEditorActionListener { @@ -409,11 +391,7 @@ public class cgeoadvsearch extends AbstractActivity { return; } - final Intent cachesIntent = new Intent(this, cgeocaches.class); - cachesIntent.putExtra("type", "owner"); - cachesIntent.putExtra("username", usernameText); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - startActivity(cachesIntent); + cgeocaches.startActivityOwner(this, usernameText); } private class findByGeocodeAction implements TextView.OnEditorActionListener { diff --git a/main/src/cgeo/geocaching/cgeoapplication.java b/main/src/cgeo/geocaching/cgeoapplication.java index eb97048..7e91a01 100644 --- a/main/src/cgeo/geocaching/cgeoapplication.java +++ b/main/src/cgeo/geocaching/cgeoapplication.java @@ -3,6 +3,7 @@ package cgeo.geocaching; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.geopoint.Geopoint; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Application; @@ -138,7 +139,7 @@ public class cgeoapplication extends Application { // nothing } - if (geoInUse == false && geo != null) { + if (!geoInUse && geo != null) { geo.closeGeo(); geo = null; @@ -182,7 +183,7 @@ public class cgeoapplication extends Application { // nothing } - if (dirInUse == false && dir != null) { + if (!dirInUse && dir != null) { dir.closeDir(); dir = null; @@ -217,7 +218,7 @@ public class cgeoapplication extends Application { } public StatusCode getError(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -225,7 +226,7 @@ public class cgeoapplication extends Application { } public boolean setError(final UUID searchId, final StatusCode error) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return false; } @@ -235,7 +236,7 @@ public class cgeoapplication extends Application { } public String getUrl(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -243,7 +244,7 @@ public class cgeoapplication extends Application { } public boolean setUrl(final UUID searchId, String url) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return false; } @@ -253,7 +254,7 @@ public class cgeoapplication extends Application { } public String[] getViewstates(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -264,7 +265,7 @@ public class cgeoapplication extends Application { if (cgBase.isEmpty(viewstates)) { return false; } - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return false; } @@ -274,7 +275,7 @@ public class cgeoapplication extends Application { } public Integer getTotal(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -282,7 +283,7 @@ public class cgeoapplication extends Application { } public Integer getCount(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return 0; } @@ -290,7 +291,7 @@ public class cgeoapplication extends Application { } public Integer getNotOfflineCount(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return 0; } @@ -298,7 +299,7 @@ public class cgeoapplication extends Application { List<String> geocodes = searches.get(searchId).getGeocodes(); if (geocodes != null) { for (String geocode : geocodes) { - if (isOffline(geocode, null) == false) { + if (!isOffline(geocode, null)) { count++; } } @@ -307,6 +308,10 @@ public class cgeoapplication extends Application { return count; } + 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); } @@ -383,7 +388,7 @@ public class cgeoapplication extends Application { } public List<Object> getBounds(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -397,8 +402,8 @@ public class cgeoapplication extends Application { return getBounds(geocodeList); } - public List<Object> getBounds(List<String> geocodes) { - if (geocodes == null || geocodes.isEmpty()) { + public List<Object> getBounds(final List<String> geocodes) { + if (CollectionUtils.isEmpty(geocodes)) { return null; } @@ -406,7 +411,7 @@ public class cgeoapplication extends Application { } public cgCache getCache(final UUID searchId) { - if (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { return null; } @@ -429,7 +434,7 @@ public class cgeoapplication extends Application { } 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 (searchId == null || searches.containsKey(searchId) == false) { + if (unknownSearch(searchId)) { List<cgCache> cachesOut = new ArrayList<cgCache>(); final List<cgCache> cachesPre = storage.loadCaches(null, null, centerLat, centerLon, spanLat, spanLon, loadA, loadW, loadS, loadL, loadI, loadO); @@ -455,78 +460,51 @@ public class cgeoapplication extends Application { return cachesOut; } - public cgSearch getBatchOfStoredCaches(boolean detailedOnly, final Geopoint coords, String cachetype, int list) { - cgSearch search = new cgSearch(); - - List<String> geocodes = getStorage().loadBatchOfStoredGeocodes(detailedOnly, coords, cachetype, list); - if (geocodes != null && geocodes.isEmpty() == false) { - for (String gccode : geocodes) { + /** + * 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); + } + public List<cgDestination> getHistoryOfSearchedLocations() { return getStorage().loadHistoryOfSearchedLocations(); } public cgSearch getHistoryOfCaches(boolean detailedOnly, String cachetype) { - cgSearch search = new cgSearch(); - - List<String> geocodes = getStorage().loadBatchOfHistoricGeocodes(detailedOnly, cachetype); - if (geocodes != null && geocodes.isEmpty() == false) { - for (String gccode : geocodes) { - search.addGeocode(gccode); - } - } - searches.put(search.getCurrentId(), search); - - return search; + final List<String> geocodes = getStorage().loadBatchOfHistoricGeocodes(detailedOnly, cachetype); + return createNewSearch(geocodes); } public UUID getCachedInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { - cgSearch search = new cgSearch(); - - List<String> geocodes = getStorage().getCachedInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); - if (geocodes != null && geocodes.isEmpty() == false) { - for (String gccode : geocodes) { - search.addGeocode(gccode); - } - } - searches.put(search.getCurrentId(), search); - - return search.getCurrentId(); + final List<String> geocodes = getStorage().getCachedInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); + return createNewSearch(geocodes).getCurrentId(); } public UUID getStoredInViewport(Long centerLat, Long centerLon, Long spanLat, Long spanLon, String cachetype) { - cgSearch search = new cgSearch(); - - List<String> geocodes = getStorage().getStoredInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); - if (geocodes != null && geocodes.isEmpty() == false) { - for (String gccode : geocodes) { - search.addGeocode(gccode); - } - } - searches.put(search.getCurrentId(), search); - - return search.getCurrentId(); + final List<String> geocodes = getStorage().getStoredInViewport(centerLat, centerLon, spanLat, spanLon, cachetype); + return createNewSearch(geocodes).getCurrentId(); } public UUID getOfflineAll(String cachetype) { - cgSearch search = new cgSearch(); - - List<String> geocodes = getStorage().getOfflineAll(cachetype); - if (geocodes != null && geocodes.isEmpty() == false) { - for (String gccode : geocodes) { - search.addGeocode(gccode); - } - } - searches.put(search.getCurrentId(), search); - - return search.getCurrentId(); + final List<String> geocodes = getStorage().getOfflineAll(cachetype); + return createNewSearch(geocodes).getCurrentId(); } public int getAllStoredCachesCount(boolean detailedOnly, String cachetype, Integer list) { @@ -584,7 +562,7 @@ public class cgeoapplication extends Application { } public void addGeocode(final UUID searchId, String geocode) { - if (this.searches.containsKey(searchId) == false || StringUtils.isBlank(geocode)) { + if (!this.searches.containsKey(searchId) || StringUtils.isBlank(geocode)) { return; } @@ -592,7 +570,7 @@ public class cgeoapplication extends Application { } public UUID addSearch(final UUID searchId, List<cgCache> cacheList, Boolean newItem, int reason) { - if (this.searches.containsKey(searchId) == false) { + if (!this.searches.containsKey(searchId)) { return null; } @@ -602,7 +580,7 @@ public class cgeoapplication extends Application { } public UUID addSearch(final cgSearch search, final List<cgCache> cacheList, final boolean newItem, final int reason) { - if (cacheList == null || cacheList.size() == 0) { + if (CollectionUtils.isEmpty(cacheList)) { return null; } @@ -630,7 +608,7 @@ public class cgeoapplication extends Application { final UUID searchId = search.getCurrentId(); - if (searches.containsKey(searchId) == false) { + if (!searches.containsKey(searchId)) { searches.put(searchId, search); } diff --git a/main/src/cgeo/geocaching/cgeoauth.java b/main/src/cgeo/geocaching/cgeoauth.java index bc6320b..3c8db34 100644 --- a/main/src/cgeo/geocaching/cgeoauth.java +++ b/main/src/cgeo/geocaching/cgeoauth.java @@ -1,8 +1,11 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; +import cgeo.geocaching.network.OAuth; import org.apache.commons.lang3.StringUtils; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.util.EntityUtils; import android.app.ProgressDialog; import android.content.Intent; @@ -16,20 +19,9 @@ import android.view.View; import android.widget.Button; import android.widget.EditText; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLConnection; import java.util.regex.Matcher; import java.util.regex.Pattern; -import javax.net.ssl.HttpsURLConnection; - public class cgeoauth extends AbstractActivity { private String OAtoken = null; private String OAtokenSecret = null; @@ -142,92 +134,41 @@ public class cgeoauth extends AbstractActivity { int status = 0; try { - String lineOne = null; - HttpsURLConnection connection = null; - - try { - final StringBuilder sb = new StringBuilder(); - final String params = cgOAuth.signOAuth(host, pathRequest, method, true, new Parameters(), null, null); - - int code = -1; - int retries = 0; - - do { - // base.trustAllHosts(); - Log.d(Settings.tag, "https://" + host + pathRequest + "?" + params); - final URL u = new URL("https://" + host + pathRequest + "?" + params); - final URLConnection uc = u.openConnection(); - connection = (HttpsURLConnection) uc; - - // connection.setHostnameVerifier(base.doNotVerify); - connection.setReadTimeout(30000); - connection.setRequestMethod(method); - HttpURLConnection.setFollowRedirects(true); - connection.setDoInput(true); - connection.setDoOutput(false); - - final InputStream in = connection.getInputStream(); - final InputStreamReader ins = new InputStreamReader(in); - final BufferedReader br = new BufferedReader(ins, 16 * 1024); - - while ((lineOne = br.readLine()) != null) { - sb.append(lineOne); - sb.append('\n'); - } - - code = connection.getResponseCode(); - retries++; - - Log.i(Settings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); - - br.close(); - in.close(); - ins.close(); - } while (code == -1 && retries < 5); - - final String line = sb.toString(); - - if (StringUtils.isNotBlank(line)) { - final Matcher paramsMatcher1 = paramsPattern1.matcher(line); - if (paramsMatcher1.find() && paramsMatcher1.groupCount() > 0) { - OAtoken = paramsMatcher1.group(1); - } - final Matcher paramsMatcher2 = paramsPattern2.matcher(line); - if (paramsMatcher2.find() && paramsMatcher2.groupCount() > 0) { - OAtokenSecret = paramsMatcher2.group(1); - } - - if (StringUtils.isNotBlank(OAtoken) && StringUtils.isNotBlank(OAtokenSecret)) { - final SharedPreferences.Editor prefsEdit = getSharedPreferences(Settings.preferences, 0).edit(); - prefsEdit.putString("temp-token-public", OAtoken); - prefsEdit.putString("temp-token-secret", OAtokenSecret); - prefsEdit.commit(); + final Parameters params = new Parameters(); + OAuth.signOAuth(host, pathRequest, method, true, params, null, null); + final String line = cgBase.getResponseData(cgBase.request("https://" + host + pathRequest, params, false)); - try { - final Parameters paramsPre = new Parameters(); - paramsPre.put("oauth_callback", "oob"); - final String paramsBrowser = cgOAuth.signOAuth(host, pathAuthorize, "GET", true, paramsPre, OAtoken, OAtokenSecret); - - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + host + pathAuthorize + "?" + paramsBrowser))); + if (StringUtils.isNotBlank(line)) { + final Matcher paramsMatcher1 = paramsPattern1.matcher(line); + if (paramsMatcher1.find()) { + OAtoken = paramsMatcher1.group(1); + } + final Matcher paramsMatcher2 = paramsPattern2.matcher(line); + if (paramsMatcher2.find()) { + OAtokenSecret = paramsMatcher2.group(1); + } - status = 1; - } catch (Exception e) { - Log.e(Settings.tag, "cgeoauth.requestToken(2): " + e.toString()); - } + if (StringUtils.isNotBlank(OAtoken) && StringUtils.isNotBlank(OAtokenSecret)) { + final SharedPreferences.Editor prefsEdit = getSharedPreferences(Settings.preferences, 0).edit(); + prefsEdit.putString("temp-token-public", OAtoken); + prefsEdit.putString("temp-token-secret", OAtokenSecret); + prefsEdit.commit(); + + try { + final Parameters paramsBrowser = new Parameters(); + paramsBrowser.put("oauth_callback", "oob"); + OAuth.signOAuth(host, pathAuthorize, "GET", true, paramsBrowser, OAtoken, OAtokenSecret); + final String encodedParams = EntityUtils.toString(new UrlEncodedFormEntity(paramsBrowser)); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://" + host + pathAuthorize + "?" + encodedParams))); + status = 1; + } catch (Exception e) { + Log.e(Settings.tag, "cgeoauth.requestToken(2): " + e.toString()); } } - } catch (IOException eio) { - Log.e(Settings.tag, "cgeoauth.requestToken(IO): " + eio.toString() + " ~ " + connection.getResponseCode() + ": " + connection.getResponseMessage()); - } catch (Exception e) { - Log.e(Settings.tag, "cgeoauth.requestToken(1): " + e.toString()); - } finally { - if (connection != null) { - connection.disconnect(); - } } - } catch (Exception e2) { - Log.e(Settings.tag, "cgeoauth.requestToken(3): " + e2.toString()); + } catch (Exception e) { + Log.e(Settings.tag, "cgeoauth.requestToken(1): " + e.toString()); } requestTokenHandler.sendEmptyMessage(status); @@ -239,64 +180,18 @@ public class cgeoauth extends AbstractActivity { final String method = "POST"; int status = 0; - String lineOne = null; try { - final Parameters paramsPre = new Parameters("oauth_verifier", pinEntry.getText().toString()); - - int code = -1; - int retries = 0; - - final String params = cgOAuth.signOAuth(host, path, method, true, paramsPre, OAtoken, OAtokenSecret); - final StringBuilder sb = new StringBuilder(); - do { - // base.trustAllHosts(); - final URL u = new URL("https://" + host + path); - final URLConnection uc = u.openConnection(); - final HttpsURLConnection connection = (HttpsURLConnection) uc; - - // connection.setHostnameVerifier(base.doNotVerify); - connection.setReadTimeout(30000); - connection.setRequestMethod(method); - HttpURLConnection.setFollowRedirects(true); - connection.setDoOutput(true); - connection.setDoInput(true); - - final OutputStream out = connection.getOutputStream(); - final OutputStreamWriter wr = new OutputStreamWriter(out); - - wr.write(params); - wr.flush(); - wr.close(); - out.close(); - - final InputStream in = connection.getInputStream(); - final InputStreamReader ins = new InputStreamReader(in); - final BufferedReader br = new BufferedReader(ins, 16 * 1024); - - while ((lineOne = br.readLine()) != null) { - sb.append(lineOne); - sb.append('\n'); - } - - code = connection.getResponseCode(); - retries++; - - Log.i(Settings.tag, host + ": " + connection.getResponseCode() + " " + connection.getResponseMessage()); - - br.close(); - ins.close(); - in.close(); - connection.disconnect(); - } while (code == -1 && retries < 5); + final Parameters params = new Parameters("oauth_verifier", pinEntry.getText().toString()); - final String line = sb.toString(); + OAuth.signOAuth(host, path, method, true, params, OAtoken, OAtokenSecret); + final String line = StringUtils.defaultString(cgBase.getResponseData(cgBase.postRequest("https://" + host + path, params))); OAtoken = ""; OAtokenSecret = ""; final Matcher paramsMatcher1 = paramsPattern1.matcher(line); - if (paramsMatcher1.find() && paramsMatcher1.groupCount() > 0) { + if (paramsMatcher1.find()) { OAtoken = paramsMatcher1.group(1); } final Matcher paramsMatcher2 = paramsPattern2.matcher(line); diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java index a823238..a1f6874 100644 --- a/main/src/cgeo/geocaching/cgeocaches.java +++ b/main/src/cgeo/geocaching/cgeocaches.java @@ -5,6 +5,7 @@ import cgeo.geocaching.activity.AbstractListActivity; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.apps.cachelist.CacheListAppFactory; +import cgeo.geocaching.enumerations.CacheListType; import cgeo.geocaching.enumerations.CacheSize; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.filter.cgFilter; @@ -25,8 +26,8 @@ import cgeo.geocaching.sorting.SizeComparator; import cgeo.geocaching.sorting.StateComparator; import cgeo.geocaching.sorting.TerrainComparator; import cgeo.geocaching.sorting.VoteComparator; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; @@ -143,7 +144,7 @@ public class cgeocaches extends AbstractListActivity { private static final int MENU_MOVE_SELECTED_OR_ALL_TO_LIST = 1200; private String action = null; - private String type = null; + private CacheListType type = null; private Geopoint coords = null; private String cachetype = null; private String keyword = null; @@ -188,7 +189,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); - Collections.sort((List<cgCache>) cacheList, gcComparator); + Collections.sort(cacheList, gcComparator); } } else { setTitle(title); @@ -285,7 +286,7 @@ public class cgeocaches extends AbstractListActivity { if (CollectionUtils.isNotEmpty(cacheListTmp)) { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); - Collections.sort((List<cgCache>) cacheList, gcComparator); + Collections.sort(cacheList, gcComparator); } if (adapter != null) { adapter.reFilter(); @@ -357,7 +358,7 @@ public class cgeocaches extends AbstractListActivity { } int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000); - int minutesRemaining = (int) ((detailTotal - detailProgress) * secondsElapsed / ((detailProgress > 0) ? detailProgress : 1) / 60); + int minutesRemaining = ((detailTotal - detailProgress) * secondsElapsed / ((detailProgress > 0) ? detailProgress : 1) / 60); waitDialog.setProgress(detailProgress); if (minutesRemaining < 1) { @@ -375,7 +376,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.clear(); cacheList.addAll(cacheListTmp); cacheListTmp.clear(); - Collections.sort((List<cgCache>) cacheList, gcComparator); + Collections.sort(cacheList, gcComparator); } } @@ -445,7 +446,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); - Collections.sort((List<cgCache>) cacheList, gcComparator); + Collections.sort(cacheList, gcComparator); } if (waitDialog != null) { @@ -473,7 +474,7 @@ public class cgeocaches extends AbstractListActivity { cacheList.addAll(cacheListTmp); cacheListTmp.clear(); - Collections.sort((List<cgCache>) cacheList, gcComparator); + Collections.sort(cacheList, gcComparator); } if (waitDialog != null) { @@ -568,9 +569,10 @@ public class cgeocaches extends AbstractListActivity { // get parameters Bundle extras = getIntent().getExtras(); if (extras != null) { - type = extras.getString(EXTRAS_LIST_TYPE); + Object typeObject = extras.get(EXTRAS_LIST_TYPE); + type = (typeObject instanceof CacheListType) ? (CacheListType) typeObject : CacheListType.OFFLINE; coords = new Geopoint(extras.getDouble("latitude"), extras.getDouble("longitude")); - cachetype = extras.getString("cachetype"); + cachetype = Settings.getCacheType(); keyword = extras.getString("keyword"); address = extras.getString("address"); username = extras.getString("username"); @@ -581,104 +583,114 @@ public class cgeocaches extends AbstractListActivity { Thread threadPure; cgSearchThread thread; - if (type.equals("offline")) { - listId = Settings.getLastList(); - if (listId <= 0) { - listId = 1; - title = res.getString(R.string.caches_stored); - } else { - final cgList list = app.getList(listId); - title = list.title; - } - - setTitle(title); - showProgress(true); - setLoadingCaches(); - - threadPure = new geocachesLoadByOffline(loadCachesHandler, coords, listId); - threadPure.start(); - } else if (type.equals("history")) { - if (adapter != null) { - adapter.setHistoric(true); - } + switch (type) { + case OFFLINE: + listId = Settings.getLastList(); + if (listId <= 0) { + listId = 1; + title = res.getString(R.string.caches_stored); + } else { + final cgList list = app.getList(listId); + title = list.title; + } - title = res.getString(R.string.caches_history); - setTitle(title); - showProgress(true); - setLoadingCaches(); + setTitle(title); + showProgress(true); + setLoadingCaches(); - threadPure = new geocachesLoadByHistory(loadCachesHandler); - threadPure.start(); - } else if (type.equals("nearest")) { - action = "pending"; - title = res.getString(R.string.caches_nearby); - setTitle(title); - showProgress(true); - setLoadingCaches(); + threadPure = new geocachesLoadByOffline(loadCachesHandler, coords, listId); + threadPure.start(); - thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else if (type.equals("coordinate")) { - action = "planning"; - title = cgBase.formatCoords(coords, true); - setTitle(title); - showProgress(true); - setLoadingCaches(); + break; + case HISTORY: + if (adapter != null) { + adapter.setHistoric(true); + } - thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else if (type.equals("keyword")) { - title = keyword; - setTitle(title); - showProgress(true); - setLoadingCaches(); + title = res.getString(R.string.caches_history); + setTitle(title); + showProgress(true); + setLoadingCaches(); - thread = new geocachesLoadByKeyword(loadCachesHandler, keyword, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else if (type.equals("address")) { - action = "planning"; - if (StringUtils.isNotBlank(address)) { - title = address; + threadPure = new geocachesLoadByHistory(loadCachesHandler); + threadPure.start(); + break; + case NEAREST: + action = "pending"; + title = res.getString(R.string.caches_nearby); setTitle(title); showProgress(true); setLoadingCaches(); - } else { + + thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + case COORDINATE: + action = "planning"; title = cgBase.formatCoords(coords, true); setTitle(title); showProgress(true); setLoadingCaches(); - } - thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else if (type.equals("username")) { - title = username; - setTitle(title); - showProgress(true); - setLoadingCaches(); + thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + case KEYWORD: + title = keyword; + setTitle(title); + showProgress(true); + setLoadingCaches(); - thread = new geocachesLoadByUserName(loadCachesHandler, username, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else if (type.equals("owner")) { - title = username; - setTitle(title); - showProgress(true); - setLoadingCaches(); + thread = new geocachesLoadByKeyword(loadCachesHandler, keyword, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + case ADDRESS: + action = "planning"; + if (StringUtils.isNotBlank(address)) { + title = address; + setTitle(title); + showProgress(true); + setLoadingCaches(); + } else { + title = cgBase.formatCoords(coords, true); + setTitle(title); + showProgress(true); + setLoadingCaches(); + } - thread = new geocachesLoadByOwner(loadCachesHandler, username, cachetype); - thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); - thread.start(); - } else { - title = "caches"; - setTitle(title); - Log.e(Settings.tag, "cgeocaches.onCreate: No action or unknown action specified"); - } + thread = new geocachesLoadByCoords(loadCachesHandler, coords, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + case USERNAME: + title = username; + setTitle(title); + showProgress(true); + setLoadingCaches(); + + thread = new geocachesLoadByUserName(loadCachesHandler, username, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + case OWNER: + title = username; + setTitle(title); + showProgress(true); + setLoadingCaches(); + thread = new geocachesLoadByOwner(loadCachesHandler, username, cachetype); + thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread)); + thread.start(); + break; + default: + title = "caches"; + setTitle(title); + Log.e(Settings.tag, "cgeocaches.onCreate: No action or unknown action specified"); + break; + } prepareFilterBar(); } @@ -793,7 +805,7 @@ public class cgeocaches extends AbstractListActivity { menu.add(0, MENU_SWITCH_SELECT_MODE, 0, res.getString(R.string.caches_select_mode)).setIcon(android.R.drawable.ic_menu_agenda); menu.add(0, MENU_INVERT_SELECTION, 0, res.getString(R.string.caches_select_invert)).setIcon(R.drawable.ic_menu_mark); - if (type.equals("offline")) { + if (type == CacheListType.OFFLINE) { SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_OFFLINE, 0, res.getString(R.string.caches_manage)).setIcon(android.R.drawable.ic_menu_save); subMenu.add(0, MENU_DROP_CACHES, 0, res.getString(R.string.caches_drop_all)); // delete saved caches subMenu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)); // download details for all caches @@ -808,7 +820,7 @@ public class cgeocaches extends AbstractListActivity { subMenuImport.add(1, MENU_IMPORT_WEB, 0, res.getString(R.string.web_import_title)).setCheckable(false).setChecked(false); } } else { - if (type.equals("history")) + if (type == CacheListType.HISTORY) { SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_HISTORY, 0, res.getString(R.string.caches_manage)).setIcon(android.R.drawable.ic_menu_save); subMenu.add(0, MENU_REMOVE_FROM_HISTORY, 0, res.getString(R.string.cache_clear_history)); // remove from history @@ -819,7 +831,7 @@ public class cgeocaches extends AbstractListActivity { navigationMenu = CacheListAppFactory.addMenuItems(menu, this, res); - if (type.equals("offline")) { + if (type == CacheListType.OFFLINE) { SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_LISTS, 0, res.getString(R.string.list_menu)).setIcon(android.R.drawable.ic_menu_more); subMenu.add(0, MENU_CREATE_LIST, 0, res.getString(R.string.list_menu_create)); subMenu.add(0, MENU_DROP_LIST, 0, res.getString(R.string.list_menu_drop)); @@ -846,7 +858,7 @@ public class cgeocaches extends AbstractListActivity { } boolean hasSelection = adapter != null && adapter.getChecked() > 0; - if (type != null && type.equals("offline")) { // only offline list + if (type == CacheListType.OFFLINE) { // only offline list if (hasSelection) { menu.findItem(MENU_DROP_CACHES).setTitle(res.getString(R.string.caches_drop_selected) + " (" + adapter.getChecked() + ")"); } else { @@ -1395,7 +1407,7 @@ public class cgeocaches extends AbstractListActivity { return; } - if (more == false) { + if (!more) { if (CollectionUtils.isEmpty(cacheList)) { listFooterText.setText(res.getString(R.string.caches_no_cache)); } else { @@ -1493,7 +1505,7 @@ public class cgeocaches extends AbstractListActivity { }); waitDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); - int etaTime = (int) ((detailTotal * 25) / 60); + int etaTime = ((detailTotal * 25) / 60); if (etaTime < 1) { waitDialog.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm)); } else if (etaTime == 1) { @@ -1973,7 +1985,7 @@ public class cgeocaches extends AbstractListActivity { final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache cache : cacheListTemp) { - if (checked > 0 && cache.statusChecked == false) { + if (checked > 0 && !cache.statusChecked) { handler.sendEmptyMessage(0); yield(); @@ -2156,7 +2168,7 @@ public class cgeocaches extends AbstractListActivity { final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList); for (cgCache cache : cacheListTemp) { - if (checked > 0 && cache.statusChecked == false) { + if (checked > 0 && !cache.statusChecked) { continue; } @@ -2200,7 +2212,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { for (cgCache cache : cacheList) { - if (checked > 0 && cache.statusChecked == false) { + if (checked > 0 && !cache.statusChecked) { handler.sendEmptyMessage(0); yield(); @@ -2270,7 +2282,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 == false) { + if (checked > 0 && !cache.statusChecked) { handler.sendEmptyMessage(0); yield(); @@ -2378,7 +2390,7 @@ public class cgeocaches extends AbstractListActivity { * unused here but needed since this method is referenced from XML layout */ public void selectList(View view) { - if (type.equals("offline") == false) { + if (type != CacheListType.OFFLINE) { return; } @@ -2541,7 +2553,7 @@ public class cgeocaches extends AbstractListActivity { private void removeList() { // if there are no caches on this list, don't bother the user with questions. // there is no harm in deleting the list, he could recreate it easily - if (cacheList != null && cacheList.isEmpty()) { + if (CollectionUtils.isEmpty(cacheList)) { removeListInternal(); return; } @@ -2584,12 +2596,16 @@ public class cgeocaches extends AbstractListActivity { } public void goManual(View view) { - if (type != null && type.equals("offline")) { - ActivityMixin.goManual(this, "c:geo-stored"); - } else if (type != null && type.equals("history")) { - ActivityMixin.goManual(this, "c:geo-history"); - } else { - ActivityMixin.goManual(this, "c:geo-nearby"); + switch (type) { + case OFFLINE: + ActivityMixin.goManual(this, "c:geo-stored"); + break; + case HISTORY: + ActivityMixin.goManual(this, "c:geo-history"); + break; + default: + ActivityMixin.goManual(this, "c:geo-nearby"); + break; } } @@ -2599,7 +2615,7 @@ public class cgeocaches extends AbstractListActivity { public static void startActivityOffline(final Context context) { final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra(EXTRAS_LIST_TYPE, "offline"); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.OFFLINE); context.startActivity(cachesIntent); } @@ -2607,30 +2623,27 @@ public class cgeocaches extends AbstractListActivity { cgeocaches cachesActivity = new cgeocaches(); Intent cachesIntent = new Intent(context, cachesActivity.getClass()); - cachesIntent.putExtra("type", "coordinate"); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.COORDINATE); cachesIntent.putExtra("latitude", coords.getLatitude()); cachesIntent.putExtra("longitude", coords.getLongitude()); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); context.startActivity(cachesIntent); } - public static void startActivityCacheOwner(final AbstractActivity context, final String userName) { + public static void startActivityOwner(final AbstractActivity context, final String userName) { final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra("type", "owner"); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.OWNER); cachesIntent.putExtra("username", userName); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); context.startActivity(cachesIntent); } - public static void startActivityCacheUser(final AbstractActivity context, final String userName) { + public static void startActivityUserName(final AbstractActivity context, final String userName) { final Intent cachesIntent = new Intent(context, cgeocaches.class); - cachesIntent.putExtra("type", "username"); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.USERNAME); cachesIntent.putExtra("username", userName); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); context.startActivity(cachesIntent); } @@ -2659,4 +2672,42 @@ public class cgeocaches extends AbstractListActivity { filterBar.setVisibility(View.GONE); } } + + public static void startActivityNearest(final Context context, final Geopoint coordsNow) { + final Intent cachesIntent = new Intent(context, cgeocaches.class); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.NEAREST); + cachesIntent.putExtra("latitude", coordsNow.getLatitude()); + cachesIntent.putExtra("longitude", coordsNow.getLongitude()); + context.startActivity(cachesIntent); + } + + public static void startActivityHistory(Context context) { + final Intent cachesIntent = new Intent(context, cgeocaches.class); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.HISTORY); + context.startActivity(cachesIntent); + } + + public static void startActivityAddress(Context context, Double latitude, Double longitude, String address) { + Intent addressIntent = new Intent(context, cgeocaches.class); + addressIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.ADDRESS); + addressIntent.putExtra("latitude", latitude); + addressIntent.putExtra("longitude", longitude); + addressIntent.putExtra("address", address); + context.startActivity(addressIntent); + } + + public static void startActivityCoordinates(final Context context, double latitude, double longitude) { + final Intent cachesIntent = new Intent(context, cgeocaches.class); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.COORDINATE); + cachesIntent.putExtra("latitude", latitude); + cachesIntent.putExtra("longitude", longitude); + context.startActivity(cachesIntent); + } + + public static void startActivityKeyword(final Context context, final String keyword) { + final Intent cachesIntent = new Intent(context, cgeocaches.class); + cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.KEYWORD); + cachesIntent.putExtra("keyword", keyword); + context.startActivity(cachesIntent); + } } diff --git a/main/src/cgeo/geocaching/cgeodetail.java b/main/src/cgeo/geocaching/cgeodetail.java index 45fea30..85d1b4b 100644 --- a/main/src/cgeo/geocaching/cgeodetail.java +++ b/main/src/cgeo/geocaching/cgeodetail.java @@ -1,19 +1,20 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; +import cgeo.geocaching.activity.Progress; import cgeo.geocaching.apps.cache.GeneralAppsFactory; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.IConnector; import cgeo.geocaching.enumerations.CacheSize; -import cgeo.geocaching.utils.CollectionUtils; import cgeo.geocaching.utils.CryptUtils; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import android.app.AlertDialog; -import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; @@ -87,18 +88,12 @@ public class cgeodetail extends AbstractActivity { private float pixelRatio = 1; private TextView cacheDistance = null; private String contextMenuUser = null; - private ProgressDialog waitDialog = null; - private ProgressDialog descDialog = null; private Spanned longDesc = null; private Boolean longDescDisplayed = false; private loadCache threadCache = null; private loadLongDesc threadLongDesc = null; private Thread storeThread = null; private Thread refreshThread = null; - private ProgressDialog storeDialog = null; - private ProgressDialog refreshDialog = null; - private ProgressDialog dropDialog = null; - private ProgressDialog watchlistDialog = null; // progress dialog for watchlist add/remove private Thread watchlistThread = null; // thread for watchlist add/remove private Map<Integer, String> calendars = new HashMap<Integer, String>(); @@ -171,14 +166,8 @@ public class cgeodetail extends AbstractActivity { private Handler loadCacheHandler = new Handler() { @Override public void handleMessage(Message msg) { - if (cgBase.UPDATE_LOAD_PROGRESS_DETAIL == msg.what) { - if (waitDialog != null - && waitDialog.isShowing() - && msg.obj instanceof String) { - waitDialog.setMessage(res.getString(R.string.cache_dialog_loading_details) - + "\n\n" - + (String) msg.obj); - } + if (cgBase.UPDATE_LOAD_PROGRESS_DETAIL == msg.what && msg.obj instanceof String) { + updateStatusMsg((String) msg.obj); } else { if (searchId == null) { showToast(res.getString(R.string.err_dwld_details_failed)); @@ -194,7 +183,7 @@ public class cgeodetail extends AbstractActivity { return; } - this.obtainMessage(cgBase.UPDATE_LOAD_PROGRESS_DETAIL, res.getString(R.string.cache_dialog_loading_details_status_render)).sendToTarget(); + updateStatusMsg(res.getString(R.string.cache_dialog_loading_details_status_render)); setView(); @@ -209,6 +198,12 @@ public class cgeodetail extends AbstractActivity { (new loadMapPreview(loadMapPreviewHandler)).start(); } } + + private void updateStatusMsg(final String msg) { + Progress.setMessage(res.getString(R.string.cache_dialog_loading_details) + + "\n\n" + + msg); + } }; final Handler loadMapPreviewHandler = new Handler() { @@ -273,9 +268,7 @@ public class cgeodetail extends AbstractActivity { showToast(res.getString(R.string.err_load_descr_failed)); } - if (descDialog != null && descDialog.isShowing()) { - descDialog.dismiss(); - } + Progress.dismiss(); longDescDisplayed = true; } @@ -313,8 +306,7 @@ public class cgeodetail extends AbstractActivity { @Override public void handleMessage(Message msg) { watchlistThread = null; - if (watchlistDialog != null) - watchlistDialog.dismiss(); + Progress.dismiss(); if (msg.what == -1) { showToast(res.getString(R.string.err_watchlist_failed)); } else { @@ -392,13 +384,13 @@ public class cgeodetail extends AbstractActivity { app.setAction(geocode); try { + String title = res.getString(R.string.cache); if (StringUtils.isNotBlank(name)) { - waitDialog = ProgressDialog.show(this, name, res.getString(R.string.cache_dialog_loading_details), true, true); + title = name; } else if (StringUtils.isNotBlank(geocode)) { - waitDialog = ProgressDialog.show(this, geocode.toUpperCase(), res.getString(R.string.cache_dialog_loading_details), true, true); - } else { - waitDialog = ProgressDialog.show(this, res.getString(R.string.cache), res.getString(R.string.cache_dialog_loading_details), true, true); + title = geocode.toUpperCase(); } + Progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, true); } catch (Exception e) { // nothing, we lost the window } @@ -491,10 +483,10 @@ public class cgeodetail extends AbstractActivity { final int id = item.getItemId(); if (id == 1) { - cgeocaches.startActivityCacheOwner(this, contextMenuUser); + cgeocaches.startActivityOwner(this, contextMenuUser); return true; } else if (id == 2) { - cgeocaches.startActivityCacheUser(this, contextMenuUser); + cgeocaches.startActivityUserName(this, contextMenuUser); return true; } else if (id == 3) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(contextMenuUser)))); @@ -623,9 +615,7 @@ public class cgeodetail extends AbstractActivity { cache = app.getCache(searchId); if (cache == null) { - if (waitDialog != null && waitDialog.isShowing()) { - waitDialog.dismiss(); - } + Progress.dismiss(); if (StringUtils.isNotBlank(geocode)) { showToast(res.getString(R.string.err_detail_cache_find) + " " + geocode + "."); @@ -659,7 +649,7 @@ public class cgeodetail extends AbstractActivity { detailsList.removeAllViews(); // actionbar icon, default myster< - ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds((Drawable) getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); + ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); // cache name (full name) itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); @@ -906,11 +896,11 @@ public class cgeodetail extends AbstractActivity { inventoryString.append('\n'); } // avoid HTML parsing where possible - if (containsHtml(inventoryItem.name)) { - inventoryString.append(Html.fromHtml(inventoryItem.name).toString()); + if (containsHtml(inventoryItem.getName())) { + inventoryString.append(Html.fromHtml(inventoryItem.getName()).toString()); } else { - inventoryString.append(inventoryItem.name); + inventoryString.append(inventoryItem.getName()); } } inventView.setText(inventoryString); @@ -966,6 +956,9 @@ public class cgeodetail extends AbstractActivity { personalNoteText.setText(cache.personalNote, TextView.BufferType.SPANNABLE); personalNoteText.setMovementMethod(LinkMovementMethod.getInstance()); } + else { + ((LinearLayout) findViewById(R.id.personalnote_box)).setVisibility(View.GONE); + } // cache short desc if (StringUtils.isNotBlank(cache.shortdesc)) { @@ -994,7 +987,7 @@ public class cgeodetail extends AbstractActivity { showDesc.setOnTouchListener(null); showDesc.setOnClickListener(null); } - } else if (longDescDisplayed == false && StringUtils.isNotBlank(cache.getDescription())) { + } else if (!longDescDisplayed && StringUtils.isNotBlank(cache.getDescription())) { ((LinearLayout) findViewById(R.id.desc_box)).setVisibility(View.VISIBLE); Button showDesc = (Button) findViewById(R.id.show_description); @@ -1029,7 +1022,7 @@ public class cgeodetail extends AbstractActivity { final TextView identification = (TextView) waypointView.findViewById(R.id.identification); ((TextView) waypointView.findViewById(R.id.type)).setText(cgBase.waypointTypees.get(wpt.typee)); - if (wpt.getPrefix().equalsIgnoreCase("OWN") == false) { + if (!wpt.getPrefix().equalsIgnoreCase("OWN")) { identification.setText(wpt.getPrefix().trim() + "/" + wpt.lookup.trim()); } else { identification.setText(res.getString(R.string.waypoint_custom)); @@ -1089,14 +1082,7 @@ public class cgeodetail extends AbstractActivity { Log.e(Settings.tag, "cgeodetail.setView: " + e.toString()); } - if (waitDialog != null && waitDialog.isShowing()) - waitDialog.dismiss(); - if (storeDialog != null && storeDialog.isShowing()) - storeDialog.dismiss(); - if (dropDialog != null && dropDialog.isShowing()) - dropDialog.dismiss(); - if (refreshDialog != null && refreshDialog.isShowing()) - refreshDialog.dismiss(); + Progress.dismiss(); displayLogs(); @@ -1244,7 +1230,7 @@ public class cgeodetail extends AbstractActivity { // add LogImages LinearLayout logLayout = (LinearLayout) rowView.findViewById(R.id.log_layout); - if ((log.logImages != null) && (!log.logImages.isEmpty())) { + if (CollectionUtils.isNotEmpty(log.logImages)) { final ArrayList<cgImage> logImages = new ArrayList<cgImage>(log.logImages); @@ -1380,10 +1366,7 @@ public class cgeodetail extends AbstractActivity { } public void loadLongDesc() { - if (waitDialog == null || waitDialog.isShowing() == false) { - descDialog = ProgressDialog.show(this, null, res.getString(R.string.cache_dialog_loading_description), true); - descDialog.setCancelable(true); - } + Progress.show(this, null, res.getString(R.string.cache_dialog_loading_description), true, true); threadLongDesc = new loadLongDesc(loadDescriptionHandler); threadLongDesc.start(); @@ -1499,7 +1482,7 @@ public class cgeodetail extends AbstractActivity { } private void addToCalendarFn(int index) { - if (calendars == null || calendars.isEmpty()) { + if (MapUtils.isEmpty(calendars)) { return; } @@ -1602,7 +1585,7 @@ public class cgeodetail extends AbstractActivity { } private void showSpoilers() { - if (cache == null || cache.spoilers == null || cache.spoilers.isEmpty()) { + if (cache == null || CollectionUtils.isEmpty(cache.spoilers)) { showToast(res.getString(R.string.err_detail_no_spoiler)); } @@ -1671,7 +1654,7 @@ public class cgeodetail extends AbstractActivity { // 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); - cgeotrackable.startActivity(cgeodetail.this, trackable.guid, trackable.geocode, trackable.name); + cgeotrackable.startActivity(cgeodetail.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName()); } else { Intent trackablesIntent = new Intent(cgeodetail.this, cgeotrackables.class); @@ -1686,17 +1669,12 @@ public class cgeodetail extends AbstractActivity { private class storeCache implements View.OnClickListener { public void onClick(View arg0) { - if (dropDialog != null && dropDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_removing)); - return; - } - if (refreshDialog != null && refreshDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_refreshing)); + if (Progress.isShowing()) { + showToast(res.getString(R.string.err_detail_still_working)); return; } - storeDialog = ProgressDialog.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true); - storeDialog.setCancelable(true); + Progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, true); if (storeThread != null) { storeThread.interrupt(); @@ -1709,17 +1687,12 @@ public class cgeodetail extends AbstractActivity { private class refreshCache implements View.OnClickListener { public void onClick(View arg0) { - if (dropDialog != null && dropDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_removing)); - return; - } - if (storeDialog != null && storeDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_saving)); + if (Progress.isShowing()) { + showToast(res.getString(R.string.err_detail_still_working)); return; } - refreshDialog = ProgressDialog.show(cgeodetail.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true); - refreshDialog.setCancelable(true); + Progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, true); if (refreshThread != null) { refreshThread.interrupt(); @@ -1762,17 +1735,12 @@ public class cgeodetail extends AbstractActivity { private class dropCache implements View.OnClickListener { public void onClick(View arg0) { - if (storeDialog != null && storeDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_saving)); - return; - } - if (refreshDialog != null && refreshDialog.isShowing()) { - showToast(res.getString(R.string.err_detail_still_refreshing)); + if (Progress.isShowing()) { + showToast(res.getString(R.string.err_detail_still_working)); return; } - dropDialog = ProgressDialog.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true); - dropDialog.setCancelable(false); + Progress.show(cgeodetail.this, res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, false); Thread thread = new dropCacheThread(dropCacheHandler); thread.start(); } @@ -1797,13 +1765,11 @@ public class cgeodetail extends AbstractActivity { */ private abstract class AbstractWatchlistClickListener implements View.OnClickListener { public void doExecute(int titleId, int messageId, Thread thread) { - if (watchlistDialog != null && watchlistDialog.isShowing()) { + if (Progress.isShowing()) { showToast(res.getString(R.string.err_watchlist_still_managing)); return; } - watchlistDialog = ProgressDialog.show(cgeodetail.this, - res.getString(titleId), res.getString(messageId), true); - watchlistDialog.setCancelable(true); + Progress.show(cgeodetail.this, res.getString(titleId), res.getString(messageId), true, true); if (watchlistThread != null) { watchlistThread.interrupt(); diff --git a/main/src/cgeo/geocaching/cgeoimages.java b/main/src/cgeo/geocaching/cgeoimages.java index 9f9a2ce..df5578c 100644 --- a/main/src/cgeo/geocaching/cgeoimages.java +++ b/main/src/cgeo/geocaching/cgeoimages.java @@ -3,6 +3,7 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.files.LocalStorage; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.ProgressDialog; @@ -178,7 +179,7 @@ public class cgeoimages extends AbstractActivity { } final ArrayList<cgImage> images = extras.getParcelableArrayList("images"); - if (images == null || images.isEmpty()) { + if (CollectionUtils.isEmpty(images)) { showToast(res.getString(R.string.warn_load_images)); finish(); return; diff --git a/main/src/cgeo/geocaching/cgeopoint.java b/main/src/cgeo/geocaching/cgeopoint.java index 6cfd69a..cc19f4a 100644 --- a/main/src/cgeo/geocaching/cgeopoint.java +++ b/main/src/cgeo/geocaching/cgeopoint.java @@ -420,16 +420,7 @@ public class cgeopoint extends AbstractActivity { return; } - cgeocaches cachesActivity = new cgeocaches(); - - Intent cachesIntent = new Intent(this, cachesActivity.getClass()); - - cachesIntent.putExtra("type", "coordinate"); - cachesIntent.putExtra("latitude", coords.getLatitude()); - cachesIntent.putExtra("longitude", coords.getLongitude()); - cachesIntent.putExtra("cachetype", Settings.getCacheType()); - - startActivity(cachesIntent); + cgeocaches.startActivityCoordinates(this, coords.getLatitude(), coords.getLongitude()); finish(); } diff --git a/main/src/cgeo/geocaching/cgeopopup.java b/main/src/cgeo/geocaching/cgeopopup.java index c214f57..f8a9541 100644 --- a/main/src/cgeo/geocaching/cgeopopup.java +++ b/main/src/cgeo/geocaching/cgeopopup.java @@ -8,7 +8,6 @@ import org.apache.commons.lang3.StringUtils; import android.app.ProgressDialog; import android.content.Intent; import android.content.res.Configuration; -import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; @@ -156,7 +155,7 @@ public class cgeopopup extends AbstractActivity { menu.findItem(5).setVisible(false); } - boolean visitPossible = fromDetail == false && Settings.isLogin(); + boolean visitPossible = !fromDetail && Settings.isLogin(); menu.findItem(MENU_LOG_VISIT).setEnabled(visitPossible); } catch (Exception e) { // nothing @@ -229,7 +228,7 @@ public class cgeopopup extends AbstractActivity { detailsList.removeAllViews(); // actionbar icon - ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds((Drawable) getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); + ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cgBase.getCacheIcon(cache.type)), null, null, null); // cache type itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); @@ -387,7 +386,7 @@ public class cgeopopup extends AbstractActivity { } // more details - if (fromDetail == false) { + if (!fromDetail) { ((LinearLayout) findViewById(R.id.more_details_box)).setVisibility(View.VISIBLE); Button buttonMore = (Button) findViewById(R.id.more_details); @@ -406,7 +405,7 @@ public class cgeopopup extends AbstractActivity { ((LinearLayout) findViewById(R.id.more_details_box)).setVisibility(View.GONE); } - if (fromDetail == false) { + if (!fromDetail) { ((LinearLayout) findViewById(R.id.offline_box)).setVisibility(View.VISIBLE); // offline use diff --git a/main/src/cgeo/geocaching/cgeosmaps.java b/main/src/cgeo/geocaching/cgeosmaps.java index c64da71..cee43e5 100644 --- a/main/src/cgeo/geocaching/cgeosmaps.java +++ b/main/src/cgeo/geocaching/cgeosmaps.java @@ -1,7 +1,8 @@ package cgeo.geocaching; import cgeo.geocaching.activity.AbstractActivity; -import cgeo.geocaching.utils.CollectionUtils; + +import org.apache.commons.collections.CollectionUtils; import android.app.ProgressDialog; import android.graphics.Bitmap; diff --git a/main/src/cgeo/geocaching/cgeotouch.java b/main/src/cgeo/geocaching/cgeotouch.java index fc9b255..372f666 100644 --- a/main/src/cgeo/geocaching/cgeotouch.java +++ b/main/src/cgeo/geocaching/cgeotouch.java @@ -113,10 +113,10 @@ public class cgeotouch extends cgLogForm { trackable = app.getTrackableByGeocode("logging trackable"); - if (StringUtils.isNotBlank(trackable.name)) { - setTitle(res.getString(R.string.trackable_touch) + trackable.name); + if (StringUtils.isNotBlank(trackable.getName())) { + setTitle(res.getString(R.string.trackable_touch) + trackable.getName()); } else { - setTitle(res.getString(R.string.trackable_touch) + trackable.geocode.toUpperCase()); + setTitle(res.getString(R.string.trackable_touch) + trackable.getGeocode().toUpperCase()); } app.setAction("logging trackable"); @@ -334,7 +334,7 @@ public class cgeotouch extends cgLogForm { private class postListener implements View.OnClickListener { public void onClick(View arg0) { - if (gettingViewstate == false) { + if (!gettingViewstate) { waitDialog = ProgressDialog.show(cgeotouch.this, null, res.getString(R.string.log_saving), true); waitDialog.setCancelable(true); @@ -389,7 +389,7 @@ public class cgeotouch extends cgLogForm { } typesPre.clear(); - if (types.contains(typeSelected) == false) { + if (!types.contains(typeSelected)) { typeSelected = types.get(0); setType(typeSelected); showToast(res.getString(R.string.info_log_type_changed)); diff --git a/main/src/cgeo/geocaching/cgeotrackable.java b/main/src/cgeo/geocaching/cgeotrackable.java index cfeac98..4037853 100644 --- a/main/src/cgeo/geocaching/cgeotrackable.java +++ b/main/src/cgeo/geocaching/cgeotrackable.java @@ -7,7 +7,6 @@ import org.apache.commons.lang3.StringUtils; import android.app.ProgressDialog; import android.content.Intent; import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; @@ -46,15 +45,15 @@ public class cgeotrackable extends AbstractActivity { TextView itemName; TextView itemValue; - if (trackable != null && trackable.errorRetrieve != null) { - showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.errorRetrieve.getErrorString(res) + "."); + if (trackable != null && trackable.getErrorRetrieve() != null) { + showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.getErrorRetrieve().getErrorString(res) + "."); finish(); return; } - if (trackable != null && StringUtils.isNotBlank(trackable.error)) { - showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.error + "."); + if (trackable != null && StringUtils.isNotBlank(trackable.getError())) { + showToast(res.getString(R.string.err_tb_details_download) + " " + trackable.getError() + "."); finish(); return; @@ -77,21 +76,21 @@ public class cgeotrackable extends AbstractActivity { try { inflater = getLayoutInflater(); - geocode = trackable.geocode.toUpperCase(); + geocode = trackable.getGeocode().toUpperCase(); - if (StringUtils.isNotBlank(trackable.name)) { - setTitle(Html.fromHtml(trackable.name).toString()); + if (StringUtils.isNotBlank(trackable.getName())) { + setTitle(Html.fromHtml(trackable.getName()).toString()); } else { - setTitle(trackable.name.toUpperCase()); + setTitle(trackable.getName().toUpperCase()); } ((ScrollView) findViewById(R.id.details_list_box)).setVisibility(View.VISIBLE); LinearLayout detailsList = (LinearLayout) findViewById(R.id.details_list); // actiobar icon - if (StringUtils.isNotBlank(trackable.iconUrl)) { + if (StringUtils.isNotBlank(trackable.getIconUrl())) { final tbIconHandler iconHandler = new tbIconHandler(((TextView) findViewById(R.id.actionbar_title))); - final tbIconThread iconThread = new tbIconThread(trackable.iconUrl, iconHandler); + final tbIconThread iconThread = new tbIconThread(trackable.getIconUrl(), iconHandler); iconThread.start(); } @@ -101,8 +100,8 @@ public class cgeotrackable extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.trackable_name)); - if (StringUtils.isNotBlank(trackable.name)) { - itemValue.setText(Html.fromHtml(trackable.name).toString()); + if (StringUtils.isNotBlank(trackable.getName())) { + itemValue.setText(Html.fromHtml(trackable.getName()).toString()); } else { itemValue.setText(res.getString(R.string.trackable_unknown)); } @@ -114,8 +113,8 @@ public class cgeotrackable extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); String tbType = null; - if (StringUtils.isNotBlank(trackable.type)) { - tbType = Html.fromHtml(trackable.type).toString(); + if (StringUtils.isNotBlank(trackable.getType())) { + tbType = Html.fromHtml(trackable.getType()).toString(); } else { tbType = res.getString(R.string.trackable_unknown); } @@ -129,7 +128,7 @@ public class cgeotrackable extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.trackable_code)); - itemValue.setText(trackable.geocode.toUpperCase()); + itemValue.setText(trackable.getGeocode().toUpperCase()); detailsList.addView(itemLayout); // trackable owner @@ -138,8 +137,8 @@ public class cgeotrackable extends AbstractActivity { itemValue = (TextView) itemLayout.findViewById(R.id.value); itemName.setText(res.getString(R.string.trackable_owner)); - if (StringUtils.isNotBlank(trackable.owner)) { - itemValue.setText(Html.fromHtml(trackable.owner), TextView.BufferType.SPANNABLE); + if (StringUtils.isNotBlank(trackable.getOwner())) { + itemValue.setText(Html.fromHtml(trackable.getOwner()), TextView.BufferType.SPANNABLE); itemLayout.setOnClickListener(new userActions()); } else { itemValue.setText(res.getString(R.string.trackable_unknown)); @@ -147,9 +146,9 @@ public class cgeotrackable extends AbstractActivity { detailsList.addView(itemLayout); // trackable spotted - if (StringUtils.isNotBlank(trackable.spottedName) || - trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN || - trackable.spottedType == cgTrackable.SPOTTED_OWNER + if (StringUtils.isNotBlank(trackable.getSpottedName()) || + trackable.getSpottedType() == cgTrackable.SPOTTED_UNKNOWN || + trackable.getSpottedType() == cgTrackable.SPOTTED_OWNER ) { itemLayout = (RelativeLayout) inflater.inflate(R.layout.cache_item, null); itemName = (TextView) itemLayout.findViewById(R.id.name); @@ -158,13 +157,13 @@ public class cgeotrackable extends AbstractActivity { itemName.setText(res.getString(R.string.trackable_spotted)); String text = null; - if (trackable.spottedType == cgTrackable.SPOTTED_CACHE) { - text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.spottedName).toString(); - } else if (trackable.spottedType == cgTrackable.SPOTTED_USER) { - text = res.getString(R.string.trackable_spotted_at_user) + " " + Html.fromHtml(trackable.spottedName).toString(); - } else if (trackable.spottedType == cgTrackable.SPOTTED_UNKNOWN) { + if (trackable.getSpottedType() == cgTrackable.SPOTTED_CACHE) { + text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.getSpottedName()).toString(); + } else if (trackable.getSpottedType() == cgTrackable.SPOTTED_USER) { + text = res.getString(R.string.trackable_spotted_at_user) + " " + Html.fromHtml(trackable.getSpottedName()).toString(); + } else if (trackable.getSpottedType() == cgTrackable.SPOTTED_UNKNOWN) { text = res.getString(R.string.trackable_spotted_unknown_location); - } else if (trackable.spottedType == cgTrackable.SPOTTED_OWNER) { + } else if (trackable.getSpottedType() == cgTrackable.SPOTTED_OWNER) { text = res.getString(R.string.trackable_spotted_owner); } else { text = "N/A"; @@ -172,16 +171,16 @@ public class cgeotrackable extends AbstractActivity { itemValue.setText(text); itemLayout.setClickable(true); - if (cgTrackable.SPOTTED_CACHE == trackable.spottedType) { + if (cgTrackable.SPOTTED_CACHE == trackable.getSpottedType()) { itemLayout.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent cacheIntent = new Intent(cgeotrackable.this, cgeodetail.class); - cacheIntent.putExtra("guid", (String) trackable.spottedGuid); - cacheIntent.putExtra("name", (String) trackable.spottedName); + cacheIntent.putExtra("guid", trackable.getSpottedGuid()); + cacheIntent.putExtra("name", trackable.getSpottedName()); startActivity(cacheIntent); } }); - } else if (cgTrackable.SPOTTED_USER == trackable.spottedType) { + } else if (cgTrackable.SPOTTED_USER == trackable.getSpottedType()) { itemLayout.setOnClickListener(new userActions()); //activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?guid=" + trackable.spottedGuid))); } @@ -190,58 +189,58 @@ public class cgeotrackable extends AbstractActivity { } // trackable origin - if (StringUtils.isNotBlank(trackable.origin)) { + if (StringUtils.isNotBlank(trackable.getOrigin())) { 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.trackable_origin)); - itemValue.setText(Html.fromHtml(trackable.origin), TextView.BufferType.SPANNABLE); + itemValue.setText(Html.fromHtml(trackable.getOrigin()), TextView.BufferType.SPANNABLE); detailsList.addView(itemLayout); } // trackable released - if (trackable.released != null) { + if (trackable.getReleased() != 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.trackable_released)); - itemValue.setText(base.formatDate(trackable.released.getTime())); + itemValue.setText(base.formatDate(trackable.getReleased().getTime())); detailsList.addView(itemLayout); } // trackable distance - if (trackable.distance != null) { + if (trackable.getDistance() != 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.trackable_distance)); - itemValue.setText(cgBase.getHumanDistance(trackable.distance)); + itemValue.setText(cgBase.getHumanDistance(trackable.getDistance())); detailsList.addView(itemLayout); } // trackable goal - if (StringUtils.isNotBlank(trackable.goal)) { + if (StringUtils.isNotBlank(trackable.getGoal())) { ((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.goal, new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); + descView.setText(Html.fromHtml(trackable.getGoal(), new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); descView.setMovementMethod(LinkMovementMethod.getInstance()); } // trackable details - if (StringUtils.isNotBlank(trackable.details)) { + if (StringUtils.isNotBlank(trackable.getDetails())) { ((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.details, new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); + descView.setText(Html.fromHtml(trackable.getDetails(), new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false), null), TextView.BufferType.SPANNABLE); descView.setMovementMethod(LinkMovementMethod.getInstance()); } // trackable image - if (StringUtils.isNotBlank(trackable.image)) { + if (StringUtils.isNotBlank(trackable.getImage())) { ((LinearLayout) findViewById(R.id.image_box)).setVisibility(View.VISIBLE); LinearLayout imgView = (LinearLayout) findViewById(R.id.image); @@ -252,7 +251,7 @@ public class cgeotrackable extends AbstractActivity { trackableImage.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.image))); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(trackable.getImage()))); } }); @@ -276,7 +275,7 @@ public class cgeotrackable extends AbstractActivity { try { cgHtmlImg imgGetter = new cgHtmlImg(cgeotrackable.this, geocode, true, 0, false); - image = imgGetter.getDrawable(trackable.image); + image = imgGetter.getDrawable(trackable.getImage()); Message message = handler.obtainMessage(0, image); handler.sendMessage(message); } catch (Exception e) { @@ -402,9 +401,9 @@ public class cgeotrackable extends AbstractActivity { String selectedName = itemName.getText().toString(); if (selectedName.equals(res.getString(R.string.trackable_owner))) { - contextMenuUser = trackable.owner; + contextMenuUser = trackable.getOwner(); } else if (selectedName.equals(res.getString(R.string.trackable_spotted))) { - contextMenuUser = trackable.spottedName; + contextMenuUser = trackable.getSpottedName(); } } @@ -419,10 +418,10 @@ public class cgeotrackable extends AbstractActivity { final int id = item.getItemId(); if (id == 1) { - cgeocaches.startActivityCacheOwner(this, contextMenuUser); + cgeocaches.startActivityOwner(this, contextMenuUser); return true; } else if (id == 2) { - cgeocaches.startActivityCacheUser(this, contextMenuUser); + cgeocaches.startActivityUserName(this, contextMenuUser); return true; } else if (id == 3) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(contextMenuUser)))); @@ -447,7 +446,7 @@ public class cgeotrackable extends AbstractActivity { logTouch(); return true; case 2: - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/track/details.aspx?tracker=" + trackable.geocode))); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/track/details.aspx?tracker=" + trackable.getGeocode()))); return true; } @@ -490,8 +489,8 @@ public class cgeotrackable extends AbstractActivity { RelativeLayout rowView; - if (trackable != null && trackable.logs != null) { - for (cgLog log : trackable.logs) { + if (trackable != null && trackable.getLogs() != null) { + for (cgLog log : trackable.getLogs()) { rowView = (RelativeLayout) inflater.inflate(R.layout.trackable_logitem, null); if (log.date > 0) { @@ -514,8 +513,8 @@ public class cgeotrackable extends AbstractActivity { ((TextView) rowView.findViewById(R.id.location)).setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { Intent cacheIntent = new Intent(cgeotrackable.this, cgeodetail.class); - cacheIntent.putExtra("guid", (String) cacheGuid); - cacheIntent.putExtra("name", (String) Html.fromHtml(cacheName).toString()); + cacheIntent.putExtra("guid", cacheGuid); + cacheIntent.putExtra("name", Html.fromHtml(cacheName).toString()); startActivity(cacheIntent); } }); @@ -527,7 +526,7 @@ public class cgeotrackable extends AbstractActivity { listView.addView(rowView); } - if (trackable.logs.size() > 0) { + if (trackable.getLogs().size() > 0) { ((LinearLayout) findViewById(R.id.log_box)).setVisibility(View.VISIBLE); } } @@ -551,8 +550,8 @@ public class cgeotrackable extends AbstractActivity { private void logTouch() { Intent logTouchIntent = new Intent(this, cgeotouch.class); - logTouchIntent.putExtra("geocode", trackable.geocode.toUpperCase()); - logTouchIntent.putExtra("guid", trackable.guid); + logTouchIntent.putExtra("geocode", trackable.getGeocode().toUpperCase()); + logTouchIntent.putExtra("guid", trackable.getGuid()); startActivity(logTouchIntent); } @@ -573,7 +572,7 @@ public class cgeotrackable extends AbstractActivity { BitmapDrawable image = null; try { - cgHtmlImg imgGetter = new cgHtmlImg(cgeotrackable.this, trackable.geocode, false, 0, false); + cgHtmlImg imgGetter = new cgHtmlImg(cgeotrackable.this, trackable.getGeocode(), false, 0, false); image = imgGetter.getDrawable(url); Message message = handler.obtainMessage(0, image); @@ -595,7 +594,7 @@ public class cgeotrackable extends AbstractActivity { public void handleMessage(Message message) { BitmapDrawable image = (BitmapDrawable) message.obj; if (image != null && view != null) { - view.setCompoundDrawablesWithIntrinsicBounds((Drawable) image, null, null, null); + view.setCompoundDrawablesWithIntrinsicBounds(image, null, null, null); } } } diff --git a/main/src/cgeo/geocaching/cgeotrackables.java b/main/src/cgeo/geocaching/cgeotrackables.java index c27ce11..d3e0ceb 100644 --- a/main/src/cgeo/geocaching/cgeotrackables.java +++ b/main/src/cgeo/geocaching/cgeotrackables.java @@ -46,7 +46,7 @@ public class cgeotrackables extends AbstractActivity { return; } else if (trackables.size() == 1) { cgTrackable trackable = trackables.get(0); - cgeotrackable.startActivity(cgeotrackables.this, trackable.guid, trackable.geocode, trackable.name); + cgeotrackable.startActivity(cgeotrackables.this, trackable.getGuid(), trackable.getGeocode(), trackable.getName()); finish(); return; } else { @@ -56,13 +56,13 @@ public class cgeotrackables extends AbstractActivity { Button oneTb = (Button) oneTbPre.findViewById(R.id.button); - if (trackable.name != null) { - oneTb.setText(Html.fromHtml(trackable.name).toString()); + if (trackable.getName() != null) { + oneTb.setText(Html.fromHtml(trackable.getName()).toString()); } else { oneTb.setText("some trackable"); } oneTb.setClickable(true); - oneTb.setOnClickListener(new buttonListener(trackable.guid, trackable.geocode, trackable.name)); + oneTb.setOnClickListener(new buttonListener(trackable.getGuid(), trackable.getGeocode(), trackable.getName())); addList.addView(oneTbPre); } } diff --git a/main/src/cgeo/geocaching/cgeovisit.java b/main/src/cgeo/geocaching/cgeovisit.java index 1f84556..c71f687 100644 --- a/main/src/cgeo/geocaching/cgeovisit.java +++ b/main/src/cgeo/geocaching/cgeovisit.java @@ -2,8 +2,8 @@ package cgeo.geocaching; import cgeo.geocaching.LogTemplateProvider.LogTemplate; import cgeo.geocaching.enumerations.StatusCode; -import cgeo.geocaching.utils.CollectionUtils; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Dialog; @@ -77,7 +77,7 @@ public class cgeovisit extends cgLogForm { @Override public void handleMessage(Message msg) { - if (types.contains(typeSelected) == false) { + if (!types.contains(typeSelected)) { typeSelected = types.get(0); setType(typeSelected); @@ -461,7 +461,7 @@ public class cgeovisit extends cgLogForm { insertIntoLog(LogTemplateProvider.applyTemplates(Settings.getSignature(), base, false), false); } - if (types.contains(typeSelected) == false) { + if (!types.contains(typeSelected)) { if (alreadyFound) { typeSelected = cgBase.LOG_NOTE; } else { @@ -552,9 +552,9 @@ public class cgeovisit extends cgLogForm { tweetBox = (LinearLayout) findViewById(R.id.tweet_box); } - if (type == 2 && tbChanged == false) { + if (type == 2 && !tbChanged) { // TODO: change action - } else if (type != 2 && tbChanged == false) { + } else if (type != 2 && !tbChanged) { // TODO: change action } @@ -591,7 +591,7 @@ public class cgeovisit extends cgLogForm { private class postListener implements View.OnClickListener { public void onClick(View arg0) { - if (gettingViewstate == false) { + if (!gettingViewstate) { waitDialog = ProgressDialog.show(cgeovisit.this, null, res.getString(R.string.log_saving), true); waitDialog.setCancelable(true); diff --git a/main/src/cgeo/geocaching/cgeowaypointadd.java b/main/src/cgeo/geocaching/cgeowaypointadd.java index e4e1479..4d293e5 100644 --- a/main/src/cgeo/geocaching/cgeowaypointadd.java +++ b/main/src/cgeo/geocaching/cgeowaypointadd.java @@ -311,8 +311,8 @@ public class cgeowaypointadd extends AbstractActivity { return; } - coords.add(0, (Double) latParsed); - coords.add(1, (Double) lonParsed); + coords.add(0, latParsed); + coords.add(1, lonParsed); } else if (latitude != null && longitude != null) { coords.add(0, latitude); coords.add(1, longitude); diff --git a/main/src/cgeo/geocaching/connector/GCConnector.java b/main/src/cgeo/geocaching/connector/GCConnector.java index d0e2d61..7699a74 100644 --- a/main/src/cgeo/geocaching/connector/GCConnector.java +++ b/main/src/cgeo/geocaching/connector/GCConnector.java @@ -9,6 +9,7 @@ import cgeo.geocaching.cgCacheWrap; import cgeo.geocaching.cgSearch; import cgeo.geocaching.cgeoapplication; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.os.Handler; @@ -110,7 +111,7 @@ public class GCConnector extends AbstractConnector implements IConnector { final cgCacheWrap caches = base.parseCache(page, reason, handler); - if (caches == null || caches.cacheList == null || caches.cacheList.isEmpty()) { + if (caches == null || CollectionUtils.isEmpty(caches.cacheList)) { if (caches != null && caches.error != null) { search.error = caches.error; } @@ -124,7 +125,7 @@ public class GCConnector extends AbstractConnector implements IConnector { return null; } - List<cgCache> cacheList = cgBase.processSearchResults(search, caches, false, false, null); + List<cgCache> cacheList = cgBase.filterSearchResults(search, caches, false, false, null); app.addSearch(search, cacheList, true, reason); return search.getCurrentId(); diff --git a/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java b/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java index 013fc18..6334973 100644 --- a/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java +++ b/main/src/cgeo/geocaching/connector/opencaching/ApiOpenCachingConnector.java @@ -47,7 +47,7 @@ public class ApiOpenCachingConnector extends OpenCachingConnector implements ICo final cgCacheWrap caches = new cgCacheWrap(); caches.cacheList.add(cache); - final List<cgCache> cacheList = cgBase.processSearchResults(search, caches, false, false, null); + final List<cgCache> cacheList = cgBase.filterSearchResults(search, caches, false, false, null); app.addSearch(search, cacheList, true, reason); return search.getCurrentId(); diff --git a/main/src/cgeo/geocaching/enumerations/CacheListType.java b/main/src/cgeo/geocaching/enumerations/CacheListType.java new file mode 100644 index 0000000..8905993 --- /dev/null +++ b/main/src/cgeo/geocaching/enumerations/CacheListType.java @@ -0,0 +1,12 @@ +package cgeo.geocaching.enumerations; + +public enum CacheListType { + OFFLINE, + HISTORY, + NEAREST, + COORDINATE, + KEYWORD, + ADDRESS, + USERNAME, + OWNER; +} diff --git a/main/src/cgeo/geocaching/files/FileList.java b/main/src/cgeo/geocaching/files/FileList.java index 770e749..2f810ea 100644 --- a/main/src/cgeo/geocaching/files/FileList.java +++ b/main/src/cgeo/geocaching/files/FileList.java @@ -4,6 +4,7 @@ import cgeo.geocaching.R; import cgeo.geocaching.Settings; import cgeo.geocaching.activity.AbstractListActivity; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; @@ -42,7 +43,7 @@ public abstract class FileList<T extends ArrayAdapter<File>> extends AbstractLis @Override public void handleMessage(Message msg) { try { - if (files == null || files.isEmpty()) { + if (CollectionUtils.isEmpty(files)) { if (waitDialog != null) { waitDialog.dismiss(); } diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java index 9ef25c9..b43d712 100644 --- a/main/src/cgeo/geocaching/files/GPXParser.java +++ b/main/src/cgeo/geocaching/files/GPXParser.java @@ -47,7 +47,8 @@ import java.util.regex.Pattern; public abstract class GPXParser extends FileParser { private static final SimpleDateFormat formatSimple = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"); // 2010-04-20T07:00:00Z - private static final SimpleDateFormat formatTimezone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.000'Z"); // 2010-04-20T01:01:03.000-04:00 + private static final SimpleDateFormat formatSimpleMilliSeconds = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'"); // 2010-04-20T07:00:00.000Z + private static final SimpleDateFormat formatTimezone = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SZ"); // 2010-04-20T01:01:03.000-04:00 private static final Pattern patternGeocode = Pattern.compile("([A-Z]{2}[0-9A-Z]+)", Pattern.CASE_INSENSITIVE); private static final Pattern patternGuid = Pattern.compile(".*" + Pattern.quote("guid=") + "([0-9a-z\\-]+)", Pattern.CASE_INSENSITIVE); @@ -224,12 +225,15 @@ public abstract class GPXParser extends FileParser { version = versionIn; } - private static Date parseDate(String inputUntrimmed) throws ParseException { + static Date parseDate(String inputUntrimmed) throws ParseException { final String input = inputUntrimmed.trim(); if (input.length() >= 3 && input.charAt(input.length() - 3) == ':') { final String removeColon = input.substring(0, input.length() - 3) + input.substring(input.length() - 2); return formatTimezone.parse(removeColon); } + if (input.contains(".")) { + return formatSimpleMilliSeconds.parse(input); + } return formatSimple.parse(input); } @@ -613,7 +617,7 @@ public abstract class GPXParser extends FileParser { try { if (attrs.getIndex("ref") > -1) { - trackable.geocode = attrs.getValue("ref").toUpperCase(); + trackable.setGeocode(attrs.getValue("ref").toUpperCase()); } } catch (Exception e) { // nothing @@ -628,7 +632,7 @@ public abstract class GPXParser extends FileParser { @Override public void end() { - if (StringUtils.isNotBlank(trackable.geocode) && StringUtils.isNotBlank(trackable.name)) { + if (StringUtils.isNotBlank(trackable.getGeocode()) && StringUtils.isNotBlank(trackable.getName())) { if (cache.inventory == null) { cache.inventory = new ArrayList<cgTrackable>(); } @@ -642,7 +646,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String tbName) { - trackable.name = validate(tbName); + trackable.setName(validate(tbName)); } }); diff --git a/main/src/cgeo/geocaching/files/LocalStorage.java b/main/src/cgeo/geocaching/files/LocalStorage.java index 13b2f3a..1b98913 100644 --- a/main/src/cgeo/geocaching/files/LocalStorage.java +++ b/main/src/cgeo/geocaching/files/LocalStorage.java @@ -218,4 +218,13 @@ public class LocalStorage { return true; } + /** + * Check if an external media (SD card) is available for use. + * + * @return true if the external media is properly mounted + */ + public static boolean isExternalStorageAvailable() { + return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); + } + } diff --git a/main/src/cgeo/geocaching/geopoint/Geopoint.java b/main/src/cgeo/geocaching/geopoint/Geopoint.java index f398f75..8063d7b 100644 --- a/main/src/cgeo/geocaching/geopoint/Geopoint.java +++ b/main/src/cgeo/geocaching/geopoint/Geopoint.java @@ -21,6 +21,8 @@ public final class Geopoint * latitude * @param lon * longitude + * @throws MalformedCoordinateException + * if any coordinate is incorrect */ public Geopoint(final double lat, final double lon) { @@ -44,6 +46,8 @@ public final class Geopoint * latitude * @param lon * longitude + * @throws MalformedCoordinateException + * if any coordinate is incorrect */ public Geopoint(final int lat, final int lon) { @@ -55,6 +59,10 @@ public final class Geopoint * * @param text * string to parse + * @throws GeopointParser.ParseException + * if the string cannot be parsed + * @throws MalformedCoordinateException + * if any coordinate is incorrect * @see GeopointParser.parse() */ public Geopoint(final String text) { @@ -62,12 +70,16 @@ public final class Geopoint } /** - * Creates new Geopoint with latitude and longitude parsed from string. - * + * Creates new Geopoint with latitude and longitude parsed from strings. + * * @param latText * latitude string to parse * @param lonText * longitude string to parse + * @throws GeopointParser.ParseException + * if any argument string cannot be parsed + * @throws MalformedCoordinateException + * if any coordinate is incorrect * @see GeopointParser.parse() */ public Geopoint(final String latText, final String lonText) { @@ -263,7 +275,7 @@ public final class Geopoint return format(GeopointFormatter.Format.LAT_LON_DECMINUTE); } - public static class GeopointException + abstract public static class GeopointException extends RuntimeException { private static final long serialVersionUID = 1L; diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index b02d796..f9e0296 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -25,6 +25,7 @@ import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnDragListener; import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import android.app.Activity; @@ -574,7 +575,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory searchId = null; searchIdIntent = null; } else if (id == MENU_STORE_CACHES) { - if (live && !isLoading() && caches != null && !caches.isEmpty()) { + if (live && !isLoading() && CollectionUtils.isNotEmpty(caches)) { final List<String> geocodes = new ArrayList<String>(); List<cgCache> cachesProtected = new ArrayList<cgCache>(caches); @@ -910,7 +911,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory moved = true; } else if (((Math.abs(spanLatitudeNow - spanLatitude) > 50) || (Math.abs(spanLongitudeNow - spanLongitude) > 50) || // changed zoom (Math.abs(centerLatitudeNow - centerLatitude) > (spanLatitudeNow / 4)) || (Math.abs(centerLongitudeNow - centerLongitude) > (spanLongitudeNow / 4)) // map moved - ) && (cachesCnt <= 0 || caches == null || caches.isEmpty() + ) && (cachesCnt <= 0 || CollectionUtils.isEmpty(caches) || !cgBase.isInViewPort(centerLatitude, centerLongitude, centerLatitudeNow, centerLongitudeNow, spanLatitude, spanLongitude, spanLatitudeNow, spanLongitudeNow))) { moved = true; } @@ -1472,7 +1473,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory stop = false; working = true; - if (mapView == null || users == null || users.isEmpty()) { + if (mapView == null || CollectionUtils.isEmpty(users)) { return; } @@ -1621,7 +1622,7 @@ public class CGeoMap extends AbstractMap implements OnDragListener, ViewFactory @Override public void run() { - if (geocodes == null || geocodes.isEmpty()) { + if (CollectionUtils.isEmpty(geocodes)) { return; } diff --git a/main/src/cgeo/geocaching/maps/CachesOverlay.java b/main/src/cgeo/geocaching/maps/CachesOverlay.java index 07e0004..9f9e2b3 100644 --- a/main/src/cgeo/geocaching/maps/CachesOverlay.java +++ b/main/src/cgeo/geocaching/maps/CachesOverlay.java @@ -276,8 +276,8 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve dialog.setTitle("cache"); String cacheType; - if (cgBase.cacheTypesInv.containsKey(coordinate.typeSpec)) { - cacheType = cgBase.cacheTypesInv.get(coordinate.typeSpec); + if (cgBase.cacheTypesInv.containsKey(coordinate.typeeSpec)) { + cacheType = cgBase.cacheTypesInv.get(coordinate.typeeSpec); } else { cacheType = cgBase.cacheTypesInv.get("mystery"); } @@ -315,7 +315,7 @@ public class CachesOverlay extends AbstractItemizedOverlay implements GeneralOve } else { dialog.setTitle("waypoint"); - String waypointL10N = cgBase.waypointTypees.get(coordinate.typeSpec); + String waypointL10N = cgBase.waypointTypees.get(coordinate.typeeSpec); if (waypointL10N == null) { waypointL10N = cgBase.waypointTypees.get(WaypointType.WAYPOINT); } diff --git a/main/src/cgeo/geocaching/cgOAuth.java b/main/src/cgeo/geocaching/network/OAuth.java index 3d6e490..38b04e9 100644 --- a/main/src/cgeo/geocaching/cgOAuth.java +++ b/main/src/cgeo/geocaching/network/OAuth.java @@ -1,5 +1,8 @@ -package cgeo.geocaching; +package cgeo.geocaching.network; +import cgeo.geocaching.Parameters; +import cgeo.geocaching.Settings; +import cgeo.geocaching.cgBase; import cgeo.geocaching.utils.CryptUtils; import org.apache.commons.lang3.StringUtils; @@ -9,35 +12,24 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -public class cgOAuth { - public static String signOAuth(String host, String path, String method, boolean https, Parameters params, String token, String tokenSecret) { - String paramsDone = ""; - - long currentTime = new Date().getTime(); // miliseconds - currentTime = currentTime / 1000; // seconds - currentTime = (long) Math.floor(currentTime); - +public class OAuth { + public static void signOAuth(final String host, final String path, final String method, final boolean https, final Parameters params, final String token, final String tokenSecret) { params.put( "oauth_consumer_key", Settings.getKeyConsumerPublic(), "oauth_nonce", CryptUtils.md5(Long.toString(System.currentTimeMillis())), "oauth_signature_method", "HMAC-SHA1", - "oauth_timestamp", Long.toString(currentTime), + "oauth_timestamp", Long.toString((long) Math.floor(new Date().getTime() / 1000)), "oauth_token", StringUtils.defaultString(token), "oauth_version", "1.0"); - params.sort(); - List<String> paramsEncoded = new ArrayList<String>(); + final List<String> paramsEncoded = new ArrayList<String>(); for (final NameValuePair nameValue : params) { paramsEncoded.add(nameValue.getName() + "=" + cgBase.urlencode_rfc3986(nameValue.getValue())); } final String keysPacked = Settings.getKeyConsumerSecret() + "&" + StringUtils.defaultString(tokenSecret); // both even if empty some of them! final String requestPacked = method + "&" + cgBase.urlencode_rfc3986((https ? "https" : "http") + "://" + host + path) + "&" + cgBase.urlencode_rfc3986(StringUtils.join(paramsEncoded.toArray(), '&')); - paramsEncoded.add("oauth_signature=" + cgBase.urlencode_rfc3986(cgBase.base64Encode(CryptUtils.hashHmac(requestPacked, keysPacked)))); - - paramsDone = StringUtils.join(paramsEncoded.toArray(), '&'); - - return paramsDone; + params.put("oauth_signature", cgBase.base64Encode(CryptUtils.hashHmac(requestPacked, keysPacked))); } } diff --git a/main/src/cgeo/geocaching/utils/CollectionUtils.java b/main/src/cgeo/geocaching/utils/CollectionUtils.java deleted file mode 100644 index 06e2419..0000000 --- a/main/src/cgeo/geocaching/utils/CollectionUtils.java +++ /dev/null @@ -1,24 +0,0 @@ -package cgeo.geocaching.utils; - -import java.util.List; -import java.util.Map; - -public class CollectionUtils { - - public static <T> boolean isEmpty(List<T> list) { - return (list != null && list.size() == 0); - } - - public static <T, T2> boolean isEmpty(Map<T, T2> map) { - return (map != null && map.size() == 0); - } - - public static <T> boolean isNotEmpty(List<T> list) { - return (list != null && list.size() != 0); - } - - public static <T, T2> boolean isNotEmpty(Map<T, T2> map) { - return (map != null && map.size() != 0); - } - -} diff --git a/tests/src/cgeo/geocaching/activity/ProgressTest.java b/tests/src/cgeo/geocaching/activity/ProgressTest.java new file mode 100644 index 0000000..8d97ce3 --- /dev/null +++ b/tests/src/cgeo/geocaching/activity/ProgressTest.java @@ -0,0 +1,26 @@ +package cgeo.geocaching.activity; + +import cgeo.geocaching.cgeo; + +import android.test.ActivityInstrumentationTestCase2; + +public class ProgressTest extends ActivityInstrumentationTestCase2<cgeo> { + public ProgressTest() { + super("cgeo.geocaching", cgeo.class); + } + + public void testProgressWrapper() { + assertFalse(Progress.isShowing()); // nothing shown initially + + Progress.show(getActivity(), "Title", "Message", true, false); + assertTrue(Progress.isShowing()); + + Progress.setMessage("Test"); + assertTrue(Progress.isShowing()); + + for (int i = 0; i < 2; i++) { // fault tolerant when dismissing to often + Progress.dismiss(); + assertFalse(Progress.isShowing()); + } + } +} diff --git a/tests/src/cgeo/geocaching/cgeoApplicationTest.java b/tests/src/cgeo/geocaching/cgeoApplicationTest.java index ff84b5b..b838a8d 100644 --- a/tests/src/cgeo/geocaching/cgeoApplicationTest.java +++ b/tests/src/cgeo/geocaching/cgeoApplicationTest.java @@ -9,6 +9,7 @@ import android.test.suitebuilder.annotation.MediumTest; import android.test.suitebuilder.annotation.SmallTest; import java.util.ArrayList; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.UUID; @@ -102,4 +103,26 @@ public class cgeoApplicationTest extends ApplicationTestCase<cgeoapplication> { cgCache cache = caches.cacheList.get(0); Assert.assertEquals("California, United States", cache.getLocation()); } + + public void testSearchTrackable() { + cgTrackable tb = base.searchTrackable("TB2J1VZ", null, null); + Assert.assertEquals("aefffb86-099f-444f-b132-605436163aa8", tb.getGuid()); + Assert.assertEquals("TB2J1VZ", tb.getGeocode()); + Assert.assertEquals("http://www.geocaching.com/images/wpttypes/21.gif", tb.getIconUrl()); + Assert.assertEquals("blafoo's Children Music CD", tb.getName()); + Assert.assertEquals("Travel Bug Dog Tag", tb.getType()); + Assert.assertEquals(new Date(2009 - 1900, 8 - 1, 24), tb.getReleased()); + Assert.assertEquals(10617.8f, tb.getDistance()); + Assert.assertEquals("Niedersachsen, Germany", tb.getOrigin()); + Assert.assertEquals("blafoo", tb.getOwner()); + Assert.assertEquals("0564a940-8311-40ee-8e76-7e91b2cf6284", tb.getOwnerGuid()); + Assert.assertEquals("Nice place for a break cache", tb.getSpottedName()); + Assert.assertEquals(cgTrackable.SPOTTED_CACHE, tb.getSpottedType()); + Assert.assertEquals("faa2d47d-19ea-422f-bec8-318fc82c8063", tb.getSpottedGuid()); + Assert.assertEquals("Kinder erfreuen.<br/><br/>Make children happy.", tb.getGoal()); + Assert.assertTrue(tb.getDetails().startsWith("Auf der CD sind")); + Assert.assertEquals("http://img.geocaching.com/track/display/38382780-87a7-4393-8393-78841678ee8c.jpg", tb.getImage()); + Assert.assertEquals(10, tb.getLogs().size()); + } + } diff --git a/tests/src/cgeo/geocaching/files/GPXParserTest.java b/tests/src/cgeo/geocaching/files/GPXParserTest.java index 22401a1..d62bd4f 100644 --- a/tests/src/cgeo/geocaching/files/GPXParserTest.java +++ b/tests/src/cgeo/geocaching/files/GPXParserTest.java @@ -206,4 +206,14 @@ public class GPXParserTest extends InstrumentationTestCase { return cacheList; } + public static void testParseDateWithFractionalSeconds() { + // was experienced in GSAK file + String dateString = "2011-08-13T02:52:18.103Z"; + try { + GPXParser.parseDate(dateString); + } catch (ParseException e) { + fail(); + e.printStackTrace(); + } + } } |
