diff options
Diffstat (limited to 'main/src/cgeo/geocaching')
55 files changed, 635 insertions, 485 deletions
diff --git a/main/src/cgeo/geocaching/AbstractPopupActivity.java b/main/src/cgeo/geocaching/AbstractPopupActivity.java index 830d61a..67d50ab 100644 --- a/main/src/cgeo/geocaching/AbstractPopupActivity.java +++ b/main/src/cgeo/geocaching/AbstractPopupActivity.java @@ -118,7 +118,7 @@ public abstract class AbstractPopupActivity extends AbstractActivity { return; } - geocode = cache.getGeocode().toUpperCase(); + geocode = cache.getGeocode(); } private void showInBrowser() { @@ -251,7 +251,7 @@ public abstract class AbstractPopupActivity extends AbstractActivity { final String cacheSize = cache.getSize() != CacheSize.UNKNOWN ? " (" + cache.getSize().getL10n() + ")" : ""; details.add(R.string.cache_type, cacheType + cacheSize); - details.add(R.string.cache_geocode, cache.getGeocode().toUpperCase()); + details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); details.addDistance(cache, cacheDistance); @@ -276,7 +276,7 @@ public abstract class AbstractPopupActivity extends AbstractActivity { @Override public void onClick(View arg0) { - CacheDetailActivity.startActivity(AbstractPopupActivity.this, geocode.toUpperCase()); + CacheDetailActivity.startActivity(AbstractPopupActivity.this, geocode); finish(); } }); diff --git a/main/src/cgeo/geocaching/CacheDetailActivity.java b/main/src/cgeo/geocaching/CacheDetailActivity.java index 2dcafde..155fa35 100644 --- a/main/src/cgeo/geocaching/CacheDetailActivity.java +++ b/main/src/cgeo/geocaching/CacheDetailActivity.java @@ -5,6 +5,7 @@ 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.connector.gc.GCConnector; @@ -15,6 +16,7 @@ import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.network.HtmlImage; +import cgeo.geocaching.network.Network; import cgeo.geocaching.network.Parameters; import cgeo.geocaching.ui.CacheDetailsCreator; import cgeo.geocaching.ui.DecryptTextClickListener; @@ -79,7 +81,6 @@ import android.view.View.OnLongClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.ViewParent; -import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; @@ -92,7 +93,6 @@ import android.widget.ScrollView; import android.widget.TextView; import android.widget.TextView.BufferType; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; @@ -250,8 +250,8 @@ public class CacheDetailActivity extends AbstractActivity { // try to get data from URI if (geocode == null && guid == null && uri != null) { - String uriHost = uri.getHost().toLowerCase(); - String uriPath = uri.getPath().toLowerCase(); + String uriHost = uri.getHost().toLowerCase(Locale.US); + String uriPath = uri.getPath().toLowerCase(Locale.US); String uriQuery = uri.getQuery(); if (uriQuery != null) { @@ -265,11 +265,11 @@ public class CacheDetailActivity extends AbstractActivity { guid = uri.getQueryParameter("guid"); if (StringUtils.isNotBlank(geocode)) { - geocode = geocode.toUpperCase(); + geocode = geocode.toUpperCase(Locale.US); guid = null; } else if (StringUtils.isNotBlank(guid)) { geocode = null; - guid = guid.toLowerCase(); + guid = guid.toLowerCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); @@ -277,7 +277,7 @@ public class CacheDetailActivity extends AbstractActivity { } } else if (uriHost.contains("coord.info")) { if (uriPath != null && uriPath.startsWith("/gc")) { - geocode = uriPath.substring(1).toUpperCase(); + geocode = uriPath.substring(1).toUpperCase(Locale.US); } else { showToast(res.getString(R.string.err_detail_open)); finish(); @@ -300,7 +300,7 @@ public class CacheDetailActivity extends AbstractActivity { if (StringUtils.isNotBlank(name)) { title = name; } else if (null != geocode && StringUtils.isNotBlank(geocode)) { // can't be null, but the compiler doesn't understand StringUtils.isNotBlank() - title = geocode.toUpperCase(); + title = geocode; } progress.show(this, title, res.getString(R.string.cache_dialog_loading_details), true, loadCacheHandler.cancelMessage()); } catch (Exception e) { @@ -695,9 +695,9 @@ public class CacheDetailActivity extends AbstractActivity { // action bar: title and icon (default: mystery icon) if (StringUtils.isNotBlank(cache.getName())) { - setTitle(cache.getName() + " (" + cache.getGeocode().toUpperCase() + ')'); + setTitle(cache.getName() + " (" + cache.getGeocode() + ')'); } else { - setTitle(cache.getGeocode().toUpperCase()); + setTitle(cache.getGeocode()); } ((TextView) findViewById(R.id.actionbar_title)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(cache.getType().markerId), null, null, null); @@ -933,7 +933,7 @@ public class CacheDetailActivity extends AbstractActivity { cgeocaches.startActivityUserName(CacheDetailActivity.this, name.toString()); return; case 2: - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(name.toString())))); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + Network.encode(name.toString())))); return; default: break; @@ -962,13 +962,13 @@ public class CacheDetailActivity extends AbstractActivity { public static void startActivity(final Context context, final String geocode) { final Intent detailIntent = new Intent(context, CacheDetailActivity.class); - detailIntent.putExtra("geocode", geocode.toUpperCase()); + detailIntent.putExtra("geocode", geocode); context.startActivity(detailIntent); } public static void startActivity(final Context context, final String geocode, final int page) { final Intent detailIntent = new Intent(context, CacheDetailActivity.class); - detailIntent.putExtra("geocode", geocode.toUpperCase()); + detailIntent.putExtra("geocode", geocode); detailIntent.putExtra(EXTRAS_PAGE, page); context.startActivity(detailIntent); } @@ -1124,8 +1124,7 @@ public class CacheDetailActivity extends AbstractActivity { attributeBox.removeAllViews(); // maximum width for attribute icons is screen width - paddings of parents - attributeBoxMaxWidth = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)) - .getDefaultDisplay().getWidth(); + attributeBoxMaxWidth = Compatibility.getDisplayWidth(); ViewParent child = attributeBox; do { if (child instanceof View) { @@ -1378,7 +1377,7 @@ public class CacheDetailActivity extends AbstractActivity { details.add(R.string.cache_name, span); details.add(R.string.cache_type, cache.getType().getL10n()); details.addSize(cache); - details.add(R.string.cache_geocode, cache.getGeocode().toUpperCase()); + details.add(R.string.cache_geocode, cache.getGeocode()); details.addCacheState(cache); details.addDistance(cache, cacheDistanceView); diff --git a/main/src/cgeo/geocaching/CachePopup.java b/main/src/cgeo/geocaching/CachePopup.java index e01e4a0..5781d54 100644 --- a/main/src/cgeo/geocaching/CachePopup.java +++ b/main/src/cgeo/geocaching/CachePopup.java @@ -79,7 +79,7 @@ public class CachePopup extends AbstractPopupActivity { if (StringUtils.isNotBlank(cache.getName())) { setTitle(cache.getName()); } else { - setTitle(geocode.toUpperCase()); + setTitle(geocode); } // actionbar icon diff --git a/main/src/cgeo/geocaching/DirectionProvider.java b/main/src/cgeo/geocaching/DirectionProvider.java index 14fd283..c1f83ac 100644 --- a/main/src/cgeo/geocaching/DirectionProvider.java +++ b/main/src/cgeo/geocaching/DirectionProvider.java @@ -14,7 +14,7 @@ public class DirectionProvider extends MemorySubject<Float> implements SensorEve private final SensorManager sensorManager; - // Previous values signalled to observers to avoid resending the same value when the + // Previous values signaled to observers to avoid resending the same value when the // device doesn't change orientation. The orientation is usually given with a 1 degree // precision by Android, so it is not uncommon to obtain exactly the same value several // times. @@ -38,14 +38,14 @@ public class DirectionProvider extends MemorySubject<Float> implements SensorEve @Override public void onAccuracyChanged(final Sensor sensor, int accuracy) { /* - * There is a bug in Android, which appearently causes this method to be called every - * time the sensor _value_ changed, even if the _accuracy_ did not change. So logging - * this event leads to the log being flooded with multiple entries _per second_, - * which I experienced when running cgeo in a building (with GPS and network being - * unreliable). - * - * See for example https://code.google.com/p/android/issues/detail?id=14792 - */ + * There is a bug in Android, which apparently causes this method to be called every + * time the sensor _value_ changed, even if the _accuracy_ did not change. So logging + * this event leads to the log being flooded with multiple entries _per second_, + * which I experienced when running cgeo in a building (with GPS and network being + * unreliable). + * + * See for example https://code.google.com/p/android/issues/detail?id=14792 + */ //Log.i(Settings.tag, "Compass' accuracy is low (" + accuracy + ")"); } diff --git a/main/src/cgeo/geocaching/EditWaypointActivity.java b/main/src/cgeo/geocaching/EditWaypointActivity.java index ef2a2cc..07beea2 100644 --- a/main/src/cgeo/geocaching/EditWaypointActivity.java +++ b/main/src/cgeo/geocaching/EditWaypointActivity.java @@ -406,7 +406,7 @@ public class EditWaypointActivity extends AbstractActivity { app.saveCache(cache, EnumSet.of(SaveFlag.SAVE_DB)); StaticMapsProvider.removeWpStaticMaps(id, geocode); if (Settings.isStoreOfflineWpMaps()) { - StaticMapsProvider.storeWaypointStaticMap(cache, EditWaypointActivity.this, waypoint, false); + StaticMapsProvider.storeWaypointStaticMap(cache, waypoint, false); } finish(); } else { diff --git a/main/src/cgeo/geocaching/ImagesActivity.java b/main/src/cgeo/geocaching/ImagesActivity.java index 0accf12..234a2e9 100644 --- a/main/src/cgeo/geocaching/ImagesActivity.java +++ b/main/src/cgeo/geocaching/ImagesActivity.java @@ -86,7 +86,7 @@ public class ImagesActivity extends AbstractActivity { final Intent logImgIntent = new Intent(fromActivity, ImagesActivity.class); // if resuming our app within this activity, finish it and return to the cache activity logImgIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) - .putExtra(EXTRAS_GEOCODE, geocode.toUpperCase()) + .putExtra(EXTRAS_GEOCODE, geocode) .putExtra(EXTRAS_TYPE, imageType); // avoid forcing the array list as parameter type diff --git a/main/src/cgeo/geocaching/LogTrackableActivity.java b/main/src/cgeo/geocaching/LogTrackableActivity.java index 4ddec72..af56c6c 100644 --- a/main/src/cgeo/geocaching/LogTrackableActivity.java +++ b/main/src/cgeo/geocaching/LogTrackableActivity.java @@ -132,7 +132,7 @@ public class LogTrackableActivity extends AbstractLoggingActivity implements Dat if (StringUtils.isNotBlank(trackable.getName())) { setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getName()); } else { - setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode().toUpperCase()); + setTitle(res.getString(R.string.trackable_touch) + ": " + trackable.getGeocode()); } if (guid == null) { @@ -357,7 +357,7 @@ public class LogTrackableActivity extends AbstractLoggingActivity implements Dat public static void startActivity(final Context context, final cgTrackable trackable) { final Intent logTouchIntent = new Intent(context, LogTrackableActivity.class); - logTouchIntent.putExtra("geocode", trackable.getGeocode().toUpperCase()); + logTouchIntent.putExtra("geocode", trackable.getGeocode()); logTouchIntent.putExtra("guid", trackable.getGuid()); logTouchIntent.putExtra("trackingcode", trackable.getTrackingcode()); context.startActivity(logTouchIntent); diff --git a/main/src/cgeo/geocaching/SearchActivity.java b/main/src/cgeo/geocaching/SearchActivity.java index 5f2bddc..dd5f52d 100644 --- a/main/src/cgeo/geocaching/SearchActivity.java +++ b/main/src/cgeo/geocaching/SearchActivity.java @@ -28,6 +28,8 @@ import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; +import java.util.Locale; + public class SearchActivity extends AbstractActivity { private static final String EXTRAS_KEYWORDSEARCH = "keywordsearch"; @@ -104,7 +106,7 @@ public class SearchActivity extends AbstractActivity { final IConnector connector = ConnectorFactory.getConnector(geocode); if (connector instanceof ISearchByGeocode) { final Intent cachesIntent = new Intent(this, CacheDetailActivity.class); - cachesIntent.putExtra("geocode", geocode.toUpperCase()); + cachesIntent.putExtra("geocode", geocode.toUpperCase(Locale.US)); startActivity(cachesIntent); return true; } @@ -113,7 +115,7 @@ public class SearchActivity extends AbstractActivity { final String trackable = BaseUtils.getMatch(query, GCConstants.PATTERN_TB_CODE, true, 0, "", false); if (StringUtils.isNotBlank(trackable)) { final Intent trackablesIntent = new Intent(this, cgeotrackable.class); - trackablesIntent.putExtra("geocode", trackable.toUpperCase()); + trackablesIntent.putExtra("geocode", trackable.toUpperCase(Locale.US)); startActivity(trackablesIntent); return true; } @@ -402,7 +404,7 @@ public class SearchActivity extends AbstractActivity { } final Intent trackablesIntent = new Intent(this, cgeotrackable.class); - trackablesIntent.putExtra("geocode", trackableText.toUpperCase()); + trackablesIntent.putExtra("geocode", trackableText.toUpperCase(Locale.US)); startActivity(trackablesIntent); } diff --git a/main/src/cgeo/geocaching/Settings.java b/main/src/cgeo/geocaching/Settings.java index e1ae9c0..6845169 100644 --- a/main/src/cgeo/geocaching/Settings.java +++ b/main/src/cgeo/geocaching/Settings.java @@ -75,7 +75,6 @@ public final class Settings { private static final String KEY_AUTO_VISIT_TRACKABLES = "trackautovisit"; private static final String KEY_AUTO_INSERT_SIGNATURE = "sigautoinsert"; private static final String KEY_ALTITUDE_CORRECTION = "altcorrection"; - private static final String KEY_USE_GOOGLE_NAVIGATION = "usegnav"; private static final String KEY_STORE_LOG_IMAGES = "logimages"; private static final String KEY_EXCLUDE_DISABLED = "excludedisabled"; private static final String KEY_EXCLUDE_OWN = "excludemine"; @@ -192,7 +191,6 @@ public final class Settings { e.putBoolean(KEY_AUTO_VISIT_TRACKABLES, old.getBoolean(KEY_AUTO_VISIT_TRACKABLES, false)); e.putBoolean(KEY_AUTO_INSERT_SIGNATURE, old.getBoolean(KEY_AUTO_INSERT_SIGNATURE, false)); e.putInt(KEY_ALTITUDE_CORRECTION, old.getInt(KEY_ALTITUDE_CORRECTION, 0)); - e.putBoolean(KEY_USE_GOOGLE_NAVIGATION, 0 != old.getInt(KEY_USE_GOOGLE_NAVIGATION, 1)); e.putBoolean(KEY_STORE_LOG_IMAGES, old.getBoolean(KEY_STORE_LOG_IMAGES, false)); e.putBoolean(KEY_EXCLUDE_DISABLED, 0 != old.getInt(KEY_EXCLUDE_DISABLED, 0)); e.putBoolean(KEY_EXCLUDE_OWN, 0 != old.getInt(KEY_EXCLUDE_OWN, 0)); @@ -672,20 +670,6 @@ public final class Settings { }); } - public static boolean isUseGoogleNavigation() { - return sharedPrefs.getBoolean(KEY_USE_GOOGLE_NAVIGATION, true); - } - - public static void setUseGoogleNavigation(final boolean useGoogleNavigation) { - editSharedSettings(new PrefRunnable() { - - @Override - public void edit(Editor edit) { - edit.putBoolean(KEY_USE_GOOGLE_NAVIGATION, useGoogleNavigation); - } - }); - } - public static boolean isAutoLoadDescription() { return sharedPrefs.getBoolean(KEY_LOAD_DESCRIPTION, false); } diff --git a/main/src/cgeo/geocaching/SettingsActivity.java b/main/src/cgeo/geocaching/SettingsActivity.java index 823b52f..0eaaa39 100644 --- a/main/src/cgeo/geocaching/SettingsActivity.java +++ b/main/src/cgeo/geocaching/SettingsActivity.java @@ -5,7 +5,6 @@ import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory.NavigationAppsEnum; import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.gc.Login; -import cgeo.geocaching.enumerations.CacheType; import cgeo.geocaching.enumerations.StatusCode; import cgeo.geocaching.files.SimpleDirChooser; import cgeo.geocaching.maps.MapProviderFactory; @@ -495,16 +494,6 @@ public class SettingsActivity extends AbstractActivity { } }); - final CheckBox gnavButton = (CheckBox) findViewById(R.id.gnav); - gnavButton.setChecked(Settings.isUseGoogleNavigation()); - gnavButton.setOnClickListener(new View.OnClickListener() { - - @Override - public void onClick(View v) { - Settings.setUseGoogleNavigation(gnavButton.isChecked()); - } - }); - final CheckBox logOffline = (CheckBox) findViewById(R.id.log_offline); logOffline.setChecked(Settings.getLogOffline()); logOffline.setOnClickListener(new View.OnClickListener() { @@ -775,7 +764,7 @@ public class SettingsActivity extends AbstractActivity { */ public void backup(View view) { // avoid overwriting an existing backup with an empty database (can happen directly after reinstalling the app) - if (app.getAllStoredCachesCount(true, CacheType.ALL) == 0) { + if (cgeoapplication.getAllCachesCount() == 0) { helpDialog(res.getString(R.string.init_backup), res.getString(R.string.init_backup_unnecessary)); return; } diff --git a/main/src/cgeo/geocaching/StaticMapsActivity.java b/main/src/cgeo/geocaching/StaticMapsActivity.java index 05a18f2..e6173b2 100644 --- a/main/src/cgeo/geocaching/StaticMapsActivity.java +++ b/main/src/cgeo/geocaching/StaticMapsActivity.java @@ -186,13 +186,13 @@ public class StaticMapsActivity extends AbstractActivity { final cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); if (waypoint_id == null) { showToast(res.getString(R.string.info_storing_static_maps)); - StaticMapsProvider.storeCacheStaticMap(cache, this, true); + StaticMapsProvider.storeCacheStaticMap(cache, true); return cache.hasStaticMap(); } final cgWaypoint waypoint = cache.getWaypointById(waypoint_id); if (waypoint != null) { showToast(res.getString(R.string.info_storing_static_maps)); - StaticMapsProvider.storeWaypointStaticMap(cache, this, waypoint, true); + StaticMapsProvider.storeWaypointStaticMap(cache, waypoint, true); return StaticMapsProvider.hasStaticMapForWaypoint(geocode, waypoint_id); } showToast(res.getString(R.string.err_detail_not_load_map_static)); diff --git a/main/src/cgeo/geocaching/StaticMapsProvider.java b/main/src/cgeo/geocaching/StaticMapsProvider.java index 8292cb4..15193db 100644 --- a/main/src/cgeo/geocaching/StaticMapsProvider.java +++ b/main/src/cgeo/geocaching/StaticMapsProvider.java @@ -1,5 +1,6 @@ package cgeo.geocaching; +import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.concurrent.BlockingThreadPool; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.geopoint.GeopointFormatter.Format; @@ -12,10 +13,10 @@ import ch.boye.httpclientandroidlib.HttpResponse; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; -import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; +import android.graphics.Point; import android.util.DisplayMetrics; import android.view.Display; import android.view.WindowManager; @@ -80,11 +81,6 @@ public class StaticMapsProvider { } public static void downloadMaps(cgCache cache) { - final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - downloadMaps(cache, display); - } - - private static void downloadMaps(cgCache cache, Display display) { if (cache == null) { Log.e("downloadMaps - missing input parameter cache"); return; @@ -92,7 +88,7 @@ public class StaticMapsProvider { if ((!Settings.isStoreOfflineMaps() && !Settings.isStoreOfflineWpMaps()) || StringUtils.isBlank(cache.getGeocode())) { return; } - int edge = guessMaxDisplaySide(display); + int edge = guessMaxDisplaySide(); if (Settings.isStoreOfflineMaps() && cache.getCoords() != null) { storeCachePreviewMap(cache); @@ -109,8 +105,8 @@ public class StaticMapsProvider { } } - public static void storeWaypointStaticMap(cgCache cache, Activity activity, cgWaypoint waypoint, boolean waitForResult) { - int edge = StaticMapsProvider.guessMaxDisplaySide(activity); + public static void storeWaypointStaticMap(cgCache cache, cgWaypoint waypoint, boolean waitForResult) { + int edge = StaticMapsProvider.guessMaxDisplaySide(); storeWaypointStaticMap(cache.getGeocode(), edge, waypoint, waitForResult); } @@ -132,8 +128,8 @@ public class StaticMapsProvider { downloadMaps(geocode, wpMarkerUrl, WAYPOINT_PREFIX + waypoint.getId() + '_', wpLatlonMap, edge, null, waitForResult); } - public static void storeCacheStaticMap(cgCache cache, Activity activity, final boolean waitForResult) { - int edge = guessMaxDisplaySide(activity); + public static void storeCacheStaticMap(cgCache cache, final boolean waitForResult) { + int edge = guessMaxDisplaySide(); storeCacheStaticMap(cache, edge, waitForResult); } @@ -167,19 +163,16 @@ public class StaticMapsProvider { downloadMap(cache.getGeocode(), 15, ROADMAP, markerUrl, PREFIX_PREVIEW, "shadow:false|", latlonMap, width, height, null); } - private static int guessMaxDisplaySide(Display display) { - final int maxWidth = display.getWidth() - 25; - final int maxHeight = display.getHeight() - 25; + private static int guessMaxDisplaySide() { + Point displaySize = Compatibility.getDisplaySize(); + final int maxWidth = displaySize.x - 25; + final int maxHeight = displaySize.y - 25; if (maxWidth > maxHeight) { return maxWidth; } return maxHeight; } - private static int guessMaxDisplaySide(Activity activity) { - return guessMaxDisplaySide(((WindowManager) activity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay()); - } - private static void downloadMaps(final String geocode, final String markerUrl, final String prefix, final String latlonMap, final int edge, final Parameters waypoints, boolean waitForResult) { if (waitForResult) { diff --git a/main/src/cgeo/geocaching/VisitCacheActivity.java b/main/src/cgeo/geocaching/VisitCacheActivity.java index 443ef3a..8c9802e 100644 --- a/main/src/cgeo/geocaching/VisitCacheActivity.java +++ b/main/src/cgeo/geocaching/VisitCacheActivity.java @@ -42,6 +42,7 @@ import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; +import java.util.Locale; public class VisitCacheActivity extends AbstractLoggingActivity implements DateDialog.DateDialogParent { static final String EXTRAS_FOUND = "found"; @@ -261,7 +262,7 @@ public class VisitCacheActivity extends AbstractLoggingActivity implements DateD if (StringUtils.isNotBlank(cache.getName())) { setTitle(res.getString(R.string.log_new_log) + ": " + cache.getName()); } else { - setTitle(res.getString(R.string.log_new_log) + ": " + cache.getGeocode().toUpperCase()); + setTitle(res.getString(R.string.log_new_log) + ": " + cache.getGeocode()); } init(); @@ -335,7 +336,7 @@ public class VisitCacheActivity extends AbstractLoggingActivity implements DateD } private static String ratingTextValue(final double rating) { - return String.format("%.1f", rating); + return String.format(Locale.getDefault(), "%.1f", rating); } @Override diff --git a/main/src/cgeo/geocaching/WaypointPopup.java b/main/src/cgeo/geocaching/WaypointPopup.java index 7fbfe10..8596107 100644 --- a/main/src/cgeo/geocaching/WaypointPopup.java +++ b/main/src/cgeo/geocaching/WaypointPopup.java @@ -43,7 +43,7 @@ public class WaypointPopup extends AbstractPopupActivity { if (StringUtils.isNotBlank(waypoint.getName())) { setTitle(waypoint.getName()); } else { - setTitle(waypoint.getGeocode().toUpperCase()); + setTitle(waypoint.getGeocode()); } // actionbar icon @@ -53,7 +53,7 @@ public class WaypointPopup extends AbstractPopupActivity { details = new CacheDetailsCreator(this, (LinearLayout) findViewById(R.id.waypoint_details_list)); //Waypoint geocode - details.add(R.string.cache_geocode, waypoint.getPrefix().toUpperCase() + waypoint.getGeocode().toUpperCase().substring(2)); + details.add(R.string.cache_geocode, waypoint.getPrefix() + waypoint.getGeocode().substring(2)); // Edit Button final Button buttonEdit = (Button) findViewById(R.id.edit); diff --git a/main/src/cgeo/geocaching/apps/AbstractLocusApp.java b/main/src/cgeo/geocaching/apps/AbstractLocusApp.java index ac6fc1c..8f61e72 100644 --- a/main/src/cgeo/geocaching/apps/AbstractLocusApp.java +++ b/main/src/cgeo/geocaching/apps/AbstractLocusApp.java @@ -22,6 +22,7 @@ import android.location.Location; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; +import java.util.Locale; /** * for the Locus API: @@ -30,7 +31,7 @@ import java.util.List; */ public abstract class AbstractLocusApp extends AbstractApp { private static final String INTENT = Intent.ACTION_VIEW; - private static final SimpleDateFormat ISO8601DATE = new SimpleDateFormat("yyyy-MM-dd'T'"); + private static final SimpleDateFormat ISO8601DATE = new SimpleDateFormat("yyyy-MM-dd'T'", Locale.US); protected AbstractLocusApp() { super(getString(R.string.caches_map_locus), INTENT); @@ -47,11 +48,11 @@ public abstract class AbstractLocusApp extends AbstractApp { /** * Display a list of caches / waypoints in Locus - * + * * @param objectsToShow * which caches/waypoints to show * @param withCacheWaypoints - * wether to give waypoints of caches to Locus or not + * Whether to give waypoints of caches to Locus or not * @param activity */ protected static boolean showInLocus(final List<?> objectsToShow, final boolean withCacheWaypoints, final boolean export, @@ -85,7 +86,7 @@ public abstract class AbstractLocusApp extends AbstractApp { final ArrayList<PointsData> data = new ArrayList<PointsData>(); data.add(pd); DisplayData.sendDataCursor(activity, data, - "content://" + LocusDataStorageProvider.class.getCanonicalName().toLowerCase(), + "content://" + LocusDataStorageProvider.class.getCanonicalName().toLowerCase(Locale.US), export); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsDirectionApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsDirectionApp.java new file mode 100644 index 0000000..db4fc1c --- /dev/null +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleMapsDirectionApp.java @@ -0,0 +1,48 @@ +package cgeo.geocaching.apps.cache.navi; + +import cgeo.geocaching.IGeoData; +import cgeo.geocaching.R; +import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.maps.MapProviderFactory; +import cgeo.geocaching.utils.Log; + +import android.app.Activity; +import android.content.Intent; +import android.net.Uri; + +public class GoogleMapsDirectionApp extends AbstractPointNavigationApp { + + protected GoogleMapsDirectionApp() { + super(getString(R.string.cache_menu_maps_directions), null); + } + + @Override + public boolean isInstalled() { + return MapProviderFactory.isGoogleMapsInstalled(); + } + + @Override + public void navigate(Activity activity, Geopoint coords) { + try { + IGeoData geo = cgeoapplication.getInstance().currentGeo(); + final Geopoint coordsNow = geo == null ? null : geo.getCoords(); + + if (coordsNow != null) { + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri + .parse("http://maps.google.com/maps?f=d&saddr=" + + coordsNow.getLatitude() + "," + coordsNow.getLongitude() + "&daddr=" + + coords.getLatitude() + "," + coords.getLongitude()))); + } else { + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri + .parse("http://maps.google.com/maps?f=d&daddr=" + + coords.getLatitude() + "," + coords.getLongitude()))); + } + + } catch (Exception e) { + Log.i("GoogleMapsDirection: application not available."); + } + + } + +} diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java index 7258e11..e74eb89 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java @@ -1,10 +1,6 @@ package cgeo.geocaching.apps.cache.navi; -import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; -import cgeo.geocaching.Settings; -import cgeo.geocaching.cgeoapplication; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; @@ -12,10 +8,13 @@ import android.app.Activity; import android.content.Intent; import android.net.Uri; -class GoogleNavigationApp extends AbstractPointNavigationApp { +abstract class GoogleNavigationApp extends AbstractPointNavigationApp { - GoogleNavigationApp() { - super(getString(R.string.cache_menu_tbt), null); + private final String mode; + + GoogleNavigationApp(final int nameResourceId, final String mode) { + super(getString(nameResourceId), null); + this.mode = mode; } @Override @@ -23,49 +22,27 @@ class GoogleNavigationApp extends AbstractPointNavigationApp { return true; } - private static boolean navigateToCoordinates(Activity activity, final Geopoint coords) { - IGeoData geo = cgeoapplication.getInstance().currentGeo(); - final Geopoint coordsNow = geo == null ? null : geo.getCoords(); - - // Google Navigation - if (Settings.isUseGoogleNavigation()) { - try { - activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri - .parse("google.navigation:ll=" + coords.getLatitude() + "," - + coords.getLongitude()))); - - return true; - } catch (Exception e) { - // nothing - } - } - - // Google Maps Directions + @Override + public void navigate(Activity activity, Geopoint coords) { try { - if (coordsNow != null) { - activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri - .parse("http://maps.google.com/maps?f=d&saddr=" - + coordsNow.getLatitude() + "," + coordsNow.getLongitude() + "&daddr=" - + coords.getLatitude() + "," + coords.getLongitude()))); - } else { - activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri - .parse("http://maps.google.com/maps?f=d&daddr=" - + coords.getLatitude() + "," + coords.getLongitude()))); - } + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri + .parse("google.navigation:ll=" + coords.getLatitude() + "," + + coords.getLongitude() + mode))); - return true; } catch (Exception e) { - // nothing + Log.i("cgBase.runNavigation: No navigation application available."); } + } - Log.i("cgBase.runNavigation: No navigation application available."); - return false; + static class GoogleNavigationWalkingApp extends GoogleNavigationApp { + GoogleNavigationWalkingApp() { + super(R.string.cache_menu_navigation_walk, "&mode=w"); + } } - @Override - public void navigate(Activity activity, Geopoint coords) { - if (!navigateToCoordinates(activity, coords)) { - ActivityMixin.showToast(activity, getString(R.string.err_navigation_no)); + static class GoogleNavigationDrivingApp extends GoogleNavigationApp { + GoogleNavigationDrivingApp() { + super(R.string.cache_menu_navigation_drive, "&mode=d"); } } }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java index 57a71bb..0ff4af2 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java @@ -8,6 +8,8 @@ import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.apps.App; +import cgeo.geocaching.apps.cache.navi.GoogleNavigationApp.GoogleNavigationDrivingApp; +import cgeo.geocaching.apps.cache.navi.GoogleNavigationApp.GoogleNavigationWalkingApp; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; @@ -40,7 +42,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** Google Maps */ GOOGLE_MAPS(new GoogleMapsApp(), 6), /** Google Navigation */ - GOOGLE_NAVIGATION(new GoogleNavigationApp(), 7), + GOOGLE_NAVIGATION(new GoogleNavigationDrivingApp(), 7), /** Google Streetview */ GOOGLE_STREETVIEW(new StreetviewApp(), 8), /** The external OruxMaps app */ @@ -48,7 +50,15 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** The external navigon app */ NAVIGON(new NavigonApp(), 10), /** The external Sygic app */ - SYGIC(new SygicNavigationApp(), 11); + SYGIC(new SygicNavigationApp(), 11), + /** + * Google Navigation in walking mode + */ + GOOGLE_NAVIGATION_WALK(new GoogleNavigationWalkingApp(), 12), + /** + * Google Maps Directions + */ + GOOGLE_MAPS_DIRECTIONS(new GoogleMapsDirectionApp(), 13); NavigationAppsEnum(App app, int id) { this.app = app; diff --git a/main/src/cgeo/geocaching/cgCache.java b/main/src/cgeo/geocaching/cgCache.java index 9286cdc..dfc18ab 100644 --- a/main/src/cgeo/geocaching/cgCache.java +++ b/main/src/cgeo/geocaching/cgCache.java @@ -441,7 +441,7 @@ public class cgCache implements ICache, IWaypoint { } Intent logVisitIntent = new Intent((Activity) fromActivity, VisitCacheActivity.class); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_ID, cacheId); - logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_GEOCODE, geocode.toUpperCase()); + logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_GEOCODE, geocode); logVisitIntent.putExtra(VisitCacheActivity.EXTRAS_FOUND, found); ((Activity) fromActivity).startActivity(logVisitIntent); @@ -661,7 +661,7 @@ public class cgCache implements ICache, IWaypoint { } StringBuilder subject = new StringBuilder("Geocache "); - subject.append(geocode.toUpperCase()); + subject.append(geocode); if (StringUtils.isNotBlank(name)) { subject.append(" - ").append(name); } @@ -1015,7 +1015,7 @@ public class cgCache implements ICache, IWaypoint { } public void setGeocode(String geocode) { - this.geocode = geocode; + this.geocode = StringUtils.upperCase(geocode); } public void setCacheId(String cacheId) { diff --git a/main/src/cgeo/geocaching/cgData.java b/main/src/cgeo/geocaching/cgData.java index b822c2b..83b45ab 100644 --- a/main/src/cgeo/geocaching/cgData.java +++ b/main/src/cgeo/geocaching/cgData.java @@ -23,7 +23,6 @@ import android.content.ContextWrapper; import android.content.res.Resources; import android.database.Cursor; import android.database.DatabaseUtils; -import android.database.DatabaseUtils.InsertHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteDoneException; @@ -73,7 +72,7 @@ public class cgData { */ private static int[] cacheColumnIndex; private CacheCache cacheCache = new CacheCache(); - private SQLiteDatabase database = null; + private static SQLiteDatabase database = null; private static final int dbVersion = 64; public static final int customListIdOffset = 10; private static final String dbName = "data"; @@ -151,9 +150,6 @@ public class cgData { + "updated long not null, " // date of save + "attribute text " + "); "; - private final static int ATTRIBUTES_GEOCODE = 2; - private final static int ATTRIBUTES_UPDATED = 3; - private final static int ATTRIBUTES_ATTRIBUTE = 4; private static final String dbCreateWaypoints = "" + "create table " + dbTableWaypoints + " (" @@ -191,14 +187,6 @@ public class cgData { + "found integer not null default 0, " + "friend integer " + "); "; - private final static int LOGS_GEOCODE = 2; - private final static int LOGS_UPDATED = 3; - private final static int LOGS_TYPE = 4; - private final static int LOGS_AUTHOR = 5; - private final static int LOGS_LOG = 6; - private final static int LOGS_DATE = 7; - private final static int LOGS_FOUND = 8; - private final static int LOGS_FRIEND = 9; private static final String dbCreateLogCount = "" + "create table " + dbTableLogCount + " (" @@ -246,7 +234,6 @@ public class cgData { + "longitude double " + "); "; - private HashMap<String, SQLiteStatement> statements = new HashMap<String, SQLiteStatement>(); private static boolean newlyCreatedDatabase = false; public synchronized void init() { @@ -268,18 +255,11 @@ public class cgData { } cacheCache.removeAllFromCache(); - clearPreparedStatements(); + PreparedStatements.clearPreparedStatements(); database.close(); database = null; } - private void clearPreparedStatements() { - for (SQLiteStatement statement : statements.values()) { - statement.close(); - } - statements.clear(); - } - private static File backupFile() { return new File(LocalStorage.getStorage(), "cgeo.sqlite"); } @@ -888,11 +868,11 @@ public class cgData { final SQLiteStatement listId; final String value; if (StringUtils.isNotBlank(geocode)) { - listId = getStatementListIdFromGeocode(); + listId = PreparedStatements.getListIdOfGeocode(); value = geocode; } else { - listId = getStatementListIdFromGuid(); + listId = PreparedStatements.getListIdOfGuid(); value = guid; } synchronized (listId) { @@ -915,7 +895,7 @@ public class cgData { init(); try { - final SQLiteStatement description = getStatementGeocode(); + final SQLiteStatement description = PreparedStatements.getGeocodeOfGuid(); synchronized (description) { description.bindString(1, guid); return description.simpleQueryForString(); @@ -936,7 +916,7 @@ public class cgData { init(); try { - final SQLiteStatement description = getStatementCacheId(); + final SQLiteStatement description = PreparedStatements.getCacheIdOfGeocode(); synchronized (description) { description.bindString(1, geocode); return description.simpleQueryForString(); @@ -1062,7 +1042,7 @@ public class cgData { database.setTransactionSuccessful(); result = true; } catch (Exception e) { - // nothing + Log.e("SaveCache", e); } finally { database.endTransaction(); } @@ -1070,25 +1050,21 @@ public class cgData { return result; } - private void saveAttributesWithoutTransaction(final cgCache cache) { + private static void saveAttributesWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableAttributes, "geocode = ?", new String[]{geocode}); - if (cache.getAttributes().isNotEmpty()) { - - InsertHelper helper = new InsertHelper(database, dbTableAttributes); - long timeStamp = System.currentTimeMillis(); - - for (String attribute : cache.getAttributes()) { - helper.prepareForInsert(); - - helper.bind(ATTRIBUTES_GEOCODE, geocode); - helper.bind(ATTRIBUTES_UPDATED, timeStamp); - helper.bind(ATTRIBUTES_ATTRIBUTE, attribute); + if (cache.getAttributes().isEmpty()) { + return; + } + SQLiteStatement statement = PreparedStatements.getInsertAttribute(); + final long timestamp = System.currentTimeMillis(); + for (String attribute : cache.getAttributes()) { + statement.bindString(1, geocode); + statement.bindLong(2, timestamp); + statement.bindString(3, attribute); - helper.execute(); - } - helper.close(); + statement.executeInsert(); } } @@ -1104,10 +1080,8 @@ public class cgData { database.beginTransaction(); try { - ContentValues values = new ContentValues(); - values.put("date", destination.getDate()); - putCoords(values, destination.getCoords()); - database.insert(dbTableSearchDestionationHistory, null, values); + SQLiteStatement insertDestination = PreparedStatements.getInsertSearchDestination(destination); + insertDestination.executeInsert(); database.setTransactionSuccessful(); } catch (Exception e) { Log.e("Updating searchedDestinations db failed", e); @@ -1133,7 +1107,7 @@ public class cgData { return result; } - private void saveOriginalWaypointsWithoutTransaction(final cgCache cache) { + private static void saveOriginalWaypointsWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableWaypoints, "geocode = ? and type <> ? and own = 0", new String[]{geocode, "own"}); @@ -1244,28 +1218,32 @@ public class cgData { return database.delete(dbTableWaypoints, "_id = " + id, null) > 0; } - private void saveSpoilersWithoutTransaction(final cgCache cache) { + private static void saveSpoilersWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableSpoilers, "geocode = ?", new String[]{geocode}); List<cgImage> spoilers = cache.getSpoilers(); if (CollectionUtils.isNotEmpty(spoilers)) { - ContentValues values = new ContentValues(); - long timeStamp = System.currentTimeMillis(); + SQLiteStatement insertSpoiler = PreparedStatements.getInsertSpoiler(); + final long timestamp = System.currentTimeMillis(); for (cgImage spoiler : spoilers) { - values.clear(); - values.put("geocode", geocode); - values.put("updated", timeStamp); - values.put("url", spoiler.getUrl()); - values.put("title", spoiler.getTitle()); - values.put("description", spoiler.getDescription()); - - database.insert(dbTableSpoilers, null, values); + insertSpoiler.bindString(1, geocode); + insertSpoiler.bindLong(2, timestamp); + insertSpoiler.bindString(3, spoiler.getUrl()); + insertSpoiler.bindString(4, spoiler.getTitle()); + final String description = spoiler.getDescription(); + if (description != null) { + insertSpoiler.bindString(5, description); + } + else { + insertSpoiler.bindNull(5); + } + insertSpoiler.executeInsert(); } } } - private void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) { + private static void saveLogsWithoutTransaction(final String geocode, final Iterable<LogEntry> logs) { // TODO delete logimages referring these logs database.delete(dbTableLogs, "geocode = ?", new String[]{geocode}); @@ -1273,54 +1251,46 @@ public class cgData { return; } - InsertHelper helper = new InsertHelper(database, dbTableLogs); - long timeStamp = System.currentTimeMillis(); + SQLiteStatement insertLog = PreparedStatements.getInsertLog(); + final long timestamp = System.currentTimeMillis(); for (LogEntry log : logs) { - helper.prepareForInsert(); - - helper.bind(LOGS_GEOCODE, geocode); - helper.bind(LOGS_UPDATED, timeStamp); - helper.bind(LOGS_TYPE, log.type.id); - helper.bind(LOGS_AUTHOR, log.author); - helper.bind(LOGS_LOG, log.log); - helper.bind(LOGS_DATE, log.date); - helper.bind(LOGS_FOUND, log.found); - helper.bind(LOGS_FRIEND, log.friend); - - long log_id = helper.execute(); - + insertLog.bindString(1, geocode); + insertLog.bindLong(2, timestamp); + insertLog.bindLong(3, log.type.id); + insertLog.bindString(4, log.author); + insertLog.bindString(5, log.log); + insertLog.bindLong(6, log.date); + insertLog.bindLong(7, log.found); + insertLog.bindLong(8, log.friend ? 1 : 0); + long logId = insertLog.executeInsert(); if (log.hasLogImages()) { - ContentValues values = new ContentValues(); + SQLiteStatement insertImage = PreparedStatements.getInsertLogImage(); for (cgImage img : log.getLogImages()) { - values.clear(); - values.put("log_id", log_id); - values.put("title", img.getTitle()); - values.put("url", img.getUrl()); - database.insert(dbTableLogImages, null, values); + insertImage.bindLong(1, logId); + insertImage.bindString(2, img.getTitle()); + insertImage.bindString(3, img.getUrl()); + insertImage.executeInsert(); } } } - helper.close(); } - private void saveLogCountsWithoutTransaction(final cgCache cache) { + private static void saveLogCountsWithoutTransaction(final cgCache cache) { String geocode = cache.getGeocode(); database.delete(dbTableLogCount, "geocode = ?", new String[]{geocode}); Map<LogType, Integer> logCounts = cache.getLogCounts(); if (MapUtils.isNotEmpty(logCounts)) { - ContentValues values = new ContentValues(); - Set<Entry<LogType, Integer>> logCountsItems = logCounts.entrySet(); - long timeStamp = System.currentTimeMillis(); + SQLiteStatement insertLogCounts = PreparedStatements.getInsertLogCounts(); + final long timestamp = System.currentTimeMillis(); for (Entry<LogType, Integer> pair : logCountsItems) { - values.clear(); - values.put("geocode", geocode); - values.put("updated", timeStamp); - values.put("type", pair.getKey().id); - values.put("count", pair.getValue()); + insertLogCounts.bindString(1, geocode); + insertLogCounts.bindLong(2, timestamp); + insertLogCounts.bindLong(3, pair.getKey().id); + insertLogCounts.bindLong(4, pair.getValue()); - database.insert(dbTableLogCount, null, values); + insertLogCounts.executeInsert(); } } } @@ -1339,7 +1309,7 @@ public class cgData { return true; } - private void saveInventoryWithoutTransaction(final String geocode, final List<cgTrackable> trackables) { + private static void saveInventoryWithoutTransaction(final String geocode, final List<cgTrackable> trackables) { if (geocode != null) { database.delete(dbTableTrackables, "geocode = ?", new String[]{geocode}); } @@ -2095,84 +2065,65 @@ public class cgData { } /** - * Number of caches stored. The number is shown on the starting activity of c:geo + * Number of caches stored for a given type and/or list * - * @param detailedOnly * @param cacheType * @param list * @return */ - public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final int list) { + public int getAllStoredCachesCount(final CacheType cacheType, final int list) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } - init(); - - String listSql; - String listSqlW; - if (list == 0) { - listSql = " where reason >= 1"; - listSqlW = " and reason >= 1"; - } else if (list >= 1) { - listSql = " where reason = " + list; - listSqlW = " and reason = " + list; - } else { - return 0; + if (list < 0) { + throw new IllegalArgumentException("list must be >= 0"); } + init(); - int count = 0; try { - String sql; - if (!detailedOnly) { - if (cacheType == CacheType.ALL) { - sql = "select count(_id) from " + dbTableCaches + listSql; - } else { - sql = "select count(_id) from " + dbTableCaches + " where type = " + DatabaseUtils.sqlEscapeString(cacheType.id) + listSqlW; - } - } else { - if (cacheType == CacheType.ALL) { - sql = "select count(_id) from " + dbTableCaches + " where detailed = 1" + listSqlW; - } else { - sql = "select count(_id) from " + dbTableCaches + " where detailed = 1 and type = " + DatabaseUtils.sqlEscapeString(cacheType.id) + listSqlW; - } + StringBuilder sql = new StringBuilder("select count(_id) from " + dbTableCaches + " where detailed = 1"); + if (cacheType != CacheType.ALL) { + sql.append(" and type = " + DatabaseUtils.sqlEscapeString(cacheType.id)); + } + if (list == 0) { + sql.append(" and reason > 0"); + } else if (list >= 1) { + sql.append(" and reason = " + list); } - SQLiteStatement compiledStmnt = database.compileStatement(sql); - count = (int) compiledStmnt.simpleQueryForLong(); - compiledStmnt.close(); + + String key = "CountCaches_" + cacheType.id + "_" + Integer.toString(list); + + SQLiteStatement compiledStmnt = PreparedStatements.getStatement(key, sql.toString()); + return (int) compiledStmnt.simpleQueryForLong(); } catch (Exception e) { Log.e("cgData.loadAllStoredCachesCount: " + e.toString()); } - return count; + return 0; } - public int getAllHistoricCachesCount() { + public int getAllHistoryCachesCount() { init(); - int count = 0; - try { - SQLiteStatement sqlCount = database.compileStatement("select count(_id) from " + dbTableCaches + " where visiteddate > 0"); - count = (int) sqlCount.simpleQueryForLong(); - sqlCount.close(); + return (int) PreparedStatements.getCountHistoryCaches().simpleQueryForLong(); } catch (Exception e) { Log.e("cgData.getAllHistoricCachesCount: " + e.toString()); } - return count; + return 0; } /** * Return a batch of stored geocodes. * - * @param detailedOnly * @param coords * the current coordinates to sort by distance, or null to sort by geocode * @param cacheType * @param listId * @return */ - public Set<String> loadBatchOfStoredGeocodes(final boolean detailedOnly, final Geopoint coords, final CacheType cacheType, final int listId) { + public Set<String> loadBatchOfStoredGeocodes(final Geopoint coords, final CacheType cacheType, final int listId) { if (cacheType == null) { throw new IllegalArgumentException("cacheType must not be null"); } @@ -2184,10 +2135,7 @@ public class cgData { specifySql.append("reason "); specifySql.append(listId != StoredList.ALL_LIST_ID ? "=" + Math.max(listId, 1) : ">= " + StoredList.STANDARD_LIST_ID); - - if (detailedOnly) { - specifySql.append(" and detailed = 1 "); - } + specifySql.append(" and detailed = 1 "); if (cacheType != CacheType.ALL) { specifySql.append(" and type = "); @@ -2420,11 +2368,6 @@ public class cgData { removeCaches(geocodes, LoadFlags.REMOVE_ALL); } - final SQLiteStatement countSql = database.compileStatement("select count(_id) from " + dbTableCaches + " where reason = 0"); - final int count = (int) countSql.simpleQueryForLong(); - countSql.close(); - Log.d("Database clean: " + count + " geocaches remaining for listId=0"); - } catch (Exception e) { Log.w("cgData.clean: " + e.toString()); } @@ -2567,27 +2510,6 @@ public class cgData { database.delete(dbTableLogsOffline, "geocode = ?", new String[]{geocode}); } - private SQLiteStatement getStatementLogCount() { - return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + dbTableLogsOffline + " WHERE geocode = ?"); - } - - private synchronized SQLiteStatement getStatement(final String key, final String query) { - SQLiteStatement statement = statements.get(key); - if (statement == null) { - statement = database.compileStatement(query); - statements.put(key, statement); - } - return statement; - } - - private SQLiteStatement getStatementCountStandardList() { - return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID); - } - - private SQLiteStatement getStatementCountAllLists() { - return getStatement("CountAllLists", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason >= " + StoredList.STANDARD_LIST_ID); - } - public boolean hasLogOffline(final String geocode) { if (StringUtils.isBlank(geocode)) { return false; @@ -2595,7 +2517,7 @@ public class cgData { init(); try { - final SQLiteStatement logCount = getStatementLogCount(); + final SQLiteStatement logCount = PreparedStatements.getLogCountOfGeocode(); synchronized (logCount) { logCount.bindString(1, geocode); return logCount.simpleQueryForLong() > 0; @@ -2616,11 +2538,12 @@ public class cgData { database.beginTransaction(); try { - ContentValues values = new ContentValues(); - values.put("visiteddate", visitedDate); + SQLiteStatement setVisit = PreparedStatements.getUpdateVisitDate(); for (String geocode : geocodes) { - database.update(dbTableCaches, values, "geocode = ?", new String[]{geocode}); + setVisit.bindLong(1, visitedDate); + setVisit.bindString(2, geocode); + setVisit.execute(); } database.setTransactionSuccessful(); } finally { @@ -2632,7 +2555,7 @@ public class cgData { init(); List<StoredList> lists = new ArrayList<StoredList>(); - lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong())); + lists.add(new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong())); try { String query = "SELECT l._id as _id, l.title as title, COUNT(c._id) as count" + @@ -2692,17 +2615,21 @@ public class cgData { } if (id == StoredList.ALL_LIST_ID) { - return new StoredList(StoredList.ALL_LIST_ID, res.getString(R.string.list_all_lists), (int) getStatementCountAllLists().simpleQueryForLong()); + return new StoredList(StoredList.ALL_LIST_ID, res.getString(R.string.list_all_lists), getAllCachesCount()); } // fall back to standard list in case of invalid list id if (id == StoredList.STANDARD_LIST_ID || id >= customListIdOffset) { - return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) getStatementCountStandardList().simpleQueryForLong()); + return new StoredList(StoredList.STANDARD_LIST_ID, res.getString(R.string.list_inbox), (int) PreparedStatements.getCountCachesOnStandardList().simpleQueryForLong()); } return null; } + public static int getAllCachesCount() { + return (int) PreparedStatements.getCountAllCaches().simpleQueryForLong(); + } + /** * Create a new list * @@ -2770,22 +2697,22 @@ public class cgData { * @return true if the list got deleted, false else */ public boolean removeList(int listId) { - boolean status = false; if (listId < customListIdOffset) { - return status; + return false; } init(); + boolean status = false; database.beginTransaction(); try { int cnt = database.delete(dbTableLists, "_id = " + (listId - customListIdOffset), null); if (cnt > 0) { // move caches from deleted list to standard list - ContentValues values = new ContentValues(); - values.put("reason", StoredList.STANDARD_LIST_ID); - database.update(dbTableCaches, values, "reason = " + listId, null); + SQLiteStatement moveToStandard = PreparedStatements.getMoveToStandardList(); + moveToStandard.bindLong(1, listId); + moveToStandard.execute(); status = true; } @@ -2807,13 +2734,14 @@ public class cgData { } init(); - final ContentValues values = new ContentValues(); - values.put("reason", listId); + SQLiteStatement move = PreparedStatements.getMoveToList(); database.beginTransaction(); try { for (cgCache cache : caches) { - database.update(dbTableCaches, values, "geocode = ?", new String[]{cache.getGeocode()}); + move.bindLong(1, listId); + move.bindString(2, cache.getGeocode()); + move.execute(); cache.setListId(listId); } database.setTransactionSuccessful(); @@ -2822,9 +2750,8 @@ public class cgData { } } - public synchronized boolean status() { + public boolean status() { return database != null; - } public boolean removeSearchedDestination(Destination destination) { @@ -2849,26 +2776,6 @@ public class cgData { return success; } - private SQLiteStatement getStatementDescription() { - return getStatement("descriptionFromGeocode", "SELECT description FROM " + dbTableCaches + " WHERE geocode = ?"); - } - - private SQLiteStatement getStatementListIdFromGeocode() { - return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE geocode = ?"); - } - - private SQLiteStatement getStatementListIdFromGuid() { - return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE guid = ?"); - } - - private SQLiteStatement getStatementCacheId() { - return getStatement("cacheIdFromGeocode", "SELECT cacheid FROM " + dbTableCaches + " WHERE geocode = ?"); - } - - private SQLiteStatement getStatementGeocode() { - return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"); - } - public String getCacheDescription(String geocode) { if (StringUtils.isBlank(geocode)) { return null; @@ -2876,7 +2783,7 @@ public class cgData { init(); try { - final SQLiteStatement description = getStatementDescription(); + final SQLiteStatement description = PreparedStatements.getDescriptionOfGeocode(); synchronized (description) { description.bindString(1, geocode); return description.simpleQueryForString(); @@ -2997,4 +2904,108 @@ public class cgData { return list.toArray(new String[list.size()]); } + private static class PreparedStatements { + + private static HashMap<String, SQLiteStatement> statements = new HashMap<String, SQLiteStatement>(); + + private PreparedStatements() { + // utility class + } + + public static SQLiteStatement getMoveToStandardList() { + return getStatement("MoveToStandardList", "UPDATE " + dbTableCaches + " SET reason = " + StoredList.STANDARD_LIST_ID + " WHERE reason = ?"); + } + + public static SQLiteStatement getMoveToList() { + return getStatement("MoveToList", "UPDATE " + dbTableCaches + " SET reason = ? WHERE geocode = ?"); + } + + public static SQLiteStatement getUpdateVisitDate() { + return getStatement("UpdateVisitDate", "UPDATE " + dbTableCaches + " SET visiteddate = ? WHERE geocode = ?"); + } + + public static SQLiteStatement getInsertLogImage() { + return getStatement("InsertLogImage", "INSERT INTO " + dbTableLogImages + " (log_id, title, url) VALUES (?, ?, ?)"); + } + + public static SQLiteStatement getInsertLogCounts() { + return getStatement("InsertLogCounts", "INSERT INTO " + dbTableLogCount + " (geocode, updated, type, count) VALUES (?, ?, ?, ?)"); + } + + public static SQLiteStatement getInsertSpoiler() { + return getStatement("InsertSpoiler", "INSERT INTO " + dbTableSpoilers + " (geocode, updated, url, title, description) VALUES (?, ?, ?, ?, ?)"); + } + + public static SQLiteStatement getInsertSearchDestination(Destination destination) { + final SQLiteStatement statement = getStatement("InsertSearch", "INSERT INTO " + dbTableSearchDestionationHistory + " (date, latitude, longitude) VALUES (?, ?, ?)"); + statement.bindLong(1, destination.getDate()); + final Geopoint coords = destination.getCoords(); + statement.bindDouble(2, coords.getLatitude()); + statement.bindDouble(3, coords.getLongitude()); + return statement; + } + + private static void clearPreparedStatements() { + for (SQLiteStatement statement : statements.values()) { + statement.close(); + } + statements.clear(); + } + + private static synchronized SQLiteStatement getStatement(final String key, final String query) { + SQLiteStatement statement = statements.get(key); + if (statement == null) { + Log.i("Compiling " + key); + statement = database.compileStatement(query); + statements.put(key, statement); + } + return statement; + } + + public static SQLiteStatement getCountHistoryCaches() { + return getStatement("HistoryCount", "select count(_id) from " + dbTableCaches + " where visiteddate > 0"); + } + + private static SQLiteStatement getLogCountOfGeocode() { + return getStatement("LogCountFromGeocode", "SELECT count(_id) FROM " + cgData.dbTableLogsOffline + " WHERE geocode = ?"); + } + + private static SQLiteStatement getCountCachesOnStandardList() { + return getStatement("CountStandardList", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason = " + StoredList.STANDARD_LIST_ID); + } + + private static SQLiteStatement getCountAllCaches() { + return getStatement("CountAllLists", "SELECT count(_id) FROM " + dbTableCaches + " WHERE reason >= " + StoredList.STANDARD_LIST_ID); + } + + private static SQLiteStatement getInsertLog() { + return getStatement("InsertLog", "INSERT INTO " + dbTableLogs + " (geocode, updated, type, author, log, date, found, friend) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"); + } + + private static SQLiteStatement getInsertAttribute() { + return getStatement("InsertAttribute", "INSERT INTO " + dbTableAttributes + " (geocode, updated, attribute) VALUES (?, ?, ?)"); + } + + private static SQLiteStatement getDescriptionOfGeocode() { + return getStatement("descriptionFromGeocode", "SELECT description FROM " + dbTableCaches + " WHERE geocode = ?"); + } + + private static SQLiteStatement getListIdOfGeocode() { + return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE geocode = ?"); + } + + private static SQLiteStatement getListIdOfGuid() { + return getStatement("listFromGeocode", "SELECT reason FROM " + dbTableCaches + " WHERE guid = ?"); + } + + private static SQLiteStatement getCacheIdOfGeocode() { + return getStatement("cacheIdFromGeocode", "SELECT cacheid FROM " + dbTableCaches + " WHERE geocode = ?"); + } + + private static SQLiteStatement getGeocodeOfGuid() { + return getStatement("geocodeFromGuid", "SELECT geocode FROM " + dbTableCaches + " WHERE guid = ?"); + } + + } + } diff --git a/main/src/cgeo/geocaching/cgTrackable.java b/main/src/cgeo/geocaching/cgTrackable.java index 7ed3424..b03a783 100644 --- a/main/src/cgeo/geocaching/cgTrackable.java +++ b/main/src/cgeo/geocaching/cgTrackable.java @@ -38,8 +38,8 @@ public class cgTrackable implements ILogable { private String trackingcode = null; public String getUrl() { - if (StringUtils.startsWithIgnoreCase(geocode, "GK")) { - String hex = geocode.substring(3); + if (StringUtils.startsWithIgnoreCase(getGeocode(), "GK")) { + String hex = getGeocode().substring(3); try { int id = Integer.parseInt(hex, 16); return "http://geokrety.org/konkret.php?id=" + id; @@ -48,7 +48,7 @@ public class cgTrackable implements ILogable { return null; } } - return "http://www.geocaching.com//track/details.aspx?tracker=" + geocode.toUpperCase(); + return "http://www.geocaching.com//track/details.aspx?tracker=" + geocode; } public String getGuid() { @@ -65,7 +65,7 @@ public class cgTrackable implements ILogable { } public void setGeocode(String geocode) { - this.geocode = geocode; + this.geocode = StringUtils.upperCase(geocode); } public String getIconUrl() { @@ -208,7 +208,7 @@ public class cgTrackable implements ILogable { } public boolean isLoggable() { - return !StringUtils.startsWithIgnoreCase(geocode, "GK"); + return !StringUtils.startsWithIgnoreCase(getGeocode(), "GK"); } public String getTrackingcode() { diff --git a/main/src/cgeo/geocaching/cgWaypoint.java b/main/src/cgeo/geocaching/cgWaypoint.java index 0e21c08..32cc526 100644 --- a/main/src/cgeo/geocaching/cgWaypoint.java +++ b/main/src/cgeo/geocaching/cgWaypoint.java @@ -156,7 +156,7 @@ public class cgWaypoint implements IWaypoint, Comparable<cgWaypoint> { } public String getUrl() { - return "http://www.geocaching.com//seek/cache_details.aspx?wp=" + geocode.toUpperCase(); + return "http://www.geocaching.com//seek/cache_details.aspx?wp=" + geocode; } @Override @@ -174,7 +174,7 @@ public class cgWaypoint implements IWaypoint, Comparable<cgWaypoint> { } public void setGeocode(String geocode) { - this.geocode = geocode; + this.geocode = StringUtils.upperCase(geocode); } @Override diff --git a/main/src/cgeo/geocaching/cgeo.java b/main/src/cgeo/geocaching/cgeo.java index c80ec6f..c1e4269 100644 --- a/main/src/cgeo/geocaching/cgeo.java +++ b/main/src/cgeo/geocaching/cgeo.java @@ -772,7 +772,7 @@ public class cgeo extends AbstractActivity { } } - countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL); + countBubbleCnt = cgeoapplication.getAllCachesCount(); countBubbleHandler.sendEmptyMessage(0); } diff --git a/main/src/cgeo/geocaching/cgeoapplication.java b/main/src/cgeo/geocaching/cgeoapplication.java index 9e221cd..c866739 100644 --- a/main/src/cgeo/geocaching/cgeoapplication.java +++ b/main/src/cgeo/geocaching/cgeoapplication.java @@ -275,10 +275,10 @@ public class cgeoapplication extends Application { return storage.getBounds(geocodes); } - /** {@link cgData#loadBatchOfStoredGeocodes(boolean, Geopoint, CacheType, int)} */ - public SearchResult getBatchOfStoredCaches(final boolean detailedOnly, final Geopoint coords, final CacheType cacheType, final int listId) { - final Set<String> geocodes = storage.loadBatchOfStoredGeocodes(detailedOnly, coords, cacheType, listId); - return new SearchResult(geocodes, getAllStoredCachesCount(true, cacheType, listId)); + /** {@link cgData#loadBatchOfStoredGeocodes(Geopoint, CacheType, int)} */ + public SearchResult getBatchOfStoredCaches(final Geopoint coords, final CacheType cacheType, final int listId) { + final Set<String> geocodes = storage.loadBatchOfStoredGeocodes(coords, cacheType, listId); + return new SearchResult(geocodes, getAllStoredCachesCount(cacheType, listId)); } /** {@link cgData#loadHistoryOfSearchedLocations()} */ @@ -303,19 +303,14 @@ public class cgeoapplication extends Application { return new SearchResult(geocodes); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ - public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType) { - return storage.getAllStoredCachesCount(detailedOnly, cacheType, 0); + /** {@link cgData#getAllStoredCachesCount(CacheType, int)} */ + public int getAllStoredCachesCount(final CacheType cacheType, final Integer list) { + return storage.getAllStoredCachesCount(cacheType, list); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ - public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final Integer list) { - return storage.getAllStoredCachesCount(detailedOnly, cacheType, list); - } - - /** {@link cgData#getAllHistoricCachesCount()} */ + /** {@link cgData#getAllHistoryCachesCount()} */ public int getAllHistoricCachesCount() { - return storage.getAllHistoricCachesCount(); + return storage.getAllHistoryCachesCount(); } /** {@link cgData#moveToList(List, int)} */ @@ -501,4 +496,8 @@ public class cgeoapplication extends Application { return storage.loadWaypoints(geocode); } + public static int getAllCachesCount() { + return cgData.getAllCachesCount(); + } + } diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java index 57fdb9c..da3059b 100644 --- a/main/src/cgeo/geocaching/cgeocaches.java +++ b/main/src/cgeo/geocaching/cgeocaches.java @@ -642,7 +642,7 @@ public class cgeocaches extends AbstractListActivity { // refresh standard list if it has changed (new caches downloaded) if (type == CacheListType.OFFLINE && listId >= StoredList.STANDARD_LIST_ID && search != null) { - SearchResult newSearch = cgeoapplication.getInstance().getBatchOfStoredCaches(true, coords, Settings.getCacheType(), listId); + SearchResult newSearch = cgeoapplication.getInstance().getBatchOfStoredCaches(coords, Settings.getCacheType(), listId); if (newSearch != null && newSearch.getTotal() != search.getTotal()) { refreshCurrentList(); } @@ -1003,7 +1003,7 @@ public class cgeocaches extends AbstractListActivity { break; case MENU_CACHE_DETAILS: final Intent cachesIntent = new Intent(this, CacheDetailActivity.class); - cachesIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); + cachesIntent.putExtra("geocode", cache.getGeocode()); cachesIntent.putExtra("name", cache.getName()); startActivity(cachesIntent); break; @@ -1283,7 +1283,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - search = cgeoapplication.getInstance().getBatchOfStoredCaches(true, coords, Settings.getCacheType(), listId); + search = cgeoapplication.getInstance().getBatchOfStoredCaches(coords, Settings.getCacheType(), listId); replaceCacheListFromSearch(); loadCachesHandler.sendMessage(Message.obtain()); } diff --git a/main/src/cgeo/geocaching/cgeonavigate.java b/main/src/cgeo/geocaching/cgeonavigate.java index 64b7cd8..61870a5 100644 --- a/main/src/cgeo/geocaching/cgeonavigate.java +++ b/main/src/cgeo/geocaching/cgeonavigate.java @@ -293,7 +293,7 @@ public class cgeonavigate extends AbstractActivity { final Intent navigateIntent = new Intent(context, cgeonavigate.class); navigateIntent.putExtra(EXTRAS_COORDS, coords); - navigateIntent.putExtra(EXTRAS_GEOCODE, geocode.toUpperCase()); + navigateIntent.putExtra(EXTRAS_GEOCODE, geocode); if (null != displayedName) { navigateIntent.putExtra(EXTRAS_NAME, displayedName); } diff --git a/main/src/cgeo/geocaching/cgeotrackable.java b/main/src/cgeo/geocaching/cgeotrackable.java index 93b410a..e436249 100644 --- a/main/src/cgeo/geocaching/cgeotrackable.java +++ b/main/src/cgeo/geocaching/cgeotrackable.java @@ -5,6 +5,7 @@ import cgeo.geocaching.connector.gc.GCParser; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Units; import cgeo.geocaching.network.HtmlImage; +import cgeo.geocaching.network.Network; import cgeo.geocaching.ui.CacheDetailsCreator; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.utils.BaseUtils; @@ -32,9 +33,9 @@ import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; -import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; +import java.util.Locale; public class cgeotrackable extends AbstractActivity { private static final int MENU_LOG_TOUCH = 1; @@ -68,12 +69,12 @@ public class cgeotrackable extends AbstractActivity { try { inflater = getLayoutInflater(); - geocode = trackable.getGeocode().toUpperCase(); + geocode = trackable.getGeocode(); if (StringUtils.isNotBlank(trackable.getName())) { setTitle(Html.fromHtml(trackable.getName()).toString()); } else { - setTitle(trackable.getName().toUpperCase()); + setTitle(trackable.getName()); } findViewById(R.id.details_list_box).setVisibility(View.VISIBLE); @@ -99,7 +100,7 @@ public class cgeotrackable extends AbstractActivity { details.add(R.string.trackable_type, tbType); // trackable geocode - details.add(R.string.trackable_code, trackable.getGeocode().toUpperCase()); + details.add(R.string.trackable_code, trackable.getGeocode()); // trackable owner TextView owner = details.add(R.string.trackable_owner, res.getString(R.string.trackable_unknown)); @@ -274,33 +275,33 @@ public class cgeotrackable extends AbstractActivity { // try to get data from URI if (geocode == null && guid == null && id == null && uri != null) { - String uriHost = uri.getHost().toLowerCase(); + String uriHost = uri.getHost().toLowerCase(Locale.US); if (uriHost.contains("geocaching.com")) { geocode = uri.getQueryParameter("tracker"); guid = uri.getQueryParameter("guid"); id = uri.getQueryParameter("id"); if (StringUtils.isNotBlank(geocode)) { - geocode = geocode.toUpperCase(); + geocode = geocode.toUpperCase(Locale.US); guid = null; id = null; } else if (StringUtils.isNotBlank(guid)) { geocode = null; - guid = guid.toLowerCase(); + guid = guid.toLowerCase(Locale.US); id = null; } else if (StringUtils.isNotBlank(id)) { geocode = null; guid = null; - id = id.toLowerCase(); + id = id.toLowerCase(Locale.US); } else { showToast(res.getString(R.string.err_tb_details_open)); finish(); return; } } else if (uriHost.contains("coord.info")) { - String uriPath = uri.getPath().toLowerCase(); + String uriPath = uri.getPath().toLowerCase(Locale.US); if (uriPath != null && uriPath.startsWith("/tb")) { - geocode = uriPath.substring(1).toUpperCase(); + geocode = uriPath.substring(1).toUpperCase(Locale.US); guid = null; id = null; } else { @@ -322,7 +323,7 @@ public class cgeotrackable extends AbstractActivity { if (StringUtils.isNotBlank(name)) { message = Html.fromHtml(name).toString(); } else if (StringUtils.isNotBlank(geocode)) { - message = geocode.toUpperCase(); + message = geocode; } else { message = res.getString(R.string.trackable); } @@ -367,7 +368,7 @@ public class cgeotrackable extends AbstractActivity { cgeocaches.startActivityUserName(this, contextMenuUser); return true; case 3: - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(contextMenuUser)))); + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + Network.encode(contextMenuUser)))); return true; default: return false; diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel11Dummy.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel11Emulation.java index 9c2bb8c..6a23ed5 100644 --- a/main/src/cgeo/geocaching/compatibility/AndroidLevel11Dummy.java +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel11Emulation.java @@ -3,9 +3,9 @@ package cgeo.geocaching.compatibility; import android.app.Activity; /** - * dummy class which has no functionality in the level 11 API + * implement level 11 API using older methods */ -public class AndroidLevel11Dummy implements AndroidLevel11Interface { +public class AndroidLevel11Emulation implements AndroidLevel11Interface { @Override public void invalidateOptionsMenu(final Activity activity) { diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel13.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel13.java new file mode 100644 index 0000000..4eac205 --- /dev/null +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel13.java @@ -0,0 +1,31 @@ +package cgeo.geocaching.compatibility; + +import cgeo.geocaching.cgeoapplication; + +import android.annotation.TargetApi; +import android.content.Context; +import android.graphics.Point; +import android.view.WindowManager; + +@TargetApi(value = 13) +public class AndroidLevel13 implements AndroidLevel13Interface { + + @Override + public int getDisplayWidth() { + return getDisplaySize().x; + } + + @Override + public Point getDisplaySize() { + Point dimensions = new Point(); + ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay().getSize(dimensions); + return dimensions; + } + + @Override + public int getDisplayHeight() { + return getDisplaySize().y; + } + +} diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel13Emulation.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel13Emulation.java new file mode 100644 index 0000000..2257d83 --- /dev/null +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel13Emulation.java @@ -0,0 +1,33 @@ +package cgeo.geocaching.compatibility; + +import cgeo.geocaching.cgeoapplication; + +import android.content.Context; +import android.graphics.Point; +import android.view.Display; +import android.view.WindowManager; + +@SuppressWarnings("deprecation") +public class AndroidLevel13Emulation implements AndroidLevel13Interface { + + @Override + public int getDisplayWidth() { + return getDisplay().getWidth(); + } + + @Override + public int getDisplayHeight() { + return getDisplay().getHeight(); + } + + @Override + public Point getDisplaySize() { + final Display display = getDisplay(); + return new Point(display.getWidth(), display.getHeight()); + } + + private static Display getDisplay() { + return ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)) + .getDefaultDisplay(); + } +} diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel13Interface.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel13Interface.java new file mode 100644 index 0000000..f4e1975 --- /dev/null +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel13Interface.java @@ -0,0 +1,11 @@ +package cgeo.geocaching.compatibility; + +import android.graphics.Point; + +public interface AndroidLevel13Interface { + int getDisplayWidth(); + + int getDisplayHeight(); + + Point getDisplaySize(); +} diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel8.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel8.java index ea5a795..a388adb 100644 --- a/main/src/cgeo/geocaching/compatibility/AndroidLevel8.java +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel8.java @@ -6,6 +6,7 @@ import android.annotation.TargetApi; import android.app.Activity; import android.app.backup.BackupManager; import android.view.Display; +import android.view.Surface; @TargetApi(8) public class AndroidLevel8 implements AndroidLevel8Interface { @@ -21,4 +22,23 @@ public class AndroidLevel8 implements AndroidLevel8Interface { Log.i("Requesting settings backup with settings manager"); BackupManager.dataChanged(name); } + + @Override + public int getRotationOffset(final Activity activity) { + try { + final int rotation = getRotation(activity); + if (rotation == Surface.ROTATION_90) { + return 90; + } else if (rotation == Surface.ROTATION_180) { + return 180; + } else if (rotation == Surface.ROTATION_270) { + return 270; + } + } catch (final Exception e) { + // This should never happen: IllegalArgumentException, IllegalAccessException or InvocationTargetException + Log.e("Cannot call getRotation()", e); + } + + return 0; + } } diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel8Dummy.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel8Dummy.java deleted file mode 100644 index d0ab911..0000000 --- a/main/src/cgeo/geocaching/compatibility/AndroidLevel8Dummy.java +++ /dev/null @@ -1,16 +0,0 @@ -package cgeo.geocaching.compatibility; - -import android.app.Activity; - -public class AndroidLevel8Dummy implements AndroidLevel8Interface { - - @Override - public int getRotation(final Activity activity) { - return 0; - } - - @Override - public void dataChanged(final String name) { - // do nothing - } -} diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel8Emulation.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel8Emulation.java new file mode 100644 index 0000000..197993d --- /dev/null +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel8Emulation.java @@ -0,0 +1,30 @@ +package cgeo.geocaching.compatibility; + +import android.annotation.TargetApi; +import android.app.Activity; +import android.content.res.Configuration; +import android.view.Display; + +@TargetApi(value = 7) +public class AndroidLevel8Emulation implements AndroidLevel8Interface { + + @Override + public int getRotation(final Activity activity) { + return 0; + } + + @Override + public void dataChanged(final String name) { + // do nothing + } + + @Override + public int getRotationOffset(Activity activity) { + final Display display = activity.getWindowManager().getDefaultDisplay(); + final int rotation = display.getOrientation(); + if (rotation == Configuration.ORIENTATION_LANDSCAPE) { + return 90; + } + return 0; + } +} diff --git a/main/src/cgeo/geocaching/compatibility/AndroidLevel8Interface.java b/main/src/cgeo/geocaching/compatibility/AndroidLevel8Interface.java index b1c4f81..761c23a 100644 --- a/main/src/cgeo/geocaching/compatibility/AndroidLevel8Interface.java +++ b/main/src/cgeo/geocaching/compatibility/AndroidLevel8Interface.java @@ -6,4 +6,5 @@ public interface AndroidLevel8Interface { public int getRotation(final Activity activity); public void dataChanged(final String name); + public int getRotationOffset(final Activity activity); }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/compatibility/Compatibility.java b/main/src/cgeo/geocaching/compatibility/Compatibility.java index 0821655..05a3331 100644 --- a/main/src/cgeo/geocaching/compatibility/Compatibility.java +++ b/main/src/cgeo/geocaching/compatibility/Compatibility.java @@ -8,11 +8,9 @@ import org.apache.commons.lang3.reflect.MethodUtils; import android.app.Activity; import android.content.Intent; -import android.content.res.Configuration; +import android.graphics.Point; import android.os.Build; import android.text.InputType; -import android.view.Display; -import android.view.Surface; import android.widget.EditText; public final class Compatibility { @@ -23,19 +21,26 @@ public final class Compatibility { private final static AndroidLevel8Interface level8; private final static AndroidLevel11Interface level11; + private final static AndroidLevel13Interface level13; static { if (isLevel8) { level8 = new AndroidLevel8(); } else { - level8 = new AndroidLevel8Dummy(); + level8 = new AndroidLevel8Emulation(); } if (sdkVersion >= 11) { level11 = new AndroidLevel11(); } else { - level11 = new AndroidLevel11Dummy(); + level11 = new AndroidLevel11Emulation(); + } + if (sdkVersion >= 13) { + level13 = new AndroidLevel13(); + } + else { + level13 = new AndroidLevel13Emulation(); } } @@ -47,29 +52,7 @@ public final class Compatibility { * @return the adjusted direction, in the [0, 360[ range */ public static float getDirectionNow(final float directionNowPre, final Activity activity) { - float offset = 0; - if (isLevel8) { - try { - final int rotation = level8.getRotation(activity); - if (rotation == Surface.ROTATION_90) { - offset = 90; - } else if (rotation == Surface.ROTATION_180) { - offset = 180; - } else if (rotation == Surface.ROTATION_270) { - offset = 270; - } - } catch (final Exception e) { - // This should never happen: IllegalArgumentException, IllegalAccessException or InvocationTargetException - Log.e("Cannot call getRotation()", e); - } - } else { - final Display display = activity.getWindowManager().getDefaultDisplay(); - final int rotation = display.getOrientation(); - if (rotation == Configuration.ORIENTATION_LANDSCAPE) { - offset = 90; - } - } - return AngleUtils.normalize(directionNowPre + offset); + return AngleUtils.normalize(directionNowPre + level8.getRotationOffset(activity)); } public static void dataChanged(final String name) { @@ -113,4 +96,16 @@ public final class Compatibility { level11.invalidateOptionsMenu(activity); } + public static int getDisplayWidth() { + return level13.getDisplayWidth(); + } + + public static int getDisplayHeight() { + return level13.getDisplayHeight(); + } + + public static Point getDisplaySize() { + return level13.getDisplaySize(); + } + } diff --git a/main/src/cgeo/geocaching/connector/gc/GCConstants.java b/main/src/cgeo/geocaching/connector/gc/GCConstants.java index 69c2d5b..69f9878 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCConstants.java +++ b/main/src/cgeo/geocaching/connector/gc/GCConstants.java @@ -1,5 +1,6 @@ package cgeo.geocaching.connector.gc; +import java.util.Locale; import java.util.regex.Pattern; /** @@ -187,7 +188,7 @@ public final class GCConstants { public static long gccodeToGCId(final String gccode) { long gcid = 0; long base = GC_BASE31; - String geocodeWO = gccode.substring(2).toUpperCase(); + String geocodeWO = gccode.substring(2).toUpperCase(Locale.US); if ((geocodeWO.length() < 4) || (geocodeWO.length() == 4 && SEQUENCE_GCID.indexOf(geocodeWO.charAt(0)) < 16)) { base = GC_BASE16; diff --git a/main/src/cgeo/geocaching/connector/gc/GCParser.java b/main/src/cgeo/geocaching/connector/gc/GCParser.java index 3b8f893..10f9d00 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCParser.java +++ b/main/src/cgeo/geocaching/connector/gc/GCParser.java @@ -48,7 +48,6 @@ import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.StrikethroughSpan; -import java.net.URLDecoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; @@ -165,14 +164,14 @@ public abstract class GCParser { String inventoryPre = null; - cache.setGeocode(BaseUtils.getMatch(row, GCConstants.PATTERN_SEARCH_GEOCODE, true, 1, cache.getGeocode(), true).toUpperCase()); + cache.setGeocode(BaseUtils.getMatch(row, GCConstants.PATTERN_SEARCH_GEOCODE, true, 1, cache.getGeocode(), true)); // cache type cache.setType(CacheType.getByPattern(BaseUtils.getMatch(row, GCConstants.PATTERN_SEARCH_TYPE, true, 1, null, true))); // cache direction - image if (Settings.getLoadDirImg()) { - cache.setDirectionImg(URLDecoder.decode(BaseUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION, true, 1, cache.getDirectionImg(), true))); + cache.setDirectionImg(Network.decode(BaseUtils.getMatch(row, GCConstants.PATTERN_SEARCH_DIRECTION, true, 1, cache.getDirectionImg(), true))); } // cache inventory @@ -383,7 +382,7 @@ public abstract class GCParser { cache.setName(cacheName); // owner real name - cache.setOwnerUserId(URLDecoder.decode(BaseUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); + cache.setOwnerUserId(Network.decode(BaseUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); cache.setOwn(StringUtils.equalsIgnoreCase(cache.getOwnerUserId(), Settings.getUsername())); @@ -435,7 +434,7 @@ public abstract class GCParser { cache.setFavoritePoints(Integer.parseInt(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); // cache size - cache.setSize(CacheSize.getById(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id).toLowerCase())); + cache.setSize(CacheSize.getById(BaseUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id))); } // cache found @@ -503,7 +502,7 @@ public abstract class GCParser { while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { // by default, use the tooltip of the attribute - String attribute = matcherAttributesInside.group(2).toLowerCase(); + String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US); // if the image name can be recognized, use the image name as attribute String imageName = matcherAttributesInside.group(1).trim(); @@ -511,7 +510,7 @@ public abstract class GCParser { int start = imageName.lastIndexOf('/'); int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { - attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(); + attribute = imageName.substring(start + 1, end).replace('-', '_').toLowerCase(Locale.US); } } attributes.add(attribute); @@ -1267,7 +1266,7 @@ public abstract class GCParser { final cgTrackable trackable = new cgTrackable(); // trackable geocode - trackable.setGeocode(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GEOCODE, true, trackable.getGeocode()).toUpperCase()); + trackable.setGeocode(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GEOCODE, true, trackable.getGeocode())); // trackable id trackable.setGuid(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_GUID, true, trackable.getGuid())); diff --git a/main/src/cgeo/geocaching/connector/gc/Tile.java b/main/src/cgeo/geocaching/connector/gc/Tile.java index 5404446..73ded4d 100644 --- a/main/src/cgeo/geocaching/connector/gc/Tile.java +++ b/main/src/cgeo/geocaching/connector/gc/Tile.java @@ -17,6 +17,7 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; +import java.util.Locale; import java.util.Set; /** @@ -99,7 +100,7 @@ public class Tile { /** * Calculate latitude/longitude for a given x/y position in this tile. - * + * * @see <a * href="http://developers.cloudmade.com/projects/tiles/examples/convert-coordinates-to-tile-numbers">Cloudmade</a> */ @@ -115,7 +116,7 @@ public class Tile { @Override public String toString() { - return String.format("(%d/%d), zoom=%d", tileX, tileY, zoomlevel); + return String.format(Locale.US, "(%d/%d), zoom=%d", tileX, tileY, zoomlevel); } /** diff --git a/main/src/cgeo/geocaching/enumerations/CacheSize.java b/main/src/cgeo/geocaching/enumerations/CacheSize.java index 155c9a5..a686dd6 100644 --- a/main/src/cgeo/geocaching/enumerations/CacheSize.java +++ b/main/src/cgeo/geocaching/enumerations/CacheSize.java @@ -5,6 +5,7 @@ import cgeo.geocaching.cgeoapplication; import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; /** @@ -34,7 +35,7 @@ public enum CacheSize { static { final HashMap<String, CacheSize> mapping = new HashMap<String, CacheSize>(); for (CacheSize cs : values()) { - mapping.put(cs.id.toLowerCase(), cs); + mapping.put(cs.id.toLowerCase(Locale.US), cs); } // add medium as additional string for Regular mapping.put("medium", CacheSize.REGULAR); @@ -51,7 +52,7 @@ public enum CacheSize { return result; } // only if String was not found, normalize it - final CacheSize resultNormalized = CacheSize.FIND_BY_ID.get(id.toLowerCase().trim()); + final CacheSize resultNormalized = CacheSize.FIND_BY_ID.get(id.toLowerCase(Locale.US).trim()); if (resultNormalized != null) { return resultNormalized; } diff --git a/main/src/cgeo/geocaching/enumerations/CacheType.java b/main/src/cgeo/geocaching/enumerations/CacheType.java index 730c989..251790f 100644 --- a/main/src/cgeo/geocaching/enumerations/CacheType.java +++ b/main/src/cgeo/geocaching/enumerations/CacheType.java @@ -5,6 +5,7 @@ import cgeo.geocaching.cgeoapplication; import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; /** @@ -59,14 +60,14 @@ public enum CacheType { final HashMap<String, CacheType> mappingPattern = new HashMap<String, CacheType>(); for (CacheType ct : values()) { mappingId.put(ct.id, ct); - mappingPattern.put(ct.pattern.toLowerCase(), ct); + mappingPattern.put(ct.pattern.toLowerCase(Locale.US), ct); } FIND_BY_ID = Collections.unmodifiableMap(mappingId); FIND_BY_PATTERN = Collections.unmodifiableMap(mappingPattern); } public static CacheType getById(final String id) { - final CacheType result = (id != null) ? CacheType.FIND_BY_ID.get(id.toLowerCase().trim()) : null; + final CacheType result = (id != null) ? CacheType.FIND_BY_ID.get(id.toLowerCase(Locale.US).trim()) : null; if (result == null) { return UNKNOWN; } @@ -74,7 +75,7 @@ public enum CacheType { } public static CacheType getByPattern(final String pattern) { - final CacheType result = (pattern != null) ? CacheType.FIND_BY_PATTERN.get(pattern.toLowerCase().trim()) : null; + final CacheType result = (pattern != null) ? CacheType.FIND_BY_PATTERN.get(pattern.toLowerCase(Locale.US).trim()) : null; if (result == null) { return UNKNOWN; } diff --git a/main/src/cgeo/geocaching/enumerations/LogType.java b/main/src/cgeo/geocaching/enumerations/LogType.java index ac64ed1..82efd7e 100644 --- a/main/src/cgeo/geocaching/enumerations/LogType.java +++ b/main/src/cgeo/geocaching/enumerations/LogType.java @@ -5,6 +5,7 @@ import cgeo.geocaching.cgeoapplication; import java.util.Collections; import java.util.HashMap; +import java.util.Locale; import java.util.Map; @@ -74,7 +75,7 @@ public enum LogType { } public static LogType getByIconName(final String imageType) { - final LogType result = imageType != null ? LogType.FIND_BY_ICONNAME.get(imageType.toLowerCase().trim()) : null; + final LogType result = imageType != null ? LogType.FIND_BY_ICONNAME.get(imageType.toLowerCase(Locale.US).trim()) : null; if (result == null) { return UNKNOWN; } @@ -82,7 +83,7 @@ public enum LogType { } public static LogType getByType(final String type) { - final LogType result = type != null ? LogType.FIND_BY_TYPE.get(type.toLowerCase().trim()) : null; + final LogType result = type != null ? LogType.FIND_BY_TYPE.get(type.toLowerCase(Locale.US).trim()) : null; if (result == null) { return UNKNOWN; } diff --git a/main/src/cgeo/geocaching/export/FieldnoteExport.java b/main/src/cgeo/geocaching/export/FieldnoteExport.java index 11214db..028ad54 100644 --- a/main/src/cgeo/geocaching/export/FieldnoteExport.java +++ b/main/src/cgeo/geocaching/export/FieldnoteExport.java @@ -31,6 +31,7 @@ import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Locale; +import java.util.TimeZone; /** * Exports offline-logs in the Groundspeak Field Note format.<br> @@ -42,6 +43,9 @@ import java.util.Locale; class FieldnoteExport extends AbstractExport { private static final File exportLocation = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/field-notes"); private static final SimpleDateFormat fieldNoteDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); + static { + fieldNoteDateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + } protected FieldnoteExport() { super(getString(R.string.export_fieldnotes)); diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java index b9d3f53..c451ad5 100644 --- a/main/src/cgeo/geocaching/files/GPXParser.java +++ b/main/src/cgeo/geocaching/files/GPXParser.java @@ -287,7 +287,7 @@ public abstract class GPXParser extends FileParser { // take the name as code, if nothing else is available if (StringUtils.isBlank(cache.getGeocode())) { if (StringUtils.isNotBlank(name)) { - cache.setGeocode(name.trim().toUpperCase()); + cache.setGeocode(name.trim()); } } @@ -326,7 +326,7 @@ public abstract class GPXParser extends FileParser { fixCache(cache); if (cache.getName().length() > 2) { - final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase(); + final String cacheGeocodeForWaypoint = "GC" + cache.getName().substring(2).toUpperCase(Locale.US); // lookup cache for waypoint in already parsed caches final cgCache cacheForWaypoint = cgeoapplication.getInstance().loadCache(cacheGeocodeForWaypoint, LoadFlags.LOAD_CACHE_OR_DB); @@ -410,7 +410,7 @@ public abstract class GPXParser extends FileParser { public void end(String body) { final String[] content = body.split("\\|"); if (content.length > 0) { - type = content[0].toLowerCase().trim(); + type = content[0].toLowerCase(Locale.US).trim(); } } }); @@ -420,7 +420,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(final String body) { - sym = body.toLowerCase(); + sym = body.toLowerCase(Locale.US); if (sym.contains("geocache") && sym.contains("found")) { cache.setFound(true); } @@ -526,7 +526,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String body) { - cache.setType(CacheType.getByPattern(validate(body.toLowerCase()))); + cache.setType(CacheType.getByPattern(validate(body))); } }); @@ -535,7 +535,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String body) { - cache.setSize(CacheSize.getById(validate(body.toLowerCase()))); + cache.setSize(CacheSize.getById(validate(body))); } }); @@ -665,7 +665,7 @@ public abstract class GPXParser extends FileParser { try { if (attrs.getIndex("ref") > -1) { - trackable.setGeocode(attrs.getValue("ref").toUpperCase()); + trackable.setGeocode(attrs.getValue("ref")); } } catch (Exception e) { // nothing @@ -745,7 +745,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String body) { - final String logType = validate(body).toLowerCase(); + final String logType = validate(body); log.type = LogType.getByType(logType); } }); diff --git a/main/src/cgeo/geocaching/files/LocParser.java b/main/src/cgeo/geocaching/files/LocParser.java index b17b203..45bcca9 100644 --- a/main/src/cgeo/geocaching/files/LocParser.java +++ b/main/src/cgeo/geocaching/files/LocParser.java @@ -77,7 +77,7 @@ public final class LocParser extends FileParser { cache.setDifficulty(coord.getDifficulty()); cache.setTerrain(coord.getTerrain()); cache.setSize(coord.getSize()); - cache.setGeocode(coord.getGeocode().toUpperCase()); + cache.setGeocode(coord.getGeocode()); cache.setReliableLatLon(true); if (StringUtils.isBlank(cache.getName())) { cache.setName(coord.getName()); @@ -149,8 +149,7 @@ public final class LocParser extends FileParser { final cgCache cache = new cgCache(); final Matcher matcherGeocode = patternGeocode.matcher(pointString); if (matcherGeocode.find()) { - final String geocode = matcherGeocode.group(1).trim().toUpperCase(); - cache.setGeocode(geocode.toUpperCase()); + cache.setGeocode(matcherGeocode.group(1).trim()); } final Matcher matcherName = patternName.matcher(pointString); diff --git a/main/src/cgeo/geocaching/geopoint/DistanceParser.java b/main/src/cgeo/geocaching/geopoint/DistanceParser.java index 5f02895..61d1ecd 100644 --- a/main/src/cgeo/geocaching/geopoint/DistanceParser.java +++ b/main/src/cgeo/geocaching/geopoint/DistanceParser.java @@ -1,5 +1,6 @@ package cgeo.geocaching.geopoint; +import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -26,7 +27,7 @@ public final class DistanceParser { } final float value = Float.parseFloat(matcher.group(1).replace(',', '.')); - final String unit = matcher.group(2).toLowerCase(); + final String unit = matcher.group(2).toLowerCase(Locale.US); if (unit.equals("m") || (unit.length() == 0 && metricUnit)) { return value / 1000; diff --git a/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java b/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java index c706e77..892335c 100644 --- a/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java +++ b/main/src/cgeo/geocaching/geopoint/GeopointFormatter.java @@ -61,13 +61,13 @@ public class GeopointFormatter switch (format) { case LAT_LON_DECDEGREE: - return String.format("%.6f %.6f", latSigned, lonSigned); + return String.format(Locale.getDefault(), "%.6f %.6f", latSigned, lonSigned); case LAT_LON_DECDEGREE_COMMA: return String.format((Locale) null, "%.6f,%.6f", latSigned, lonSigned); case LAT_LON_DECMINUTE: - return String.format("%c %02d° %06.3f · %c %03d° %06.3f", + return String.format(Locale.getDefault(), "%c %02d° %06.3f · %c %03d° %06.3f", gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw(), gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); case LAT_LON_DECMINUTE_RAW: @@ -75,7 +75,7 @@ public class GeopointFormatter gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw(), gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); case LAT_LON_DECSECOND: - return String.format("%c %02d° %02d' %06.3f\" · %c %03d° %02d' %06.3f\"", + return String.format(Locale.getDefault(), "%c %02d° %02d' %06.3f\" · %c %03d° %02d' %06.3f\"", gp.getLatDir(), gp.getLatDeg(), gp.getLatMin(), gp.getLatSecRaw(), gp.getLonDir(), gp.getLonDeg(), gp.getLonMin(), gp.getLonSecRaw()); @@ -83,19 +83,19 @@ public class GeopointFormatter return String.format((Locale) null, "%.6f", latSigned); case LAT_DECMINUTE: - return String.format("%c %02d° %06.3f", gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw()); + return String.format(Locale.getDefault(), "%c %02d° %06.3f", gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw()); case LAT_DECMINUTE_RAW: - return String.format("%c %02d %06.3f", gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw()); + return String.format(Locale.getDefault(), "%c %02d %06.3f", gp.getLatDir(), gp.getLatDeg(), gp.getLatMinRaw()); case LON_DECDEGREE_RAW: return String.format((Locale) null, "%.6f", lonSigned); case LON_DECMINUTE: - return String.format("%c %03d° %06.3f", gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); + return String.format(Locale.getDefault(), "%c %03d° %06.3f", gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); case LON_DECMINUTE_RAW: - return String.format("%c %03d %06.3f", gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); + return String.format(Locale.getDefault(), "%c %03d %06.3f", gp.getLonDir(), gp.getLonDeg(), gp.getLonMinRaw()); } // Keep the compiler happy even though it cannot happen diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index 3e136b7..0ffe689 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -368,7 +368,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto activity = this.getActivity(); app = (cgeoapplication) activity.getApplication(); - int countBubbleCnt = app.getAllStoredCachesCount(true, CacheType.ALL); + int countBubbleCnt = cgeoapplication.getAllCachesCount(); caches = new LeastRecentlyUsedSet<cgCache>(MAX_CACHES + countBubbleCnt); final MapProvider mapProvider = Settings.getMapProvider(); diff --git a/main/src/cgeo/geocaching/maps/MapProviderFactory.java b/main/src/cgeo/geocaching/maps/MapProviderFactory.java index cb1f87f..483189f 100644 --- a/main/src/cgeo/geocaching/maps/MapProviderFactory.java +++ b/main/src/cgeo/geocaching/maps/MapProviderFactory.java @@ -23,7 +23,7 @@ public class MapProviderFactory { MapsforgeMapProvider.getInstance(); } - private static boolean isGoogleMapsInstalled() { + public static boolean isGoogleMapsInstalled() { boolean googleMaps = true; try { Class.forName("com.google.android.maps.MapActivity"); diff --git a/main/src/cgeo/geocaching/network/HtmlImage.java b/main/src/cgeo/geocaching/network/HtmlImage.java index d47afb9..e25eec5 100644 --- a/main/src/cgeo/geocaching/network/HtmlImage.java +++ b/main/src/cgeo/geocaching/network/HtmlImage.java @@ -3,6 +3,7 @@ package cgeo.geocaching.network; import cgeo.geocaching.R; import cgeo.geocaching.StoredList; import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.compatibility.Compatibility; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.files.LocalStorage; import cgeo.geocaching.utils.ImageHelper; @@ -12,15 +13,13 @@ import ch.boye.httpclientandroidlib.HttpResponse; import org.apache.commons.lang3.StringUtils; -import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; +import android.graphics.Point; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.Html; -import android.view.Display; -import android.view.WindowManager; import java.io.File; import java.io.FileInputStream; @@ -66,9 +65,9 @@ public class HtmlImage implements Html.ImageGetter { bfOptions = new BitmapFactory.Options(); bfOptions.inTempStorage = new byte[16 * 1024]; - final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - this.maxWidth = display.getWidth() - 25; - this.maxHeight = display.getHeight() - 25; + Point displaySize = Compatibility.getDisplaySize(); + this.maxWidth = displaySize.x - 25; + this.maxHeight = displaySize.y - 25; this.resources = cgeoapplication.getInstance().getResources(); } diff --git a/main/src/cgeo/geocaching/network/Network.java b/main/src/cgeo/geocaching/network/Network.java index 72b325e..ed921b2 100644 --- a/main/src/cgeo/geocaching/network/Network.java +++ b/main/src/cgeo/geocaching/network/Network.java @@ -34,6 +34,7 @@ import ch.boye.httpclientandroidlib.params.HttpParams; import ch.boye.httpclientandroidlib.protocol.HttpContext; import ch.boye.httpclientandroidlib.util.EntityUtils; +import org.apache.commons.lang3.CharEncoding; import org.apache.commons.lang3.StringUtils; import org.json.JSONException; import org.json.JSONObject; @@ -43,11 +44,13 @@ import android.net.Uri; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; import java.net.URLEncoder; public abstract class Network { private static final int NB_DOWNLOAD_RETRIES = 4; + /** User agent id */ private final static String PC_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1"; /** Native user agent, taken from a Android 2.2 Nexus **/ @@ -397,7 +400,27 @@ public abstract class Network { } public static String rfc3986URLEncode(String text) { - return StringUtils.replace(URLEncoder.encode(text).replace("+", "%20"), "%7E", "~"); + return StringUtils.replace(Network.encode(text).replace("+", "%20"), "%7E", "~"); + } + + public static String decode(final String text) { + try { + return URLDecoder.decode(text, CharEncoding.UTF_8); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; + } + + public static String encode(final String text) { + try { + return URLEncoder.encode(text, CharEncoding.UTF_8); + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + return null; } } diff --git a/main/src/cgeo/geocaching/ui/EditorDialog.java b/main/src/cgeo/geocaching/ui/EditorDialog.java index 50b3e27..6dcf546 100644 --- a/main/src/cgeo/geocaching/ui/EditorDialog.java +++ b/main/src/cgeo/geocaching/ui/EditorDialog.java @@ -53,7 +53,7 @@ public class EditorDialog extends Dialog { @Override public void show() { super.show(); - getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT); + getWindow().setLayout(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); } } diff --git a/main/src/cgeo/geocaching/utils/AngleUtils.java b/main/src/cgeo/geocaching/utils/AngleUtils.java index e2b4a66..6e59a91 100644 --- a/main/src/cgeo/geocaching/utils/AngleUtils.java +++ b/main/src/cgeo/geocaching/utils/AngleUtils.java @@ -8,9 +8,11 @@ public class AngleUtils { /** * Return the angle to turn of to go from an angle to the other - * - * @param from the origin angle in degrees - * @param to the target angle in degreees + * + * @param from + * the origin angle in degrees + * @param to + * the target angle in degrees * @return a value in degrees, in the [-180, 180[ range */ public static float difference(final float from, final float to) { diff --git a/main/src/cgeo/geocaching/utils/ImageHelper.java b/main/src/cgeo/geocaching/utils/ImageHelper.java index 4c18b06..98cad64 100644 --- a/main/src/cgeo/geocaching/utils/ImageHelper.java +++ b/main/src/cgeo/geocaching/utils/ImageHelper.java @@ -1,13 +1,12 @@ package cgeo.geocaching.utils; import cgeo.geocaching.cgeoapplication; +import cgeo.geocaching.compatibility.Compatibility; -import android.content.Context; import android.graphics.Bitmap; +import android.graphics.Point; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; -import android.view.Display; -import android.view.WindowManager; public class ImageHelper { @@ -24,9 +23,9 @@ public class ImageHelper { */ public static BitmapDrawable scaleBitmapToFitDisplay(final Bitmap image) { final cgeoapplication app = cgeoapplication.getInstance(); - final Display display = ((WindowManager) app.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); - final int maxWidth = display.getWidth() - 25; - final int maxHeight = display.getHeight() - 25; + Point displaySize = Compatibility.getDisplaySize(); + final int maxWidth = displaySize.x - 25; + final int maxHeight = displaySize.y - 25; Bitmap result = image; int width = image.getWidth(); diff --git a/main/src/cgeo/geocaching/utils/TranslationUtils.java b/main/src/cgeo/geocaching/utils/TranslationUtils.java index a29c5a7..4d318f0 100644 --- a/main/src/cgeo/geocaching/utils/TranslationUtils.java +++ b/main/src/cgeo/geocaching/utils/TranslationUtils.java @@ -1,12 +1,11 @@ package cgeo.geocaching.utils; import cgeo.geocaching.activity.AbstractActivity; +import cgeo.geocaching.network.Network; import android.content.Intent; import android.net.Uri; -import java.net.URLEncoder; - /** * Utilities used for translating */ @@ -30,7 +29,7 @@ public final class TranslationUtils { * @return URI ready to be parsed */ private static String buildTranslationURI(final String toLang, final String text) { - String content = URLEncoder.encode(text); + String content = Network.encode(text); // the app works better without the "+", the website works better with "+", therefore assume using the app if installed if (ProcessUtils.isInstalled(TRANSLATION_APP)) { content = content.replace("+", "%20"); |