diff options
Diffstat (limited to 'main/src')
77 files changed, 1474 insertions, 1798 deletions
diff --git a/main/src/cgeo/geocaching/CacheDetailActivity.java b/main/src/cgeo/geocaching/CacheDetailActivity.java index 5a27c9d..878d583 100644 --- a/main/src/cgeo/geocaching/CacheDetailActivity.java +++ b/main/src/cgeo/geocaching/CacheDetailActivity.java @@ -30,7 +30,6 @@ import cgeo.geocaching.utils.UnknownTagsHandler; import com.viewpagerindicator.TitlePageIndicator; import com.viewpagerindicator.TitleProvider; - import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; @@ -124,7 +123,6 @@ public class CacheDetailActivity extends AbstractActivity { private static final String CALENDAR_ADDON_URI = "market://details?id=cgeo.calendar"; - private cgGeo geolocation; private cgCache cache; private final Progress progress = new Progress(); private SearchResult search; @@ -188,10 +186,6 @@ public class CacheDetailActivity extends AbstractActivity { setContentView(R.layout.cacheview); setTitle(res.getString(R.string.cache)); - if (geolocation == null) { - geolocation = app.startGeo(locationUpdater); - } - String geocode = null; String guid = null; String name = null; @@ -330,9 +324,7 @@ public class CacheDetailActivity extends AbstractActivity { public void onResume() { super.onResume(); - if (geolocation == null) { - geolocation = app.startGeo(locationUpdater); - } + app.addGeoObserver(locationUpdater); if (refreshOnResume) { notifyDataSetChanged(); refreshOnResume = false; @@ -341,19 +333,11 @@ public class CacheDetailActivity extends AbstractActivity { @Override public void onDestroy() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } - if (cache != null) { cache.setChangeNotificationHandler(null); } @@ -363,9 +347,7 @@ public class CacheDetailActivity extends AbstractActivity { @Override public void onPause() { - if (geolocation != null) { - geolocation = app.removeGeo(); - } + app.deleteGeoObserver(locationUpdater); super.onPause(); } @@ -470,6 +452,7 @@ public class CacheDetailActivity extends AbstractActivity { switch (index) { case MENU_FIELD_COPY: ClipboardUtils.copyToClipboard(clickedItemText); + showToast(res.getString(R.string.clipboard_copy_ok)); return true; case MENU_FIELD_TRANSLATE: TranslationUtils.startActivityTranslate(this, Locale.getDefault().getLanguage(), clickedItemText.toString()); @@ -513,14 +496,14 @@ public class CacheDetailActivity extends AbstractActivity { case CONTEXT_MENU_WAYPOINT_DEFAULT_NAVIGATION: { final cgWaypoint waypoint = cache.getWaypoint(index); if (waypoint != null) { - NavigationAppFactory.startDefaultNavigationApplication(geolocation, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, waypoint, null); } } break; case CONTEXT_MENU_WAYPOINT_NAVIGATE: { final cgWaypoint waypoint = cache.getWaypoint(contextMenuWPIndex); if (waypoint != null) { - NavigationAppFactory.showNavigationMenu(geolocation, this, null, waypoint, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, waypoint, null); } } break; @@ -568,43 +551,41 @@ public class CacheDetailActivity extends AbstractActivity { public boolean onOptionsItemSelected(MenuItem item) { final int menuItem = item.getItemId(); - // no menu selected, but a new sub menu shown - if (menuItem == 0) { - return false; - } - - if (menuItem == MENU_DEFAULT_NAVIGATION) { - startDefaultNavigation(); - return true; - } else if (menuItem == MENU_LOG_VISIT) { - refreshOnResume = true; - cache.logVisit(this); - return true; - } else if (menuItem == MENU_BROWSER) { - cache.openInBrowser(this); - return true; - } else if (menuItem == MENU_CACHES_AROUND) { - cgeocaches.startActivityCachesAround(this, cache.getCoords()); - return true; - } else if (menuItem == MENU_CALENDAR) { - addToCalendarWithIntent(); - return true; - } else if (menuItem == MENU_SHARE) { - if (cache != null) { - cache.shareCache(this, res); + switch(menuItem) { + case 0: + // no menu selected, but a new sub menu shown + return false; + case MENU_DEFAULT_NAVIGATION: + startDefaultNavigation(); return true; - } - return false; + case MENU_LOG_VISIT: + refreshOnResume = true; + cache.logVisit(this); + return true; + case MENU_BROWSER: + cache.openInBrowser(this); + return true; + case MENU_CACHES_AROUND: + cgeocaches.startActivityCachesAround(this, cache.getCoords()); + return true; + case MENU_CALENDAR: + addToCalendarWithIntent(); + return true; + case MENU_SHARE: + if (cache != null) { + cache.shareCache(this, res); + return true; + } + return false; } - if (NavigationAppFactory.onMenuItemSelected(item, geolocation, this, cache, null, null)) { + if (NavigationAppFactory.onMenuItemSelected(item, app.currentGeo(), this, cache, null, null)) { return true; } if (GeneralAppsFactory.onMenuItemSelected(item, this, cache)) { return true; } - int logType = menuItem - MENU_LOG_VISIT_OFFLINE; - cache.logOffline(this, LogType.getById(logType)); + cache.logOffline(this, LogType.getById(menuItem - MENU_LOG_VISIT_OFFLINE)); return true; } @@ -709,12 +690,9 @@ public class CacheDetailActivity extends AbstractActivity { progress.dismiss(); } - private class LocationUpdater implements UpdateLocationCallback { + private class LocationUpdater extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } + public void updateLocation(final IGeoData geo) { if (cacheDistanceView == null) { return; } @@ -722,13 +700,13 @@ public class CacheDetailActivity extends AbstractActivity { try { StringBuilder dist = new StringBuilder(); - if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { - dist.append(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); + if (geo.getCoords() != null && cache != null && cache.getCoords() != null) { + dist.append(HumanDistance.getHumanDistance(geo.getCoords().distanceTo(cache.getCoords()))); } if (cache != null && cache.getElevation() != null) { - if (geo.altitudeNow != null) { - double diff = (cache.getElevation() - geo.altitudeNow); + if (geo.getAltitude() != 0.0) { + double diff = cache.getElevation() - geo.getAltitude(); if (diff >= 0) { dist.append(" ↗"); } else if (diff < 0) { @@ -863,7 +841,7 @@ public class CacheDetailActivity extends AbstractActivity { } //TODO: previously this used also the search argument "search". check if still needed - NavigationAppFactory.startDefaultNavigationApplication(geolocation, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); } /** @@ -876,7 +854,7 @@ public class CacheDetailActivity extends AbstractActivity { } //TODO: previously this used also the search argument "search". check if still needed - NavigationAppFactory.startDefaultNavigationApplication2(geolocation, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, cache, null, null); } /** @@ -894,7 +872,7 @@ public class CacheDetailActivity extends AbstractActivity { } private void showNavigationMenu() { - NavigationAppFactory.showNavigationMenu(geolocation, this, cache, null, null); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); } /** @@ -947,7 +925,7 @@ public class CacheDetailActivity extends AbstractActivity { res.getString(R.string.user_menu_open_browser) }; - AlertDialog.Builder builder = new AlertDialog.Builder(CacheDetailActivity.this); + AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(res.getString(R.string.user_menu_title) + " " + name); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { @@ -1516,10 +1494,6 @@ public class CacheDetailActivity extends AbstractActivity { } } - if (geolocation != null) { - locationUpdater.updateLocation(geolocation); - } - return view; } @@ -1805,7 +1779,7 @@ public class CacheDetailActivity extends AbstractActivity { if (cache.getListId() >= StoredList.STANDARD_LIST_ID) { long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes - String ago = ""; + String ago; if (diff < 15) { ago = res.getString(R.string.cache_offline_time_mins_few); } else if (diff < 50) { @@ -2056,7 +2030,7 @@ public class CacheDetailActivity extends AbstractActivity { // if description has HTML table, add a note at the end of the long description if (unknownTagsHandler.isTableDetected() && descriptionView == view.findViewById(R.id.longdesc)) { final int startPos = description.length(); - ((Editable) description).append("\n\n" + res.getString(R.string.cache_description_table_note)); + ((Editable) description).append("\n\n").append(res.getString(R.string.cache_description_table_note)); ((Editable) description).setSpan(new StyleSpan(Typeface.ITALIC), startPos, description.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); publishProgress(); } @@ -2402,13 +2376,13 @@ public class CacheDetailActivity extends AbstractActivity { wpNavView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { - NavigationAppFactory.startDefaultNavigationApplication(geolocation, CacheDetailActivity.this, null, wpt, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), CacheDetailActivity.this, null, wpt, null); } }); wpNavView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { - NavigationAppFactory.startDefaultNavigationApplication2(geolocation, CacheDetailActivity.this, null, wpt, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), CacheDetailActivity.this, null, wpt, null); return true; } }); diff --git a/main/src/cgeo/geocaching/DirectionProvider.java b/main/src/cgeo/geocaching/DirectionProvider.java new file mode 100644 index 0000000..6802b2a --- /dev/null +++ b/main/src/cgeo/geocaching/DirectionProvider.java @@ -0,0 +1,56 @@ +package cgeo.geocaching; + +import cgeo.geocaching.compatibility.Compatibility; +import cgeo.geocaching.utils.MemorySubject; + +import android.app.Activity; +import android.content.Context; +import android.hardware.Sensor; +import android.hardware.SensorEvent; +import android.hardware.SensorEventListener; +import android.hardware.SensorManager; + +public class DirectionProvider extends MemorySubject<Float> implements SensorEventListener { + + private final SensorManager sensorManager; + + public DirectionProvider(final Context context) { + sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); + + } + + @Override + protected void onFirstObserver() { + sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); + } + + @Override + protected void onLastObserver() { + sensorManager.unregisterListener(this); + } + + @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 + */ + + //Log.i(Settings.tag, "Compass' accuracy is low (" + accuracy + ")"); + } + + @Override + public void onSensorChanged(final SensorEvent event) { + notifyObservers(event.values[0]); + } + + public static float getDirectionNow(final Activity activity, final float direction) { + return Compatibility.getDirectionNow(direction, activity); + } + +} diff --git a/main/src/cgeo/geocaching/GeoDataProvider.java b/main/src/cgeo/geocaching/GeoDataProvider.java new file mode 100644 index 0000000..58b0696 --- /dev/null +++ b/main/src/cgeo/geocaching/GeoDataProvider.java @@ -0,0 +1,305 @@ +package cgeo.geocaching; + +import cgeo.geocaching.enumerations.LocationProviderType; +import cgeo.geocaching.geopoint.Geopoint; +import cgeo.geocaching.go4cache.Go4Cache; +import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.MemorySubject; + +import android.content.Context; +import android.location.GpsSatellite; +import android.location.GpsStatus; +import android.location.Location; +import android.location.LocationListener; +import android.location.LocationManager; +import android.os.Bundle; + +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.TimeUnit; + +/** + * Provide information about the user location. This class should be instantiated only once per application. + */ +class GeoDataProvider extends MemorySubject<IGeoData> { + + private static final String LAST_LOCATION_PSEUDO_PROVIDER = "last"; + private final LocationManager geoManager; + private final GpsStatus.Listener gpsStatusListener = new GpsStatusListener(); + private final LocationData gpsLocation = new LocationData(); + private final LocationData netLocation = new LocationData(); + private final Listener networkListener = new Listener(LocationManager.NETWORK_PROVIDER, netLocation); + private final Listener gpsListener = new Listener(LocationManager.GPS_PROVIDER, gpsLocation); + private final Unregisterer unregisterer = new Unregisterer(); + public boolean gpsEnabled = false; + public int satellitesVisible = 0; + public int satellitesFixed = 0; + + private static class LocationData { + public Location location; + public long timestamp = 0; + + public void update(final Location location) { + this.location = location; + timestamp = System.currentTimeMillis(); + } + + public boolean isRecent() { + return isValid() && System.currentTimeMillis() < timestamp + 30000; + } + + public boolean isValid() { + return location != null; + } + } + + private static class GeoData extends Location implements IGeoData { + public boolean gpsEnabled = false; + public int satellitesVisible = 0; + public int satellitesFixed = 0; + + GeoData(final Location location, final boolean gpsEnabled, final int satellitesVisible, final int satellitesFixed) { + super(location); + this.gpsEnabled = gpsEnabled; + this.satellitesVisible = satellitesVisible; + this.satellitesFixed = satellitesFixed; + } + + @Override + public Location getLocation() { + return this; + } + + private static LocationProviderType getLocationProviderType(final String provider) { + if (provider.equals(LocationManager.GPS_PROVIDER)) { + return LocationProviderType.GPS; + } + if (provider.equals(LocationManager.NETWORK_PROVIDER)) { + return LocationProviderType.NETWORK; + } + return LocationProviderType.LAST; + } + + @Override + public LocationProviderType getLocationProvider() { + return getLocationProviderType(getProvider()); + } + + @Override + public Geopoint getCoords() { + return new Geopoint(this); + } + + @Override + public boolean getGpsEnabled() { + return gpsEnabled; + } + + @Override + public int getSatellitesVisible() { + return satellitesVisible; + } + + @Override + public int getSatellitesFixed() { + return satellitesFixed; + } + } + + private class Unregisterer extends Thread { + + private boolean unregisterRequested = false; + private final ArrayBlockingQueue<Boolean> queue = new ArrayBlockingQueue<Boolean>(1); + + public void cancelUnregister() { + try { + queue.put(false); + } catch (final InterruptedException e) { + // Do nothing + } + } + + public void lateUnregister() { + try { + queue.put(true); + } catch (final InterruptedException e) { + // Do nothing + } + } + + @Override + public void run() { + try { + while (true) { + if (unregisterRequested) { + final Boolean element = queue.poll(2500, TimeUnit.MILLISECONDS); + if (element == null) { + // Timeout + unregisterListeners(); + unregisterRequested = false; + } else { + unregisterRequested = element; + } + } else { + unregisterRequested = queue.take(); + } + } + } catch (final InterruptedException e) { + // Do nothing + } + } + + } + + /** + * Build a new geo data provider object. + * <p/> + * There is no need to instantiate more than one such object in an application, as observers can be added + * at will. + * + * @param context the context used to retrieve the system services + */ + GeoDataProvider(final Context context) { + geoManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); + unregisterer.start(); + // Start with an empty GeoData just in case someone queries it before we get + // a chance to get any information. + notifyObservers(new GeoData(new Location(LAST_LOCATION_PSEUDO_PROVIDER), false, 0, 0)); + } + + private void registerListeners() { + geoManager.addGpsStatusListener(gpsStatusListener); + + for (final Listener listener : new Listener[] { networkListener, gpsListener }) { + try { + geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener); + } catch (final Exception e) { + Log.w("There is no location provider " + listener.locationProvider); + } + } + } + + private synchronized void unregisterListeners() { + // This method must be synchronized because it will be called asynchronously from the Unregisterer thread. + // We check that no observers have been re-added to prevent a race condition. + if (sizeObservers() == 0) { + geoManager.removeUpdates(networkListener); + geoManager.removeUpdates(gpsListener); + geoManager.removeGpsStatusListener(gpsStatusListener); + } + } + + @Override + protected void onFirstObserver() { + unregisterer.cancelUnregister(); + registerListeners(); + } + + @Override + protected void onLastObserver() { + unregisterer.lateUnregister(); + } + + private class Listener implements LocationListener { + private final String locationProvider; + private final LocationData locationData; + + Listener(final String locationProvider, final LocationData locationData) { + this.locationProvider = locationProvider; + this.locationData = locationData; + } + + @Override + public void onStatusChanged(final String provider, final int status, final Bundle extras) { + // nothing + } + + @Override + public void onProviderDisabled(final String provider) { + // nothing + } + + @Override + public void onProviderEnabled(final String provider) { + // nothing + } + + @Override + public void onLocationChanged(final Location location) { + locationData.update(location); + selectBest(); + } + } + + private final class GpsStatusListener implements GpsStatus.Listener { + + @Override + public void onGpsStatusChanged(final int event) { + boolean changed = false; + switch (event) { + case GpsStatus.GPS_EVENT_SATELLITE_STATUS: { + final GpsStatus status = geoManager.getGpsStatus(null); + int visible = 0; + int fixed = 0; + for (final GpsSatellite satellite : status.getSatellites()) { + if (satellite.usedInFix()) { + fixed++; + } + visible++; + } + if (visible != satellitesVisible || fixed != satellitesFixed) { + satellitesVisible = visible; + satellitesFixed = fixed; + changed = true; + } + break; + } + case GpsStatus.GPS_EVENT_STARTED: + if (!gpsEnabled) { + gpsEnabled = true; + changed = true; + } + break; + case GpsStatus.GPS_EVENT_STOPPED: + if (gpsEnabled) { + gpsEnabled = false; + satellitesFixed = 0; + satellitesVisible = 0; + changed = true; + } + break; + } + + if (changed) { + selectBest(); + } + } + } + + private LocationData best() { + if (gpsLocation.isRecent() || !netLocation.isValid()) { + return gpsLocation.isValid() ? gpsLocation : null; + } + if (!gpsLocation.isValid()) { + return netLocation; + } + return gpsLocation.timestamp > netLocation.timestamp ? gpsLocation : netLocation; + } + + private void selectBest() { + assign(best()); + } + + private void assign(final LocationData locationData) { + if (locationData == null) { + return; + } + + // We do not necessarily get signalled when satellites go to 0/0. + final int visible = gpsLocation.isRecent() ? satellitesVisible : 0; + final IGeoData current = new GeoData(locationData.location, gpsEnabled, visible, satellitesFixed); + notifyObservers(current); + + Go4Cache.signalCoordinates(current.getCoords()); + } + +} diff --git a/main/src/cgeo/geocaching/GeoObserver.java b/main/src/cgeo/geocaching/GeoObserver.java new file mode 100644 index 0000000..8d5475f --- /dev/null +++ b/main/src/cgeo/geocaching/GeoObserver.java @@ -0,0 +1,13 @@ +package cgeo.geocaching; + +import cgeo.geocaching.utils.IObserver; + +public abstract class GeoObserver implements IObserver<IGeoData> { + + abstract protected void updateLocation(final IGeoData geo); + + @Override + public void update(final IGeoData geo) { + updateLocation(geo); + } +} diff --git a/main/src/cgeo/geocaching/IGeoData.java b/main/src/cgeo/geocaching/IGeoData.java new file mode 100644 index 0000000..9696b27 --- /dev/null +++ b/main/src/cgeo/geocaching/IGeoData.java @@ -0,0 +1,21 @@ +package cgeo.geocaching; + +import cgeo.geocaching.enumerations.LocationProviderType; +import cgeo.geocaching.geopoint.Geopoint; + +import android.location.Location; + +public interface IGeoData { + + public Location getLocation(); + public LocationProviderType getLocationProvider(); + public Geopoint getCoords(); + public double getAltitude(); + public float getBearing(); + public float getSpeed(); + public float getAccuracy(); + public boolean getGpsEnabled(); + public int getSatellitesVisible(); + public int getSatellitesFixed(); + +} diff --git a/main/src/cgeo/geocaching/StaticMapsProvider.java b/main/src/cgeo/geocaching/StaticMapsProvider.java index 2ae54b5..9fbf429 100644 --- a/main/src/cgeo/geocaching/StaticMapsProvider.java +++ b/main/src/cgeo/geocaching/StaticMapsProvider.java @@ -137,7 +137,7 @@ public class StaticMapsProvider { private static int guessMinDisplaySide(Display display) { final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; - int edge = 0; + int edge; if (maxWidth > maxHeight) { edge = maxWidth; } else { diff --git a/main/src/cgeo/geocaching/UpdateDirectionCallback.java b/main/src/cgeo/geocaching/UpdateDirectionCallback.java deleted file mode 100644 index 9381917..0000000 --- a/main/src/cgeo/geocaching/UpdateDirectionCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package cgeo.geocaching; - -public interface UpdateDirectionCallback { - public void updateDirection(cgDirection dir); -} diff --git a/main/src/cgeo/geocaching/UpdateLocationCallback.java b/main/src/cgeo/geocaching/UpdateLocationCallback.java deleted file mode 100644 index f0334a1..0000000 --- a/main/src/cgeo/geocaching/UpdateLocationCallback.java +++ /dev/null @@ -1,5 +0,0 @@ -package cgeo.geocaching; - -public interface UpdateLocationCallback { - public void updateLocation(cgGeo geo); -} diff --git a/main/src/cgeo/geocaching/VisitCacheActivity.java b/main/src/cgeo/geocaching/VisitCacheActivity.java index 96bd549..c5a178a 100644 --- a/main/src/cgeo/geocaching/VisitCacheActivity.java +++ b/main/src/cgeo/geocaching/VisitCacheActivity.java @@ -88,16 +88,13 @@ public class VisitCacheActivity extends AbstractActivity implements DateDialog.D showToast(res.getString(R.string.info_log_type_changed)); } - if (Login.isEmpty(viewstates) && attempts < 2) { - final LoadDataThread thread; - thread = new LoadDataThread(); - thread.start(); - - return; - } else if (Login.isEmpty(viewstates) && attempts >= 2) { - showToast(res.getString(R.string.err_log_load_data)); - showProgress(false); - + if (Login.isEmpty(viewstates)) { + if (attempts < 2) { + new LoadDataThread().start(); + } else { + showToast(res.getString(R.string.err_log_load_data)); + showProgress(false); + } return; } @@ -295,7 +292,7 @@ public class VisitCacheActivity extends AbstractActivity implements DateDialog.D @Override public boolean onCreateOptionsMenu(Menu menu) { - SubMenu menuLog = null; + SubMenu menuLog; menuLog = menu.addSubMenu(0, 0, 0, res.getString(R.string.log_add)).setIcon(R.drawable.ic_menu_add); for (LogTemplate template : LogTemplateProvider.getTemplates()) { @@ -336,7 +333,9 @@ public class VisitCacheActivity extends AbstractActivity implements DateDialog.D if (id == MENU_SIGNATURE) { insertIntoLog(LogTemplateProvider.applyTemplates(Settings.getSignature(), false), true); return true; - } else if (id >= 10 && id <= 19) { + } + + if (id >= 10 && id <= 19) { rating = (id - 9) / 2.0; if (rating < 1) { rating = 0; @@ -344,12 +343,13 @@ public class VisitCacheActivity extends AbstractActivity implements DateDialog.D updatePostButtonText(); return true; } + final LogTemplate template = LogTemplateProvider.getTemplate(id); if (template != null) { - final String newText = template.getValue(false); - insertIntoLog(newText, true); + insertIntoLog(template.getValue(false), true); return true; } + return false; } @@ -400,9 +400,10 @@ public class VisitCacheActivity extends AbstractActivity implements DateDialog.D if (group == R.id.type) { setType(LogType.getById(id)); - return true; - } else if (group == R.id.changebutton) { + } + + if (group == R.id.changebutton) { try { final LogTypeTrackable logType = LogTypeTrackable.findById(id); if (logType != null) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java index bf7ebb1..16b641e 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/AbstractPointNavigationApp.java @@ -1,7 +1,7 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; @@ -24,7 +24,7 @@ abstract class AbstractPointNavigationApp extends AbstractNavigationApp { } @Override - public final boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, Geopoint coords) { + public final boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, Geopoint coords) { if (cache == null && waypoint == null && coords == null) { return false; } @@ -46,13 +46,24 @@ abstract class AbstractPointNavigationApp extends AbstractNavigationApp { protected abstract void navigate(Activity activity, Geopoint point); - private static Geopoint getCoordinates(cgCache cache, cgWaypoint waypoint, Geopoint coords) { + /** + * Return the first of the cache coordinates, the waypoint coordinates or the extra coordinates. <code>null</code> + * entities are skipped. + * + * @param cache a cache + * @param waypoint a waypoint + * @param coords extra coordinates + * @return the first non-null coordinates, or null if none are set + */ + private static Geopoint getCoordinates(final cgCache cache, final cgWaypoint waypoint, final Geopoint coords) { if (cache != null && cache.getCoords() != null) { return cache.getCoords(); } - else if (waypoint != null && waypoint.getCoords() != null) { + + if (waypoint != null && waypoint.getCoords() != null) { return waypoint.getCoords(); } + return coords; } }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java b/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java index 3d804d9..720b85a 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/CompassApp.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeonavigate; import cgeo.geocaching.geopoint.Geopoint; @@ -22,7 +22,7 @@ class CompassApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { if (cache != null && cache.getGeocode() != null) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java index 74141c3..fb72157 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/GoogleNavigationApp.java @@ -1,11 +1,11 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.Settings; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; @@ -26,7 +26,7 @@ class GoogleNavigationApp extends AbstractNavigationApp { } @Override - public boolean invoke(final cgGeo geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords) { if (activity == null) { return false; } @@ -50,8 +50,8 @@ class GoogleNavigationApp extends AbstractNavigationApp { return true; } - private static boolean navigateToCoordinates(cgGeo geo, Activity activity, final Geopoint coords) { - final Geopoint coordsNow = geo == null ? null : geo.coordsNow; + private static boolean navigateToCoordinates(IGeoData geo, Activity activity, final Geopoint coords) { + final Geopoint coordsNow = geo == null ? null : geo.getCoords(); // Google Navigation if (Settings.isUseGoogleNavigation()) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java index 44f151e..2f05459 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/InternalMap.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.enumerations.WaypointType; import cgeo.geocaching.geopoint.Geopoint; @@ -18,7 +18,7 @@ class InternalMap extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { if (cache != null) { CGeoMap.startActivityGeoCode(activity, cache.getGeocode()); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java index c867373..60e3315 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/LocusApp.java @@ -1,9 +1,9 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; +import cgeo.geocaching.apps.AbstractLocusApp; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.apps.AbstractLocusApp; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; @@ -20,7 +20,7 @@ class LocusApp extends AbstractLocusApp implements NavigationApp { * @author koem */ @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { final ArrayList<Object> points = new ArrayList<Object>(); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java index 119d27b..62629de 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationApp.java @@ -1,15 +1,15 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; +import cgeo.geocaching.apps.App; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.apps.App; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; public interface NavigationApp extends App { - public boolean invoke(final cgGeo geo, final Activity activity, + public boolean invoke(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint coords); } diff --git a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java index 4a9032a..e0c773c 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/NavigationAppFactory.java @@ -1,14 +1,13 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; -import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.StaticMapsProvider; +import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; -import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.utils.Log; @@ -80,7 +79,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * A dialog is created for tool selection and the selected tool is started afterwards. * <p /> * Delegates to - * {@link #showNavigationMenu(cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint, boolean, boolean)} with + * {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} with * <code>showInternalMap = true</code> and <code>showDefaultNavigation = false</code> * * @param geo @@ -89,7 +88,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param waypoint * @param destination */ - public static void showNavigationMenu(final cgGeo geo, final Activity activity, + public static void showNavigationMenu(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint destination) { showNavigationMenu(geo, activity, cache, waypoint, destination, true, false); } @@ -111,9 +110,9 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param showDefaultNavigation * should be <code>false</code> by default * - * @see #showNavigationMenu(cgGeo, Activity, cgCache, cgWaypoint, Geopoint) + * @see #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint) */ - public static void showNavigationMenu(final cgGeo geo, final Activity activity, + public static void showNavigationMenu(final IGeoData geo, final Activity activity, final cgCache cache, final cgWaypoint waypoint, final Geopoint destination, final boolean showInternalMap, final boolean showDefaultNavigation) { final AlertDialog.Builder builder = new AlertDialog.Builder(activity); @@ -188,10 +187,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** * Adds the installed navigation tools to the given menu. - * Use {@link #onMenuItemSelected(MenuItem, cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint)} on + * Use {@link #onMenuItemSelected(MenuItem, IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} on * selection event to start the selected navigation tool. * - * <b>Only use this way if {@link #showNavigationMenu(cgGeo, Activity, cgCache, SearchResult, cgWaypoint, Geopoint)} + * <b>Only use this way if {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} * is not suitable for the given usecase.</b> * * @param menu @@ -203,11 +202,11 @@ public final class NavigationAppFactory extends AbstractAppFactory { /** * Adds the installed navigation tools to the given menu. - * Use {@link #onMenuItemSelected(MenuItem, cgGeo, Activity, cgCache, cgWaypoint, Geopoint)} on + * Use {@link #onMenuItemSelected(MenuItem, IGeoData, Activity, cgCache, cgWaypoint, Geopoint)} on * selection event to start the selected navigation tool. * * <b>Only use this way if - * {@link #showNavigationMenu(cgGeo, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} is + * {@link #showNavigationMenu(IGeoData, Activity, cgCache, cgWaypoint, Geopoint, boolean, boolean)} is * not suitable for the given usecase.</b> * * @param menu @@ -239,7 +238,7 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @return */ public static boolean onMenuItemSelected(final MenuItem item, - final cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { + final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { if (cache == null && waypoint == null && destination == null) { return false; } @@ -271,11 +270,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param geo * @param activity * @param cache - * @param search * @param waypoint * @param destination */ - public static void startDefaultNavigationApplication(final cgGeo geo, Activity activity, cgCache cache, + public static void startDefaultNavigationApplication(final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { final NavigationApp app = getDefaultNavigationApplication(activity); @@ -294,11 +292,10 @@ public final class NavigationAppFactory extends AbstractAppFactory { * @param geo * @param activity * @param cache - * @param search * @param waypoint * @param destination */ - public static void startDefaultNavigationApplication2(final cgGeo geo, Activity activity, cgCache cache, + public static void startDefaultNavigationApplication2(final IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint destination) { final NavigationApp app = getDefaultNavigationApplication2(activity); diff --git a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java index a87e61b..9af90ac 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/RMapsApp.java @@ -1,8 +1,8 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter.Format; @@ -21,7 +21,7 @@ class RMapsApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { try { final ArrayList<String> locations = new ArrayList<String>(); if (cache != null && cache.getCoords() != null) { diff --git a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java index db316bd..d8b66c2 100644 --- a/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java +++ b/main/src/cgeo/geocaching/apps/cache/navi/StaticMapApp.java @@ -1,12 +1,12 @@ package cgeo.geocaching.apps.cache.navi; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.ILogable; import cgeo.geocaching.R; import cgeo.geocaching.StaticMapsActivity; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.geopoint.Geopoint; import android.app.Activity; @@ -25,7 +25,7 @@ class StaticMapApp extends AbstractNavigationApp { } @Override - public boolean invoke(cgGeo geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { + public boolean invoke(IGeoData geo, Activity activity, cgCache cache, cgWaypoint waypoint, final Geopoint coords) { final ILogable logable = cache != null && cache.getListId() != 0 ? cache : waypoint; final String geocode = logable.getGeocode().toUpperCase(); if (geocode == null) { diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java index 621aea4..45ebaff 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListApp.java @@ -1,9 +1,9 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.App; +import cgeo.geocaching.cgCache; import android.app.Activity; @@ -11,7 +11,7 @@ import java.util.List; interface CacheListApp extends App { - boolean invoke(final cgGeo geo, final List<cgCache> caches, + boolean invoke(final IGeoData geo, final List<cgCache> caches, final Activity activity, final SearchResult search); } diff --git a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java index d0ae3df..0b36716 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java +++ b/main/src/cgeo/geocaching/apps/cachelist/CacheListAppFactory.java @@ -1,15 +1,13 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.activity.IAbstractActivity; import cgeo.geocaching.apps.AbstractAppFactory; import cgeo.geocaching.utils.Log; -import org.apache.commons.lang3.ArrayUtils; - import android.app.Activity; import android.content.res.Resources; import android.view.Menu; @@ -20,16 +18,12 @@ import java.util.ArrayList; import java.util.List; public final class CacheListAppFactory extends AbstractAppFactory { - private static CacheListApp[] apps = new CacheListApp[] {}; - - private static CacheListApp[] getMultiPointNavigationApps() { - if (ArrayUtils.isEmpty(apps)) { - apps = new CacheListApp[] { - new InternalCacheListMap(), - new LocusCacheListApp(false), - new LocusCacheListApp(true) }; - } - return apps; + private static class LazyHolder { + public static final CacheListApp[] apps = { + new InternalCacheListMap(), + new LocusCacheListApp(false), + new LocusCacheListApp(true) + }; } /** @@ -38,34 +32,34 @@ public final class CacheListAppFactory extends AbstractAppFactory { * @param res * @return the added menu item (also for a sub menu, then the menu item in the parent menu is returned) */ - public static MenuItem addMenuItems(Menu menu, - Activity activity, Resources res) { - List<CacheListApp> activeApps = new ArrayList<CacheListApp>(); - for (CacheListApp app : getMultiPointNavigationApps()) { + public static MenuItem addMenuItems(final Menu menu, final Activity activity, final Resources res) { + final List<CacheListApp> activeApps = new ArrayList<CacheListApp>(LazyHolder.apps.length); + for (final CacheListApp app : LazyHolder.apps) { if (app.isInstalled(activity)) { activeApps.add(app); } } // use a new sub menu, if more than one app is available - if (activeApps.size() > 1) { - SubMenu subMenu = menu.addSubMenu(0, 101, 0, - res.getString(R.string.caches_on_map)).setIcon( - R.drawable.ic_menu_mapmode); - for (CacheListApp app : activeApps) { - subMenu.add(0, app.getId(), 0, app.getName()); - } - return subMenu.getItem(); - } else if (activeApps.size() == 1) { - return menu.add(0, activeApps.get(0).getId(), 0, - activeApps.get(0).getName()).setIcon(R.drawable.ic_menu_mapmode); + switch (activeApps.size()) { + case 0: + return null; + case 1: + return menu.add(0, activeApps.get(0).getId(), 0, + activeApps.get(0).getName()).setIcon(R.drawable.ic_menu_mapmode); + default: + final SubMenu subMenu = menu.addSubMenu(0, 101, 0, + res.getString(R.string.caches_on_map)).setIcon(R.drawable.ic_menu_mapmode); + for (final CacheListApp app : activeApps) { + subMenu.add(0, app.getId(), 0, app.getName()); + } + return subMenu.getItem(); } - return null; } public static boolean onMenuItemSelected(final MenuItem item, - final cgGeo geo, final List<cgCache> caches, final IAbstractActivity activity, + final IGeoData geo, final List<cgCache> caches, final IAbstractActivity activity, final SearchResult search) { - CacheListApp app = (CacheListApp) getAppFromMenuItem(item, apps); + final CacheListApp app = (CacheListApp) getAppFromMenuItem(item, LazyHolder.apps); if (app != null) { try { boolean result = app.invoke(geo, caches, (Activity) activity, search); diff --git a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java index 5eaefc9..f450bbc 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java +++ b/main/src/cgeo/geocaching/apps/cachelist/InternalCacheListMap.java @@ -1,10 +1,10 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.AbstractApp; +import cgeo.geocaching.cgCache; import cgeo.geocaching.maps.CGeoMap; import android.app.Activity; @@ -24,7 +24,7 @@ class InternalCacheListMap extends AbstractApp implements CacheListApp { } @Override - public boolean invoke(cgGeo geo, List<cgCache> caches, Activity activity, final SearchResult search) { + public boolean invoke(IGeoData geo, List<cgCache> caches, Activity activity, final SearchResult search) { CGeoMap.startActivitySearch(activity, search, null); return true; } diff --git a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java index 1b50861..b7557c3 100644 --- a/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java +++ b/main/src/cgeo/geocaching/apps/cachelist/LocusCacheListApp.java @@ -1,10 +1,10 @@ package cgeo.geocaching.apps.cachelist; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; -import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.apps.AbstractLocusApp; +import cgeo.geocaching.cgCache; import org.apache.commons.collections.CollectionUtils; @@ -29,7 +29,7 @@ class LocusCacheListApp extends AbstractLocusApp implements CacheListApp { * @author koem */ @Override - public boolean invoke(cgGeo geo, List<cgCache> cacheList, Activity activity, final SearchResult search) { + public boolean invoke(IGeoData geo, List<cgCache> cacheList, Activity activity, final SearchResult search) { if (CollectionUtils.isEmpty(cacheList)) { return false; } diff --git a/main/src/cgeo/geocaching/cgData.java b/main/src/cgeo/geocaching/cgData.java index c290917..9b83a7e 100644 --- a/main/src/cgeo/geocaching/cgData.java +++ b/main/src/cgeo/geocaching/cgData.java @@ -751,7 +751,7 @@ public class cgData { "100"); if (cursor != null) { - int index = 0; + int index; if (cursor.getCount() > 0) { cursor.moveToFirst(); @@ -812,7 +812,7 @@ public class cgData { } if (cursor != null) { - int index = 0; + int index; cnt = cursor.getCount(); if (cnt > 0) { @@ -863,7 +863,7 @@ public class cgData { public boolean isOffline(String geocode, String guid) { init(); - Cursor cursor = null; + Cursor cursor; long listId = StoredList.TEMPORARY_LIST_ID; try { @@ -893,7 +893,7 @@ public class cgData { if (cursor != null) { final int cnt = cursor.getCount(); - int index = 0; + int index; if (cnt > 0) { cursor.moveToFirst(); @@ -1227,11 +1227,7 @@ public class cgData { ok = true; } else { final int rows = databaseRW.update(dbTableWaypoints, values, "_id = " + id, null); - if (rows > 0) { - ok = true; - } else { - ok = false; - } + ok = rows > 0; } databaseRW.setTransactionSuccessful(); } finally { @@ -1945,7 +1941,7 @@ public class cgData { cursor.getString(indexLog)); log.id = cursor.getInt(indexLogsId); log.found = cursor.getInt(indexFound); - log.friend = cursor.getInt(indexFriend) == 1 ? true : false; + log.friend = cursor.getInt(indexFriend) == 1; logs.add(log); } if (!cursor.isNull(indexLogImagesId)) { @@ -2104,8 +2100,8 @@ public class cgData { } init(); - String listSql = null; - String listSqlW = null; + String listSql; + String listSqlW; if (list == 0) { listSql = " where reason >= 1"; listSqlW = " and reason >= 1"; @@ -2118,7 +2114,7 @@ public class cgData { int count = 0; try { - String sql = "select count(_id) from " + dbTableCaches; // this default is not used, but we like to have variables initialized + String sql; if (!detailedOnly) { if (cacheType == CacheType.ALL) { sql = "select count(_id) from " + dbTableCaches + listSql; @@ -2371,7 +2367,7 @@ public class cgData { Log.d("Database clean: started"); - Cursor cursor = null; + Cursor cursor; Set<String> geocodes = new HashSet<String>(); try { @@ -2951,7 +2947,7 @@ public class cgData { for (int i = 0; i < WAYPOINT_COLUMNS.length; i++) { query.append(i > 0 ? ", " : "").append(dbTableWaypoints).append('.').append(WAYPOINT_COLUMNS[i]).append(' '); } - query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints).append("._id == ").append(dbTableCaches).append("._id and ").append(where); + query.append(" FROM ").append(dbTableWaypoints).append(", ").append(dbTableCaches).append(" WHERE ").append(dbTableWaypoints).append(".geocode == ").append(dbTableCaches).append(".geocode and ").append(where); final Cursor cursor = databaseRO.rawQuery(query.toString(), null); try { diff --git a/main/src/cgeo/geocaching/cgDirection.java b/main/src/cgeo/geocaching/cgDirection.java deleted file mode 100644 index d985a7b..0000000 --- a/main/src/cgeo/geocaching/cgDirection.java +++ /dev/null @@ -1,67 +0,0 @@ -package cgeo.geocaching; - -import cgeo.geocaching.compatibility.Compatibility; - -import android.app.Activity; -import android.content.Context; -import android.hardware.Sensor; -import android.hardware.SensorEvent; -import android.hardware.SensorEventListener; -import android.hardware.SensorManager; - -public class cgDirection { - private final Context context; - private final SensorManager sensorManager; - private final SensorListener sensorListener; - private UpdateDirectionCallback updateDirectionCallback = null; - - public Float directionNow = null; - - public cgDirection(Context contextIn, UpdateDirectionCallback callback) { - context = contextIn; - updateDirectionCallback = callback; - sensorListener = new SensorListener(); - sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); - sensorManager.registerListener(sensorListener, sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_NORMAL); - } - - public void closeDir() { - if (sensorManager != null && sensorListener != null) { - sensorManager.unregisterListener(sensorListener); - } - } - - public void replaceUpdate(UpdateDirectionCallback callback) { - updateDirectionCallback = callback; - fireDirectionCallback(); - } - - private void fireDirectionCallback() { - if (updateDirectionCallback != null && directionNow != null) { - updateDirectionCallback.updateDirection(this); - } - } - - private final class SensorListener implements SensorEventListener { - @Override - public void onAccuracyChanged(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 - */ - - //Log.i(Settings.tag, "Compass' accuracy is low (" + accuracy + ")"); - } - - @Override - public void onSensorChanged(SensorEvent event) { - directionNow = Compatibility.getDirectionNow(event.values[0], (Activity) context); - fireDirectionCallback(); - } - } -} diff --git a/main/src/cgeo/geocaching/cgGeo.java b/main/src/cgeo/geocaching/cgGeo.java deleted file mode 100644 index c5ab556..0000000 --- a/main/src/cgeo/geocaching/cgGeo.java +++ /dev/null @@ -1,252 +0,0 @@ -package cgeo.geocaching; - -import cgeo.geocaching.enumerations.LocationProviderType; -import cgeo.geocaching.geopoint.Geopoint; -import cgeo.geocaching.go4cache.Go4Cache; -import cgeo.geocaching.utils.Log; - -import android.content.Context; -import android.location.GpsSatellite; -import android.location.GpsStatus; -import android.location.Location; -import android.location.LocationListener; -import android.location.LocationManager; -import android.os.Bundle; - -import java.util.Iterator; - -public class cgGeo { - - private static final String LAST_LOCATION_PSEUDO_PROVIDER = "last"; - private final LocationManager geoManager = (LocationManager) cgeoapplication.getInstance().getSystemService(Context.LOCATION_SERVICE); - private UpdateLocationCallback updateLocationCallback = null; - private final AbstractLocationListener networkListener = new NetworkLocationListener(); - private final AbstractLocationListener gpsListener = new GpsLocationListener(); - private final GpsStatusListener gpsStatusListener = new GpsStatusListener(); - private Location locGps = null; - private Location locNet = null; - private long locGpsLast = 0L; - public Location location = null; - public LocationProviderType locationProvider = LocationProviderType.LAST; - public Geopoint coordsNow = null; - public Double altitudeNow = null; - public float bearingNow = 0; - public float speedNow = 0; - public float accuracyNow = -1f; - public int satellitesVisible = 0; - public int satellitesFixed = 0; - - public cgGeo() { - restoreLastLocation(); - - geoManager.addGpsStatusListener(gpsStatusListener); - - for (AbstractLocationListener listener : new AbstractLocationListener[] { networkListener, gpsListener }) { - try { - geoManager.requestLocationUpdates(listener.locationProvider, 0, 0, listener); - } catch (Exception e) { - Log.w("There is no location provider " + listener.locationProvider); - } - } - } - - public void closeGeo() { - geoManager.removeUpdates(networkListener); - geoManager.removeUpdates(gpsListener); - geoManager.removeGpsStatusListener(gpsStatusListener); - } - - public void replaceUpdate(UpdateLocationCallback callback) { - updateLocationCallback = callback; - fireLocationCallback(); - } - - private void fireLocationCallback() { - if (updateLocationCallback != null) { - updateLocationCallback.updateLocation(this); - } - } - - private static abstract class AbstractLocationListener implements LocationListener { - private final String locationProvider; - - protected AbstractLocationListener(String provider) { - this.locationProvider = provider; - } - - @Override - public void onStatusChanged(String provider, int status, Bundle extras) { - // nothing - } - - @Override - public void onProviderDisabled(String provider) { - // nothing - } - - @Override - public void onProviderEnabled(String provider) { - // nothing - } - } - - private final class GpsLocationListener extends AbstractLocationListener { - - public GpsLocationListener() { - super(LocationManager.GPS_PROVIDER); - } - - @Override - public void onLocationChanged(Location location) { - locGps = location; - locGpsLast = System.currentTimeMillis(); - selectBest(location.getProvider()); - } - } - - private final class NetworkLocationListener extends AbstractLocationListener { - - protected NetworkLocationListener() { - super(LocationManager.NETWORK_PROVIDER); - } - - @Override - public void onLocationChanged(Location location) { - locNet = location; - selectBest(location.getProvider()); - } - - } - - private final class GpsStatusListener implements GpsStatus.Listener { - - @Override - public void onGpsStatusChanged(int event) { - if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS) { - final GpsStatus status = geoManager.getGpsStatus(null); - final Iterator<GpsSatellite> statusIterator = status.getSatellites().iterator(); - - int satellites = 0; - int fixed = 0; - - while (statusIterator.hasNext()) { - GpsSatellite sat = statusIterator.next(); - if (sat.usedInFix()) { - fixed++; - } - satellites++; - } - - boolean changed = false; - if (satellites != satellitesVisible) { - satellitesVisible = satellites; - changed = true; - } - if (fixed != satellitesFixed) { - satellitesFixed = fixed; - changed = true; - } - - if (changed) { - selectBest(null); - } - } - } - } - - private void selectBest(final String signallingProvider) { - if (locNet != null && locGps == null) { // we have only NET - assign(locNet); - } - else if ((locNet == null && locGps != null) // we have only GPS - || (satellitesFixed > 0) // GPS seems to be fixed - || (signallingProvider != null && signallingProvider.equals(LocationManager.GPS_PROVIDER)) // we have new location from GPS - || locGpsLast > (System.currentTimeMillis() - 30 * 1000) // GPS was working in last 30 seconds - ) { - assign(locGps); - } - else { - assign(locNet); // nothing else, using NET - } - } - - private void assignLastLocation(final Geopoint coords) { - if (coords == null) { - return; - } - - locationProvider = LocationProviderType.LAST; - coordsNow = coords; - altitudeNow = null; - bearingNow = 0f; - speedNow = 0f; - accuracyNow = 999f; - - fireLocationCallback(); - } - - private void assign(final Location loc) { - if (loc == null) { - locationProvider = LocationProviderType.LAST; - return; - } - - location = loc; - - final String provider = location.getProvider(); - if (provider.equals(LocationManager.GPS_PROVIDER)) { - locationProvider = LocationProviderType.GPS; - } else if (provider.equals(LocationManager.NETWORK_PROVIDER)) { - locationProvider = LocationProviderType.NETWORK; - } else if (provider.equalsIgnoreCase(LAST_LOCATION_PSEUDO_PROVIDER)) { - locationProvider = LocationProviderType.LAST; - } - - coordsNow = new Geopoint(location.getLatitude(), location.getLongitude()); - cgeoapplication.getInstance().setLastCoords(coordsNow); - - if (location.hasAltitude() && locationProvider != LocationProviderType.LAST) { - altitudeNow = location.getAltitude() + Settings.getAltCorrection(); - } else { - altitudeNow = null; - } - if (location.hasBearing() && locationProvider != LocationProviderType.LAST) { - bearingNow = location.getBearing(); - } else { - bearingNow = 0f; - } - if (location.hasSpeed() && locationProvider != LocationProviderType.LAST) { - speedNow = location.getSpeed(); - } else { - speedNow = 0f; - } - if (location.hasAccuracy() && locationProvider != LocationProviderType.LAST) { - accuracyNow = location.getAccuracy(); - } else { - accuracyNow = 999f; - } - - fireLocationCallback(); - - if (locationProvider == LocationProviderType.GPS || locationProvider == LocationProviderType.NETWORK) { - Go4Cache.signalCoordinates(coordsNow); - } - } - - private void restoreLastLocation() { - // restore from last location (stored by app) - assignLastLocation(cgeoapplication.getInstance().getLastCoords()); - - // restore from last location (stored by device sensors) - for (String provider : new String[] { LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER }) { - final Location lastLocation = geoManager.getLastKnownLocation(provider); - if (lastLocation != null) { - lastLocation.setProvider(LAST_LOCATION_PSEUDO_PROVIDER); - assign(lastLocation); - - Log.i("Using last location from " + provider); - break; - } - } - } -} diff --git a/main/src/cgeo/geocaching/cgeo.java b/main/src/cgeo/geocaching/cgeo.java index 72a931d..3cf5f44 100644 --- a/main/src/cgeo/geocaching/cgeo.java +++ b/main/src/cgeo/geocaching/cgeo.java @@ -10,6 +10,7 @@ import cgeo.geocaching.geopoint.HumanDistance; import cgeo.geocaching.geopoint.IConversion; import cgeo.geocaching.maps.CGeoMap; import cgeo.geocaching.ui.Formatter; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.collections.CollectionUtils; @@ -22,12 +23,11 @@ import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; +import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.res.Configuration; import android.location.Address; import android.location.Geocoder; -import android.location.GpsStatus; -import android.location.LocationManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; @@ -58,7 +58,6 @@ public class cgeo extends AbstractActivity { public static final int SEARCH_REQUEST_CODE = 2; private int version = 0; - private cgGeo geo = null; private TextView filterTitle = null; private boolean cleanupRunning = false; private int countBubbleCnt = 0; @@ -67,8 +66,7 @@ public class cgeo extends AbstractActivity { private boolean addressObtaining = false; private boolean initialized = false; - private LocationManager locationManager; - private boolean gpsEnabled = false; + final private UpdateLocation locationUpdater = new UpdateLocation(); private Handler updateUserInfoHandler = new Handler() { @@ -115,9 +113,7 @@ public class cgeo extends AbstractActivity { addText.append(address.getAdminArea()); } - if (geo != null) { - addCoords = geo.coordsNow; - } + addCoords = app.currentGeo().getCoords(); TextView navLocation = (TextView) findViewById(R.id.nav_location); navLocation.setText(addText.toString()); @@ -130,40 +126,40 @@ public class cgeo extends AbstractActivity { } }; - private class SatellitesHandler extends Handler { + private class SatellitesHandler extends Handler implements IObserver<IGeoData> { - final private static int NO_GPS = 0; - final private static int SATELLITES = 1; + private boolean gpsEnabled = false; + private int satellitesFixed = 0; + private int satellitesVisible = 0; @Override public void handleMessage(final Message msg) { - String satellites = ""; - switch (msg.what) { - case NO_GPS: - satellites = res.getString(R.string.loc_gps_disabled); - break; - case SATELLITES: - final int satellitesFixed = msg.arg1; - final int satellitesVisible = msg.arg2; - if (satellitesFixed > 0) { - satellites = res.getString(R.string.loc_sat) + ": " + satellitesFixed + '/' + satellitesVisible; - } else if (satellitesVisible >= 0) { - satellites = res.getString(R.string.loc_sat) + ": 0/" + satellitesVisible; - } - break; + final IGeoData data = (IGeoData) msg.obj; + if (data.getGpsEnabled() == gpsEnabled && + data.getSatellitesFixed() == satellitesFixed && + data.getSatellitesVisible() == satellitesVisible) { + return; } - final TextView navSatellites = (TextView) findViewById(R.id.nav_satellites); - navSatellites.setText(satellites); - } + gpsEnabled = data.getGpsEnabled(); + satellitesFixed = data.getSatellitesFixed(); + satellitesVisible = data.getSatellitesVisible(); - public void noGps() { - obtainMessage(NO_GPS).sendToTarget(); + final TextView navSatellites = (TextView) findViewById(R.id.nav_satellites); + if (gpsEnabled) { + if (satellitesFixed > 0) { + navSatellites.setText(res.getString(R.string.loc_sat) + ": " + satellitesFixed + '/' + satellitesVisible); + } else if (satellitesVisible >= 0) { + navSatellites.setText(res.getString(R.string.loc_sat) + ": 0/" + satellitesVisible); + } + } else { + navSatellites.setText(res.getString(R.string.loc_gps_disabled)); + } } - public void satellites(final int fixed, final int visible) { - obtainMessage(SATELLITES, fixed, visible).sendToTarget(); + @Override + public void update(final IGeoData data) { + obtainMessage(0, data).sendToTarget(); } - } private SatellitesHandler satellitesHandler = new SatellitesHandler(); @@ -184,21 +180,6 @@ public class cgeo extends AbstractActivity { } }; - private final GpsStatus.Listener gpsListener = new GpsStatus.Listener() { - - @Override - public void onGpsStatusChanged(int event) { - if (event == GpsStatus.GPS_EVENT_STARTED && !gpsEnabled) { - satellitesHandler.satellites(0, 0); - gpsEnabled = true; - } else if (event == GpsStatus.GPS_EVENT_STOPPED && gpsEnabled) { - satellitesHandler.noGps(); - gpsEnabled = false; - } - } - - }; - public cgeo() { super("c:geo-main-screen"); } @@ -209,29 +190,20 @@ public class cgeo extends AbstractActivity { app.setAction(null); - app.cleanGeo(); - app.cleanDir(); - setContentView(R.layout.main); setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL); // type to search try { - PackageManager manager = this.getPackageManager(); - PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); - + final PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0); version = info.versionCode; - - Log.i("Starting " + info.packageName + " " + info.versionCode + " a.k.a " + info.versionName + "..."); - - info = null; - manager = null; - } catch (Exception e) { + Log.i("Starting " + info.packageName + " " + info.versionCode + " a.k.a " + info.versionName + "…"); + } catch (final NameNotFoundException e) { Log.i("No info."); } try { if (!Settings.isHelpShown()) { - RelativeLayout helper = (RelativeLayout) findViewById(R.id.helper); + final RelativeLayout helper = (RelativeLayout) findViewById(R.id.helper); if (helper != null) { helper.setVisibility(View.VISIBLE); helper.setClickable(true); @@ -249,8 +221,6 @@ public class cgeo extends AbstractActivity { // nothing } - locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); - init(); } @@ -264,12 +234,9 @@ public class cgeo extends AbstractActivity { @Override public void onResume() { super.onResume(); - - gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - locationManager.addGpsStatusListener(gpsListener); - + app.addGeoObserver(locationUpdater); + app.addGeoObserver(satellitesHandler); updateUserInfoHandler.sendEmptyMessage(-1); - init(); } @@ -278,34 +245,20 @@ public class cgeo extends AbstractActivity { initialized = false; app.showLoginToast = true; - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { initialized = false; - - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { initialized = false; - - locationManager.removeGpsStatusListener(gpsListener); - - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(locationUpdater); + app.deleteGeoObserver(satellitesHandler); super.onPause(); } @@ -405,11 +358,8 @@ public class cgeo extends AbstractActivity { // context menu for offline button if (v.getId() == R.id.search_offline) { - List<StoredList> cacheLists = app.getLists(); - int listCount = cacheLists.size(); menu.setHeaderTitle(res.getString(R.string.list_title)); - for (int i = 0; i < listCount; i++) { - StoredList list = cacheLists.get(i); + for (final StoredList list : app.getLists()) { menu.add(Menu.NONE, MENU_OPEN_LIST + list.id, Menu.NONE, list.getTitleAndCount()); } return; @@ -458,23 +408,22 @@ public class cgeo extends AbstractActivity { } @Override - public boolean onContextItemSelected(MenuItem item) { + public boolean onContextItemSelected(final MenuItem item) { final int id = item.getItemId(); + if (id < 0) { + return false; + } if (id == 0) { Settings.setCacheType(CacheType.ALL); setFilterTitle(); - - return true; } else if (id > MENU_OPEN_LIST) { - int listId = id - MENU_OPEN_LIST; - Settings.saveLastList(listId); + Settings.saveLastList(id - MENU_OPEN_LIST); cgeocaches.startActivityOffline(this); - return true; - } else if (id > 0) { + } else { final String itemTitle = item.getTitle().toString(); CacheType cacheType = CacheType.ALL; - for (CacheType ct : CacheType.values()) { + for (final CacheType ct : CacheType.values()) { if (ct.getL10n().equalsIgnoreCase(itemTitle)) { cacheType = ct; break; @@ -482,11 +431,9 @@ public class cgeo extends AbstractActivity { } Settings.setCacheType(cacheType); setFilterTitle(); - - return true; } - return false; + return true; } private void setFilterTitle() { @@ -501,14 +448,6 @@ public class cgeo extends AbstractActivity { return; } - //TODO This is ugly fix for #486 bug should be reported to library - if (Thread.currentThread().getContextClassLoader() == null) - { - Thread.currentThread().setContextClassLoader(new ClassLoader() { - }); - StringUtils.isNotBlank("haha"); - } - initialized = true; Settings.setLanguage(Settings.isUseEnglish()); @@ -518,10 +457,6 @@ public class cgeo extends AbstractActivity { (new firstLogin()).start(); } - if (geo == null) { - geo = app.startGeo(new UpdateLocation()); - } - final View findOnMap = findViewById(R.id.map); findOnMap.setClickable(true); findOnMap.setOnClickListener(new OnClickListener() { @@ -601,21 +536,16 @@ public class cgeo extends AbstractActivity { .show(); } - private class UpdateLocation implements UpdateLocationCallback { - - private final View nearestView = findViewById(R.id.nearest); - private final TextView navType = (TextView) findViewById(R.id.nav_type); - private final TextView navAccuracy = (TextView) findViewById(R.id.nav_accuracy); - private final TextView navLocation = (TextView) findViewById(R.id.nav_location); + private class UpdateLocation extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + public void updateLocation(final IGeoData geo) { + final View nearestView = findViewById(R.id.nearest); + final TextView navType = (TextView) findViewById(R.id.nav_type); + final TextView navAccuracy = (TextView) findViewById(R.id.nav_accuracy); + final TextView navLocation = (TextView) findViewById(R.id.nav_location); try { - if (geo.coordsNow != null) { + if (geo.getCoords() != null) { if (!nearestView.isClickable()) { nearestView.setFocusable(true); nearestView.setClickable(true); @@ -627,20 +557,14 @@ public class cgeo extends AbstractActivity { nearestView.setBackgroundResource(R.drawable.main_nearby); } - if (!gpsEnabled) { - satellitesHandler.noGps(); - } else { - satellitesHandler.satellites(geo.satellitesFixed, geo.satellitesVisible); - } - - navType.setText(res.getString(geo.locationProvider.resourceId)); + navType.setText(res.getString(geo.getLocationProvider().resourceId)); - if (geo.accuracyNow >= 0) { - int speed = Math.round(geo.speedNow) * 60 * 60 / 1000; + if (geo.getAccuracy() >= 0) { + int speed = Math.round(geo.getSpeed()) * 60 * 60 / 1000; if (Settings.isUseMetricUnits()) { - navAccuracy.setText("±" + Math.round(geo.accuracyNow) + " m" + Formatter.SEPARATOR + speed + " km/h"); + navAccuracy.setText("±" + Math.round(geo.getAccuracy()) + " m" + Formatter.SEPARATOR + speed + " km/h"); } else { - navAccuracy.setText("±" + Math.round(geo.accuracyNow * IConversion.METERS_TO_FEET) + " ft" + Formatter.SEPARATOR + speed / IConversion.MILES_TO_KILOMETER + " mph"); + navAccuracy.setText("±" + Math.round(geo.getAccuracy() * IConversion.METERS_TO_FEET) + " ft" + Formatter.SEPARATOR + speed / IConversion.MILES_TO_KILOMETER + " mph"); } } else { navAccuracy.setText(null); @@ -650,15 +574,15 @@ public class cgeo extends AbstractActivity { if (addCoords == null) { navLocation.setText(res.getString(R.string.loc_no_addr)); } - if (addCoords == null || (geo.coordsNow.distanceTo(addCoords) > 0.5 && !addressObtaining)) { + if (addCoords == null || (geo.getCoords().distanceTo(addCoords) > 0.5 && !addressObtaining)) { (new ObtainAddressThread()).start(); } } else { - if (geo.altitudeNow != null) { - final String humanAlt = HumanDistance.getHumanDistance(geo.altitudeNow.floatValue() / 1000); - navLocation.setText(geo.coordsNow + " | " + humanAlt); + if (geo.getAltitude() != 0.0) { + final String humanAlt = HumanDistance.getHumanDistance((float) geo.getAltitude() / 1000); + navLocation.setText(geo.getCoords() + " | " + humanAlt); } else { - navLocation.setText(geo.coordsNow.toString()); + navLocation.setText(geo.getCoords().toString()); } } } else { @@ -692,12 +616,12 @@ public class cgeo extends AbstractActivity { * unused here but needed since this method is referenced from XML layout */ public void cgeoFindNearest(View v) { - if (geo == null || geo.coordsNow == null) { + if (app.currentGeo().getCoords() == null) { return; } findViewById(R.id.nearest).setPressed(true); - cgeocaches.startActivityNearest(this, geo.coordsNow); + cgeocaches.startActivityNearest(this, app.currentGeo().getCoords()); } /** @@ -859,9 +783,6 @@ public class cgeo extends AbstractActivity { @Override public void run() { - if (geo == null) { - return; - } if (addressObtaining) { return; } @@ -869,8 +790,8 @@ public class cgeo extends AbstractActivity { try { final Geocoder geocoder = new Geocoder(cgeo.this, Locale.getDefault()); - - addresses = geocoder.getFromLocation(geo.coordsNow.getLatitude(), geo.coordsNow.getLongitude(), 1); + final Geopoint coords = app.currentGeo().getCoords(); + addresses = geocoder.getFromLocation(coords.getLatitude(), coords.getLongitude(), 1); } catch (Exception e) { Log.i("Failed to obtain address"); } diff --git a/main/src/cgeo/geocaching/cgeoabout.java b/main/src/cgeo/geocaching/cgeoabout.java index 0c812f0..f112539 100644 --- a/main/src/cgeo/geocaching/cgeoabout.java +++ b/main/src/cgeo/geocaching/cgeoabout.java @@ -5,7 +5,6 @@ import cgeo.geocaching.utils.Log; import android.content.Intent; import android.content.pm.PackageInfo; -import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.text.method.LinkMovementMethod; @@ -27,13 +26,9 @@ public class cgeoabout extends AbstractActivity { private void init() { try { - PackageManager manager = this.getPackageManager(); - PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); + final PackageInfo info = getPackageManager().getPackageInfo(this.getPackageName(), 0); setTitle(res.getString(R.string.about) + " (ver. " + info.versionName + ")"); - - manager = null; - ((TextView) findViewById(R.id.contributors)).setMovementMethod(LinkMovementMethod.getInstance()); ((TextView) findViewById(R.id.changelog)).setMovementMethod(LinkMovementMethod.getInstance()); } catch (Exception e) { diff --git a/main/src/cgeo/geocaching/cgeoadvsearch.java b/main/src/cgeo/geocaching/cgeoadvsearch.java index 3183273..6eda1f9 100644 --- a/main/src/cgeo/geocaching/cgeoadvsearch.java +++ b/main/src/cgeo/geocaching/cgeoadvsearch.java @@ -6,6 +6,7 @@ import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.utils.BaseUtils; import cgeo.geocaching.utils.EditUtils; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -23,13 +24,11 @@ import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; -public class cgeoadvsearch extends AbstractActivity { +public class cgeoadvsearch extends AbstractActivity implements IObserver<IGeoData> { public static final String EXTRAS_KEYWORDSEARCH = "keywordsearch"; private static final int MENU_SEARCH_OWN_CACHES = 1; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private EditText latEdit = null; private EditText lonEdit = null; @@ -78,34 +77,13 @@ public class cgeoadvsearch extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(this); init(); } @Override - public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - - super.onDestroy(); - } - - @Override - public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - - super.onStop(); - } - - @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -146,10 +124,6 @@ public class cgeoadvsearch extends AbstractActivity { private void init() { Settings.getLogin(); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - ((Button) findViewById(R.id.buttonLatitude)).setOnClickListener(new findByCoordsAction()); ((Button) findViewById(R.id.buttonLongitude)).setOnClickListener(new findByCoordsAction()); @@ -237,33 +211,26 @@ public class cgeoadvsearch extends AbstractActivity { displayTrackable.setOnClickListener(new findTrackableListener()); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; + @Override + public void update(final IGeoData geo) { + try { + if (latEdit == null) { + latEdit = (EditText) findViewById(R.id.latitude); + } + if (lonEdit == null) { + lonEdit = (EditText) findViewById(R.id.longitude); } - try { - if (latEdit == null) { - latEdit = (EditText) findViewById(R.id.latitude); + if (geo.getCoords() != null) { + if (latEdit != null) { + latEdit.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); } - if (lonEdit == null) { - lonEdit = (EditText) findViewById(R.id.longitude); - } - - if (geo.coordsNow != null) { - if (latEdit != null) { - latEdit.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - } - if (lonEdit != null) { - lonEdit.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } + if (lonEdit != null) { + lonEdit.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); } - } catch (Exception e) { - Log.w("Failed to update location."); } + } catch (Exception e) { + Log.w("Failed to update location."); } } @@ -271,7 +238,7 @@ public class cgeoadvsearch extends AbstractActivity { @Override public void onClick(View arg0) { - cgeocoords coordsDialog = new cgeocoords(cgeoadvsearch.this, null, null, geo); + cgeocoords coordsDialog = new cgeocoords(cgeoadvsearch.this, null, null, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -298,9 +265,10 @@ public class cgeoadvsearch extends AbstractActivity { final String lonText = lonView.getText().toString(); if (StringUtils.isEmpty(latText) || StringUtils.isEmpty(lonText)) { - if (geo.coordsNow != null) { - latView.setText(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE)); - lonView.setText(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE)); + final IGeoData geo = app.currentGeo(); + if (geo.getCoords() != null) { + latView.setText(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE)); + lonView.setText(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE)); } } else { try { diff --git a/main/src/cgeo/geocaching/cgeoapplication.java b/main/src/cgeo/geocaching/cgeoapplication.java index 2b10c16..e1e67e4 100644 --- a/main/src/cgeo/geocaching/cgeoapplication.java +++ b/main/src/cgeo/geocaching/cgeoapplication.java @@ -8,6 +8,7 @@ import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag; import cgeo.geocaching.enumerations.LogType; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.Viewport; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -15,7 +16,6 @@ import org.apache.commons.lang3.StringUtils; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; -import android.content.Context; import android.content.res.Resources; import android.os.Handler; import android.os.Message; @@ -33,11 +33,8 @@ public class cgeoapplication extends Application { private cgData storage = null; private String action = null; - private Geopoint lastCoords = null; - private cgGeo geo = null; - private boolean geoInUse = false; - private cgDirection dir = null; - private boolean dirInUse = false; + private volatile GeoDataProvider geo; + private volatile DirectionProvider dir; public boolean firstRun = true; // c:geo is just launched public boolean showLoginToast = true; //login toast shown just once. private boolean databaseCleaned = false; // database was cleaned @@ -63,9 +60,6 @@ public class cgeoapplication extends Application { public void onTerminate() { Log.d("Terminating c:geo..."); - cleanGeo(); - cleanDir(); - if (storage != null) { storage.clean(); storage.closeDb(); @@ -114,107 +108,50 @@ public class cgeoapplication extends Application { restoreThread.start(); } - public void cleanGeo() { - if (geo != null) { - geo.closeGeo(); - geo = null; - } + public void addGeoObserver(final IObserver<? super IGeoData> observer) { + currentGeoObject().addObserver(observer); } - public void cleanDir() { - if (dir != null) { - dir.closeDir(); - dir = null; - } + public void deleteGeoObserver(final IObserver<? super IGeoData> observer) { + currentGeoObject().deleteObserver(observer); } - public boolean storageStatus() { - return storage.status(); - } - - public cgGeo startGeo(UpdateLocationCallback geoUpdate) { + private GeoDataProvider currentGeoObject() { if (geo == null) { - geo = new cgGeo(); - Log.i("Location service started"); + synchronized(this) { + if (geo == null) { + geo = new GeoDataProvider(this); + } + } } - - geo.replaceUpdate(geoUpdate); - geoInUse = true; - return geo; } - public float getSpeedFromGeo() { - return geo != null ? geo.speedNow : 0f; + public IGeoData currentGeo() { + return currentGeoObject().getMemory(); } - public cgGeo removeGeo() { - if (geo != null) { - geo.replaceUpdate(null); - } - geoInUse = false; - - (new removeGeoThread()).start(); - - return null; + public void addDirectionObserver(final IObserver<? super Float> observer) { + currentDirObject().addObserver(observer); } - private class removeGeoThread extends Thread { - - @Override - public void run() { - try { - sleep(2500); - } catch (Exception e) { - // nothing - } - - if (!geoInUse && geo != null) { - cleanGeo(); - Log.i("Location service stopped"); - } - } + public void deleteDirectionObserver(final IObserver<? super Float> observer) { + currentDirObject().deleteObserver(observer); } - public cgDirection startDir(Context context, UpdateDirectionCallback dirUpdate) { + private DirectionProvider currentDirObject() { if (dir == null) { - dir = new cgDirection(context, dirUpdate); - - Log.i("Direction service started"); + synchronized(this) { + if (dir == null) { + dir = new DirectionProvider(this); + } + } } - - dir.replaceUpdate(dirUpdate); - dirInUse = true; - return dir; } - public cgDirection removeDir() { - if (dir != null) { - dir.replaceUpdate(null); - } - dirInUse = false; - - (new removeDirThread()).start(); - - return null; - } - - private class removeDirThread extends Thread { - - @Override - public void run() { - try { - sleep(2500); - } catch (Exception e) { - // nothing - } - - if (!dirInUse && dir != null) { - cleanDir(); - Log.i("Direction service stopped"); - } - } + public boolean storageStatus() { + return storage.status(); } public void cleanDatabase(boolean more) { @@ -264,10 +201,7 @@ public class cgeoapplication extends Application { return null; } - cgTrackable trackable = null; - trackable = storage.loadTrackable(geocode); - - return trackable; + return storage.loadTrackable(geocode); } /** {@link cgData#allDetailedThere()} */ @@ -304,24 +238,24 @@ public class cgeoapplication extends Application { return new SearchResult(geocodes, getAllHistoricCachesCount()); } - /** {@link cgData#loadCachedInViewport(long, long, long, long, CacheType)} */ + /** {@link cgData#loadCachedInViewport(Viewport, CacheType)} */ public SearchResult getCachedInViewport(final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = storage.loadCachedInViewport(viewport, cacheType); return new SearchResult(geocodes); } - /** {@link cgData#loadStoredInViewport(long, long, long, long, CacheType)} */ + /** {@link cgData#loadStoredInViewport(Viewport, CacheType)} */ public SearchResult getStoredInViewport(final Viewport viewport, final CacheType cacheType) { final Set<String> geocodes = storage.loadStoredInViewport(viewport, cacheType); return new SearchResult(geocodes); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, Integer)} */ + /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType) { return storage.getAllStoredCachesCount(detailedOnly, cacheType, 0); } - /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, Integer)} */ + /** {@link cgData#getAllStoredCachesCount(boolean, CacheType, int)} */ public int getAllStoredCachesCount(final boolean detailedOnly, final CacheType cacheType, final Integer list) { return storage.getAllStoredCachesCount(detailedOnly, cacheType, list); } @@ -407,14 +341,6 @@ public class cgeoapplication extends Application { return StringUtils.defaultString(action); } - public void setLastCoords(final Geopoint coords) { - lastCoords = coords; - } - - public Geopoint getLastCoords() { - return lastCoords; - } - /** {@link cgData#saveLogOffline(String, Date, LogType, String)} */ public boolean saveLogOffline(String geocode, Date date, LogType logtype, String log) { return storage.saveLogOffline(geocode, date, logtype, log); diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java index 76d04dc..b4caa89 100644 --- a/main/src/cgeo/geocaching/cgeocaches.java +++ b/main/src/cgeo/geocaching/cgeocaches.java @@ -37,6 +37,7 @@ import cgeo.geocaching.sorting.TerrainComparator; import cgeo.geocaching.sorting.VisitComparator; import cgeo.geocaching.sorting.VoteComparator; import cgeo.geocaching.ui.CacheListAdapter; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import cgeo.geocaching.utils.RunnableWithArgument; @@ -49,7 +50,6 @@ import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.os.Handler; @@ -74,7 +74,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -public class cgeocaches extends AbstractListActivity { +public class cgeocaches extends AbstractListActivity implements IObserver<Object> { private static final int MAX_LIST_ITEMS = 1000; private static final String EXTRAS_LIST_TYPE = "type"; @@ -107,7 +107,6 @@ public class cgeocaches extends AbstractListActivity { private static final int SUBMENU_MANAGE_LISTS = 55; private static final int SUBMENU_MANAGE_OFFLINE = 56; private static final int SUBMENU_SORT = 57; - private static final int SUBMENU_IMPORT = 59; private static final int SUBMENU_MANAGE_HISTORY = 60; private static final int MENU_SORT_DATE = 61; private static final int MENU_SORT_FINDS = 62; @@ -120,6 +119,7 @@ public class cgeocaches extends AbstractListActivity { private static final int MENU_FILTER = 74; private static final int MSG_DONE = -1; + private static final int MSG_RESTART_GEO_AND_DIR = -2; private static final int MSG_CANCEL = -99; private String action = null; @@ -137,17 +137,12 @@ public class cgeocaches extends AbstractListActivity { private TextView listFooterText = null; private Progress progress = new Progress(); private Float northHeading = 0f; - private cgGeo geo = null; - private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new UpdateLocation(); - private UpdateDirectionCallback dirUpdate = new UpdateDirection(); private String title = ""; private int detailTotal = 0; private int detailProgress = 0; private long detailProgressTime = 0L; private LoadDetailsThread threadDetails = null; private LoadFromWebThread threadWeb = null; - private DropDetailsThread threadR = null; private RemoveFromHistoryThread threadH = null; private int listId = StoredList.TEMPORARY_LIST_ID; private GeocodeComparator gcComparator = new GeocodeComparator(); @@ -200,7 +195,7 @@ public class cgeocaches extends AbstractListActivity { AlertDialog alert = dialog.create(); alert.show(); - } else if (app != null && search != null && search.getError() != null) { + } else if (search != null && search.getError() != null) { showToast(res.getString(R.string.err_download_fail) + ' ' + search.getError().getErrorString(res) + '.'); hideLoading(); @@ -210,8 +205,9 @@ public class cgeocaches extends AbstractListActivity { return; } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoords(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } } catch (Exception e) { @@ -277,8 +273,9 @@ public class cgeocaches extends AbstractListActivity { return; } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoords(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } } catch (Exception e) { @@ -322,6 +319,8 @@ public class cgeocaches extends AbstractListActivity { if (threadDetails != null) { threadDetails.kill(); } + } else if (msg.what == MSG_RESTART_GEO_AND_DIR) { + startGeoAndDir(); } else { if (cacheList != null && search != null) { final Set<cgCache> cacheListTmp = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB); @@ -333,8 +332,9 @@ public class cgeocaches extends AbstractListActivity { } } - if (geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoords(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); adapter.setActualHeading(northHeading); } @@ -363,12 +363,10 @@ public class cgeocaches extends AbstractListActivity { refreshCurrentList(); } else if (msg.what == -2) { progress.dismiss(); - startGeoAndDir(); showToast(res.getString(R.string.sendToCgeo_download_fail)); finish(); } else if (msg.what == -3) { progress.dismiss(); - startGeoAndDir(); showToast(res.getString(R.string.sendToCgeo_no_registration)); finish(); } else if (msg.what == MSG_CANCEL) { @@ -390,7 +388,6 @@ public class cgeocaches extends AbstractListActivity { Collections.sort(cacheList, gcComparator); } - startGeoAndDir(); progress.dismiss(); } } @@ -469,6 +466,13 @@ public class cgeocaches extends AbstractListActivity { super.onCreate(savedInstanceState); // init + if (CollectionUtils.isNotEmpty(cacheList)) { + setMoreCaches(); + } + + setTitle(title); + setAdapter(); + app.setAction(action); setTheme(); @@ -493,8 +497,6 @@ public class cgeocaches extends AbstractListActivity { } } - init(); - Thread threadPure; cgSearchThread thread; @@ -639,27 +641,18 @@ public class cgeocaches extends AbstractListActivity { } @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - - init(); - } - - @Override public void onResume() { super.onResume(); - init(); - - if (adapter != null && geo != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); - adapter.setActualHeading(northHeading); - } + startGeoAndDir(); if (adapter != null) { adapter.setSelectMode(false, true); - if (geo != null && geo.coordsNow != null) { - adapter.forceSort(geo.coordsNow); + final Geopoint coordsNow = app.currentGeo().getCoords(); + if (coordsNow != null) { + adapter.setActualCoordinates(coordsNow); + adapter.setActualHeading(northHeading); + adapter.forceSort(coordsNow); } } @@ -682,15 +675,11 @@ public class cgeocaches extends AbstractListActivity { adapter = null; } - removeGeoAndDir(); - super.onDestroy(); } @Override public void onStop() { - removeGeoAndDir(); - super.onStop(); } @@ -983,7 +972,7 @@ public class cgeocaches extends AbstractListActivity { return true; } - return CacheListAppFactory.onMenuItemSelected(item, geo, cacheList, this, search); + return CacheListAppFactory.onMenuItemSelected(item, app.currentGeo(), cacheList, this, search); } private void setComparator(MenuItem item, @@ -1050,8 +1039,7 @@ public class cgeocaches extends AbstractListActivity { final boolean moveAll = adapter.getChecked() == 0; if (moveAll) { selected = new ArrayList<cgCache>(cacheList); - } - else { + } else { selected = adapter.getCheckedCaches(); } app.moveToList(selected, newListId); @@ -1064,7 +1052,6 @@ public class cgeocaches extends AbstractListActivity { @Override public boolean onContextItemSelected(MenuItem item) { - final int id = item.getItemId(); ContextMenu.ContextMenuInfo info = item.getMenuInfo(); // restore menu info for sub menu items, see @@ -1081,64 +1068,62 @@ public class cgeocaches extends AbstractListActivity { Log.w("cgeocaches.onContextItemSelected: " + e.toString()); } - if (id == MENU_DEFAULT_NAVIGATION) { - final cgCache cache = getCacheFromAdapter(adapterInfo); - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); - return true; - } else if (id == MENU_NAVIGATION) { - final cgCache cache = getCacheFromAdapter(adapterInfo); - NavigationAppFactory.showNavigationMenu(geo, this, cache, null, null); - return true; - } else if (id == MENU_LOG_VISIT) { - getCacheFromAdapter(adapterInfo).logVisit(this); - return true; - } else if (id == MENU_CACHE_DETAILS) { - final Intent cachesIntent = new Intent(this, CacheDetailActivity.class); - final cgCache cache = getCacheFromAdapter(adapterInfo); - cachesIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); - cachesIntent.putExtra("name", cache.getName()); - startActivity(cachesIntent); + final cgCache cache = adapterInfo != null ? getCacheFromAdapter(adapterInfo) : null; - return true; - } else if (id == MENU_DROP_CACHE) { - getCacheFromAdapter(adapterInfo).drop(new Handler() { - @Override - public void handleMessage(Message msg) { - refreshCurrentList(); - } - }); - return true; - } else if (id == MENU_MOVE_TO_LIST) { - final cgCache cache = getCacheFromAdapter(adapterInfo); - new StoredList.UserInterface(this).promptForListSelection(R.string.cache_menu_move_list, new RunnableWithArgument<Integer>() { - - @Override - public void run(Integer newListId) { - app.moveToList(Collections.singletonList(cache), newListId); - adapter.resetChecks(); - refreshCurrentList(); - } - }); - return true; - } else if (id == MENU_STORE_CACHE) { - final cgCache cache = getCacheFromAdapter(adapterInfo); - //FIXME: this must use the same handler like in the CacheDetailActivity. Will be done by moving the handler into the store method. - cache.store(this, null); + // just in case the list got resorted while we are executing this code + if (cache == null) { return true; } - // we must remember the menu info for the sub menu, there is a bug - // in Android: - // https://code.google.com/p/android/issues/detail?id=7139 - lastMenuInfo = info; - - if (adapterInfo != null) { - // create a search for a single cache (as if in details view) - final cgCache cache = getCacheFromAdapter(adapterInfo); + final int id = item.getItemId(); + switch (id) { + case MENU_DEFAULT_NAVIGATION: + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); + break; + case MENU_NAVIGATION: + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); + break; + case MENU_LOG_VISIT: + cache.logVisit(this); + break; + case MENU_CACHE_DETAILS: + final Intent cachesIntent = new Intent(this, CacheDetailActivity.class); + cachesIntent.putExtra("geocode", cache.getGeocode().toUpperCase()); + cachesIntent.putExtra("name", cache.getName()); + startActivity(cachesIntent); + break; + case MENU_DROP_CACHE: + cache.drop(new Handler() { + @Override + public void handleMessage(Message msg) { + refreshCurrentList(); + } + }); + break; + case MENU_MOVE_TO_LIST: + new StoredList.UserInterface(this).promptForListSelection(R.string.cache_menu_move_list, new RunnableWithArgument<Integer>() { - int logType = id - MENU_LOG_VISIT_OFFLINE; - cache.logOffline(this, LogType.getById(logType)); + @Override + public void run(Integer newListId) { + app.moveToList(Collections.singletonList(cache), newListId); + adapter.resetChecks(); + refreshCurrentList(); + } + }); + break; + case MENU_STORE_CACHE: + //FIXME: this must use the same handler like in the CacheDetailActivity. Will be done by moving the handler into the store method. + cache.store(this, null); + break; + default: + // we must remember the menu info for the sub menu, there is a bug + // in Android: + // https://code.google.com/p/android/issues/detail?id=7139 + lastMenuInfo = info; + // create a search for a single cache (as if in details view) + cache.logOffline(this, LogType.getById(id - MENU_LOG_VISIT_OFFLINE)); } + return true; } @@ -1210,13 +1195,6 @@ public class cgeocaches extends AbstractListActivity { adapter.notifyDataSetChanged(); } adapter.reFilter(); - - if (geo != null) { - adapter.setActualCoordinates(geo.coordsNow); - } - if (dir != null) { - adapter.setActualHeading(dir.directionNow); - } } private void setLoadingCaches() { @@ -1260,41 +1238,18 @@ public class cgeocaches extends AbstractListActivity { listFooter.setClickable(enableMore); } - private void init() { - startGeoAndDir(); - - if (CollectionUtils.isNotEmpty(cacheList)) { - setMoreCaches(); - } - - setTitle(title); - setAdapter(); - - if (geo != null) { - geoUpdate.updateLocation(geo); - } - if (dir != null) { - dirUpdate.updateDirection(dir); - } - } - - // sensor & geolocation manager + // Sensor & geolocation manager. This must be called from the UI thread as it may + // cause the system listeners to start if nobody else required them before. private void startGeoAndDir() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isLiveList() && Settings.isUseCompass() && dir == null) { - dir = app.startDir(this, dirUpdate); + app.addGeoObserver(this); + if (Settings.isLiveList() && Settings.isUseCompass()) { + app.addDirectionObserver(this); } } private void removeGeoAndDir() { - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } + app.deleteGeoObserver(this); + app.deleteDirectionObserver(this); } private void importGpx() { @@ -1437,56 +1392,49 @@ public class cgeocaches extends AbstractListActivity { public void dropSelected() { progress.show(this, null, res.getString(R.string.caches_drop_progress), true, dropDetailsHandler.obtainMessage(MSG_CANCEL)); + new DropDetailsThread(dropDetailsHandler).start(); + } - threadR = new DropDetailsThread(dropDetailsHandler); - threadR.start(); + @Override + public void update(final Object data) { + if (data instanceof IGeoData) { + updateGeoData((IGeoData) data); + } else { + updateDirection((Float) data); + } } - private class UpdateLocation implements UpdateLocationCallback { + private void updateGeoData(final IGeoData geo) { + if (adapter == null) { + return; + } - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - if (adapter == null) { - return; + try { + if (cacheList != null && geo.getCoords() != null) { + adapter.setActualCoordinates(geo.getCoords()); } - try { - if (cacheList != null && geo.coordsNow != null) { - adapter.setActualCoordinates(geo.coordsNow); + if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h + if (!Settings.isUseCompass()) { + adapter.setActualHeading(geo.getBearing()); } - - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - if (!Settings.isUseCompass()) { - adapter.setActualHeading(geo.bearingNow); - } - if (northHeading != null) { - adapter.setActualHeading(northHeading); - } + if (northHeading != null) { + adapter.setActualHeading(northHeading); } - } catch (Exception e) { - Log.w("Failed to UpdateLocation location."); } + } catch (Exception e) { + Log.w("Failed to UpdateLocation location."); } } - private class UpdateDirection implements UpdateDirectionCallback { - - @Override - public void updateDirection(cgDirection dir) { - if (!Settings.isLiveList()) { - return; - } - if (dir == null || dir.directionNow == null) { - return; - } + public void updateDirection(final float direction) { + if (!Settings.isLiveList()) { + return; + } - northHeading = dir.directionNow; - if (northHeading != null && adapter != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h) { - adapter.setActualHeading(northHeading); - } + northHeading = DirectionProvider.getDirectionNow(this, direction); + if (northHeading != null && adapter != null && (app.currentGeo().getSpeed() <= 5)) { // use compass when speed is lower than 18 km/h) { + adapter.setActualHeading(northHeading); } } @@ -1636,14 +1584,7 @@ public class cgeocaches extends AbstractListActivity { @Override public void run() { - Map<String, String> params = new HashMap<String, String>(); - params.put("username", username); - if (cacheType != null) { - params.put("cacheType", cacheType.id); - } - search = GCParser.searchByOwner(this, username, cacheType, Settings.isShowCaptcha()); - handler.sendMessage(Message.obtain()); } } @@ -1725,6 +1666,7 @@ public class cgeocaches extends AbstractListActivity { } cacheListTemp.clear(); + handler.sendEmptyMessage(MSG_RESTART_GEO_AND_DIR); handler.sendEmptyMessage(MSG_DONE); } } @@ -1810,6 +1752,8 @@ public class cgeocaches extends AbstractListActivity { } handler.sendEmptyMessage(ret); + + startGeoAndDir(); } } @@ -1837,6 +1781,8 @@ public class cgeocaches extends AbstractListActivity { removeGeoAndDir(); app.markDropped(selected); handler.sendEmptyMessage(MSG_DONE); + + startGeoAndDir(); } } diff --git a/main/src/cgeo/geocaching/cgeocoords.java b/main/src/cgeo/geocaching/cgeocoords.java index 57fd144..0ad2e81 100644 --- a/main/src/cgeo/geocaching/cgeocoords.java +++ b/main/src/cgeo/geocaching/cgeocoords.java @@ -31,7 +31,7 @@ import android.widget.TextView; public class cgeocoords extends Dialog { final private AbstractActivity context; - final private cgGeo geo; + final private IGeoData geo; final private cgCache cache; private Geopoint gp; @@ -46,7 +46,7 @@ public class cgeocoords extends Dialog { private coordInputFormatEnum currentFormat = null; - public cgeocoords(final AbstractActivity context, final cgCache cache, final Geopoint gp, final cgGeo geo) { + public cgeocoords(final AbstractActivity context, final cgCache cache, final Geopoint gp, final IGeoData geo) { super(context); this.context = context; this.geo = geo; @@ -54,8 +54,8 @@ public class cgeocoords extends Dialog { if (gp != null) { this.gp = gp; - } else if (geo != null && geo.coordsNow != null) { - this.gp = geo.coordsNow; + } else if (geo != null && geo.getCoords() != null) { + this.gp = geo.getCoords(); } else { this.gp = new Geopoint(0.0, 0.0); } @@ -413,8 +413,8 @@ public class cgeocoords extends Dialog { // Start new format with an acceptable value: either the current one // entered by the user, else our current coordinates, else (0,0). if (!calc(false)) { - if (geo != null && geo.coordsNow != null) { - gp = geo.coordsNow; + if (geo != null && geo.getCoords() != null) { + gp = geo.getCoords(); } else { gp = new Geopoint(0.0, 0.0); } @@ -436,12 +436,12 @@ public class cgeocoords extends Dialog { @Override public void onClick(View v) { - if (geo == null || geo.coordsNow == null) { + if (geo == null || geo.getCoords() == null) { context.showToast(context.getResources().getString(R.string.err_point_unknown_position)); return; } - gp = geo.coordsNow; + gp = geo.getCoords(); updateGUI(); } } diff --git a/main/src/cgeo/geocaching/cgeoimages.java b/main/src/cgeo/geocaching/cgeoimages.java index 10b8b21..7145d59 100644 --- a/main/src/cgeo/geocaching/cgeoimages.java +++ b/main/src/cgeo/geocaching/cgeoimages.java @@ -60,14 +60,14 @@ public class cgeoimages extends AbstractActivity { private void loadImages(final List<cgImage> images, final int progressMessage, final boolean offline) { count = images.size(); - progressDialog = new ProgressDialog(cgeoimages.this); + progressDialog = new ProgressDialog(this); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(res.getString(progressMessage)); progressDialog.setCancelable(true); progressDialog.setMax(count); progressDialog.show(); - LinearLayout rowView = null; + LinearLayout rowView; for (final cgImage img : images) { rowView = (LinearLayout) inflater.inflate(R.layout.cache_image_item, null); diff --git a/main/src/cgeo/geocaching/cgeoinit.java b/main/src/cgeo/geocaching/cgeoinit.java index 08f2204..a5f1641 100644 --- a/main/src/cgeo/geocaching/cgeoinit.java +++ b/main/src/cgeo/geocaching/cgeoinit.java @@ -175,7 +175,7 @@ public class cgeoinit extends AbstractActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == 0) { - boolean status = false; + boolean status; ((EditText) findViewById(R.id.username)).setText(""); ((EditText) findViewById(R.id.password)).setText(""); diff --git a/main/src/cgeo/geocaching/cgeonavigate.java b/main/src/cgeo/geocaching/cgeonavigate.java index f7bc379..64af2df 100644 --- a/main/src/cgeo/geocaching/cgeonavigate.java +++ b/main/src/cgeo/geocaching/cgeonavigate.java @@ -7,6 +7,7 @@ import cgeo.geocaching.geopoint.IConversion; import cgeo.geocaching.maps.CGeoMap; import cgeo.geocaching.ui.CompassView; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.PeriodicHandler; import org.apache.commons.lang3.StringUtils; @@ -24,7 +25,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -public class cgeonavigate extends AbstractActivity { +public class cgeonavigate extends AbstractActivity implements IObserver<Object> { private static final String EXTRAS_COORDS = "coords"; private static final String EXTRAS_NAME = "name"; @@ -33,10 +34,6 @@ public class cgeonavigate extends AbstractActivity { private static final int MENU_MAP = 0; private static final int MENU_SWITCH_COMPASS_GPS = 1; private PowerManager pm = null; - private cgGeo geo = null; - private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new update(); - private UpdateDirectionCallback dirUpdate = new UpdateDirection(); private Geopoint dstCoords = null; private float cacheHeading = 0; private Float northHeading = null; @@ -73,14 +70,6 @@ public class cgeonavigate extends AbstractActivity { setContentView(R.layout.navigate); setTitle(res.getString(R.string.compass_title)); - // sensor & geolocation manager - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(this, dirUpdate); - } - // get parameters Bundle extras = getIntent().getExtras(); if (extras != null) { @@ -110,13 +99,6 @@ public class cgeonavigate extends AbstractActivity { setTitle(); setDestCoords(); - if (geo != null) { - geoUpdate.updateLocation(geo); - } - if (dir != null) { - dirUpdate.updateDirection(dir); - } - // get textviews once compassView = (CompassView) findViewById(R.id.rose); } @@ -134,11 +116,9 @@ public class cgeonavigate extends AbstractActivity { setGo4CacheAction(); // sensor & geolocation manager - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(this, dirUpdate); + app.addGeoObserver(this); + if (Settings.isUseCompass()) { + app.addDirectionObserver(this); } // keep backlight on @@ -157,42 +137,20 @@ public class cgeonavigate extends AbstractActivity { @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - if (dir != null) { - dir = app.removeDir(); - } - updaterHandler.stop(); - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - if (dir != null) { - dir = app.removeDir(); - } - + app.deleteGeoObserver(this); + app.deleteDirectionObserver(this); super.onPause(); } @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - if (dir != null) { - dir = app.removeDir(); - } - compassView.destroyDrawingCache(); - compassView = null; - super.onDestroy(); } @@ -232,13 +190,9 @@ public class cgeonavigate extends AbstractActivity { Settings.setUseCompass(!oldSetting); invalidateOptionsMenuCompatible(); if (oldSetting) { - if (dir != null) { - dir = app.removeDir(); - } + app.deleteDirectionObserver(this); } else { - if (dir == null) { - dir = app.startDir(this, dirUpdate); - } + app.addDirectionObserver(this); } } else if (id == 2) { Intent pointIntent = new Intent(this, cgeopoint.class); @@ -253,7 +207,7 @@ public class cgeonavigate extends AbstractActivity { dstCoords = coordinate.getCoords(); setTitle(); setDestCoords(); - updateDistanceInfo(); + updateDistanceInfo(app.currentGeo()); Log.d("destination set: " + title + " (" + dstCoords + ")"); return true; @@ -278,8 +232,8 @@ public class cgeonavigate extends AbstractActivity { ((TextView) findViewById(R.id.destination)).setText(dstCoords.toString()); } - private void updateDistanceInfo() { - if (geo == null || geo.coordsNow == null || dstCoords == null) { + private void updateDistanceInfo(final IGeoData geo) { + if (geo.getCoords() == null || dstCoords == null) { return; } @@ -290,83 +244,76 @@ public class cgeonavigate extends AbstractActivity { headingView = (TextView) findViewById(R.id.heading); } - cacheHeading = geo.coordsNow.bearingTo(dstCoords); - distanceView.setText(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(dstCoords))); + cacheHeading = geo.getCoords().bearingTo(dstCoords); + distanceView.setText(HumanDistance.getHumanDistance(geo.getCoords().distanceTo(dstCoords))); headingView.setText(Math.round(cacheHeading) + "°"); } - private class update implements UpdateLocationCallback { + @Override + public void update(final Object data) { + if (data instanceof IGeoData) { + updateGeoData((IGeoData) data); + } else { + updateDirection((Float) data); + } + } - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; + private void updateGeoData(final IGeoData geo) { + try { + if (navType == null || navLocation == null || navAccuracy == null) { + navType = (TextView) findViewById(R.id.nav_type); + navAccuracy = (TextView) findViewById(R.id.nav_accuracy); + navSatellites = (TextView) findViewById(R.id.nav_satellites); + navLocation = (TextView) findViewById(R.id.nav_location); } - try { - if (navType == null || navLocation == null || navAccuracy == null) { - navType = (TextView) findViewById(R.id.nav_type); - navAccuracy = (TextView) findViewById(R.id.nav_accuracy); - navSatellites = (TextView) findViewById(R.id.nav_satellites); - navLocation = (TextView) findViewById(R.id.nav_location); + if (geo.getCoords() != null) { + String satellites; + if (geo.getSatellitesFixed() > 0) { + satellites = res.getString(R.string.loc_sat) + ": " + geo.getSatellitesFixed() + "/" + geo.getSatellitesVisible(); + } else if (geo.getSatellitesVisible() >= 0) { + satellites = res.getString(R.string.loc_sat) + ": 0/" + geo.getSatellitesVisible(); + } else { + satellites = ""; } + navSatellites.setText(satellites); + navType.setText(res.getString(geo.getLocationProvider().resourceId)); - if (geo.coordsNow != null) { - String satellites = null; - if (geo.satellitesFixed > 0) { - satellites = res.getString(R.string.loc_sat) + ": " + geo.satellitesFixed + "/" + geo.satellitesVisible; - } else if (geo.satellitesVisible >= 0) { - satellites = res.getString(R.string.loc_sat) + ": 0/" + geo.satellitesVisible; + if (geo.getAccuracy() >= 0) { + if (Settings.isUseMetricUnits()) { + navAccuracy.setText("±" + Math.round(geo.getAccuracy()) + " m"); } else { - satellites = ""; + navAccuracy.setText("±" + Math.round(geo.getAccuracy() * IConversion.METERS_TO_FEET) + " ft"); } - navSatellites.setText(satellites); - navType.setText(res.getString(geo.locationProvider.resourceId)); - - if (geo.accuracyNow >= 0) { - if (Settings.isUseMetricUnits()) { - navAccuracy.setText("±" + Math.round(geo.accuracyNow) + " m"); - } else { - navAccuracy.setText("±" + Math.round(geo.accuracyNow * IConversion.METERS_TO_FEET) + " ft"); - } - } else { - navAccuracy.setText(null); - } - - if (geo.altitudeNow != null) { - final String humanAlt = HumanDistance.getHumanDistance(geo.altitudeNow.floatValue() / 1000); - navLocation.setText(geo.coordsNow + " | " + humanAlt); - } else { - navLocation.setText(geo.coordsNow.toString()); - } - - updateDistanceInfo(); } else { - navType.setText(null); navAccuracy.setText(null); - navLocation.setText(res.getString(R.string.loc_trying)); } - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - northHeading = geo.bearingNow; + if (geo.getAltitude() != 0.0f) { + final String humanAlt = HumanDistance.getHumanDistance((float) geo.getAltitude() / 1000); + navLocation.setText(geo.getCoords() + " | " + humanAlt); + } else { + navLocation.setText(geo.getCoords().toString()); } - } catch (Exception e) { - Log.w("Failed to update location."); - } - } - } - - private class UpdateDirection implements UpdateDirectionCallback { - @Override - public void updateDirection(cgDirection dir) { - if (dir == null || dir.directionNow == null) { - return; + updateDistanceInfo(geo); + } else { + navType.setText(null); + navAccuracy.setText(null); + navLocation.setText(res.getString(R.string.loc_trying)); } - if (geo == null || geo.speedNow <= 5) { // use compass when speed is lower than 18 km/h - northHeading = dir.directionNow; + if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h + northHeading = geo.getBearing(); } + } catch (Exception e) { + Log.w("Failed to LocationUpdater location."); + } + } + + private void updateDirection(final float direction) { + if (app.currentGeo().getSpeed() <= 5) { // use compass when speed is lower than 18 km/h + northHeading = DirectionProvider.getDirectionNow(this, direction); } } diff --git a/main/src/cgeo/geocaching/cgeopoint.java b/main/src/cgeo/geocaching/cgeopoint.java index a7402be..01173b3 100644 --- a/main/src/cgeo/geocaching/cgeopoint.java +++ b/main/src/cgeo/geocaching/cgeopoint.java @@ -7,6 +7,7 @@ import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.ui.Formatter; import cgeo.geocaching.utils.Log; +import cgeo.geocaching.utils.IObserver; import org.apache.commons.lang3.StringUtils; @@ -34,7 +35,7 @@ import android.widget.TextView; import java.util.List; -public class cgeopoint extends AbstractActivity { +public class cgeopoint extends AbstractActivity implements IObserver<IGeoData> { private static final int MENU_DEFAULT_NAVIGATION = 2; private static final int MENU_NAVIGATE = 0; private static final int MENU_CACHES_AROUND = 5; @@ -84,8 +85,6 @@ public class cgeopoint extends AbstractActivity { } } - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private Button latButton = null; private Button lonButton = null; private boolean changed = false; @@ -146,7 +145,7 @@ public class cgeopoint extends AbstractActivity { historyListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, - ContextMenuInfo menuInfo) { + ContextMenuInfo menuInfo) { menu.add(Menu.NONE, CONTEXT_MENU_NAVIGATE, Menu.NONE, res.getString(R.string.cache_menu_navigate)); menu.add(Menu.NONE, CONTEXT_MENU_EDIT_WAYPOINT, Menu.NONE, R.string.waypoint_edit); menu.add(Menu.NONE, CONTEXT_MENU_DELETE_WAYPOINT, Menu.NONE, R.string.waypoint_delete); @@ -164,7 +163,7 @@ public class cgeopoint extends AbstractActivity { case CONTEXT_MENU_NAVIGATE: contextMenuItemPosition = position; if (destination instanceof Destination) { - NavigationAppFactory.showNavigationMenu(geo, this, null, null, ((Destination) destination).getCoords()); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, null, ((Destination) destination).getCoords()); return true; } break; @@ -224,42 +223,27 @@ public class cgeopoint extends AbstractActivity { @Override public void onResume() { super.onResume(); - + app.addGeoObserver(this); init(); } @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } private void init() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - latButton = (Button) findViewById(R.id.buttonLatitude); lonButton = (Button) findViewById(R.id.buttonLongitude); @@ -305,7 +289,7 @@ public class cgeopoint extends AbstractActivity { if (latButton.getText().length() > 0 && lonButton.getText().length() > 0) { gp = new Geopoint(latButton.getText().toString() + " " + lonButton.getText().toString()); } - cgeocoords coordsDialog = new cgeocoords(cgeopoint.this, null, gp, geo); + cgeocoords coordsDialog = new cgeocoords(cgeopoint.this, null, gp, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -400,7 +384,7 @@ public class cgeopoint extends AbstractActivity { return true; case MENU_NAVIGATE: - NavigationAppFactory.showNavigationMenu(geo, this, null, null, coords); + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, null, coords); return true; default: return false; @@ -468,7 +452,7 @@ public class cgeopoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, null, null, geopoint); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, null, geopoint); } private void cachesAround() { @@ -484,41 +468,35 @@ public class cgeopoint extends AbstractActivity { finish(); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - - try { - latButton.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - lonButton.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } catch (Exception e) { - Log.w("Failed to update location."); - } + @Override + public void update(final IGeoData geo) { + try { + latButton.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); + lonButton.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); + } catch (final Exception e) { + Log.w("Failed to update location."); } } private class currentListener implements View.OnClickListener { public void onClick(View arg0) { - if (geo == null || geo.coordsNow == null) { + final Geopoint coords = app.currentGeo().getCoords(); + if (coords == null) { showToast(res.getString(R.string.err_point_unknown_position)); return; } - latButton.setText(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE)); - lonButton.setText(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE)); + latButton.setText(coords.format(GeopointFormatter.Format.LAT_DECMINUTE)); + lonButton.setText(coords.format(GeopointFormatter.Format.LON_DECMINUTE)); changed = false; } } private Geopoint getDestination() { - Geopoint result = null; - Geopoint coords = null; + Geopoint result; + Geopoint coords; String bearingText = ((EditText) findViewById(R.id.bearing)).getText().toString(); // combine distance from EditText and distanceUnit saved from Spinner @@ -540,17 +518,17 @@ public class cgeopoint extends AbstractActivity { return null; } } else { - if (geo == null || geo.coordsNow == null) { + if (app.currentGeo().getCoords() == null) { showToast(res.getString(R.string.err_point_curr_position_unavailable)); return null; } - coords = geo.coordsNow; + coords = app.currentGeo().getCoords(); } if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { // bearing & distance - double bearing = 0; + double bearing; try { bearing = Double.parseDouble(bearingText); } catch (NumberFormatException e) { diff --git a/main/src/cgeo/geocaching/cgeopopup.java b/main/src/cgeo/geocaching/cgeopopup.java index 8981261..5284d4f 100644 --- a/main/src/cgeo/geocaching/cgeopopup.java +++ b/main/src/cgeo/geocaching/cgeopopup.java @@ -45,8 +45,7 @@ public class cgeopopup extends AbstractActivity { private LayoutInflater inflater = null; private String geocode = null; private cgCache cache = null; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); + private GeoObserver geoUpdate = new UpdateLocation(); private ProgressDialog storeDialog = null; private ProgressDialog dropDialog = null; private TextView cacheDistance = null; @@ -198,34 +197,31 @@ public class cgeopopup extends AbstractActivity { public boolean onOptionsItemSelected(MenuItem item) { final int menuItem = item.getItemId(); - if (menuItem == 2) { - navigateTo(); - return true; - } else if (menuItem == 3) { - NavigationAppFactory.showNavigationMenu(geo, this, cache, null, null); - return true; - } else if (menuItem == 5) { - cachesAround(); - return true; - } else if (menuItem == MENU_LOG_VISIT) { - cache.logVisit(this); - finish(); - return true; - } else if (menuItem == 7) { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.getGeocode()))); - return true; + switch (menuItem) { + case 2: + navigateTo(); + break; + case 3: + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, cache, null, null); + break; + case 5: + cachesAround(); + break; + case MENU_LOG_VISIT: + cache.logVisit(this); + finish(); + break; + case 7: + startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/seek/cache_details.aspx?wp=" + cache.getGeocode()))); + break; + default: + cache.logOffline(this, LogType.getById(menuItem - MENU_LOG_VISIT_OFFLINE)); } - int logType = menuItem - MENU_LOG_VISIT_OFFLINE; - cache.logOffline(this, LogType.getById(logType)); return true; } private void init() { - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - app.setAction(geocode); cache = app.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB); @@ -294,7 +290,7 @@ public class cgeopopup extends AbstractActivity { itemName.setText(res.getString(R.string.cache_status)); - StringBuilder state = new StringBuilder(); + final StringBuilder state = new StringBuilder(); if (cache.isFound()) { if (state.length() > 0) { state.append(", "); @@ -322,8 +318,6 @@ public class cgeopopup extends AbstractActivity { itemValue.setText(state.toString()); detailsList.addView(itemLayout); - - state = null; } // distance @@ -432,7 +426,7 @@ public class cgeopopup extends AbstractActivity { if (cache.getListId() > 0) { long diff = (System.currentTimeMillis() / (60 * 1000)) - (cache.getDetailedUpdate() / (60 * 1000)); // minutes - String ago = ""; + String ago; if (diff < 15) { ago = res.getString(R.string.cache_offline_time_mins_few); } else if (diff < 50) { @@ -469,10 +463,6 @@ public class cgeopopup extends AbstractActivity { } catch (Exception e) { Log.e("cgeopopup.init: " + e.toString()); } - - if (geo != null) { - geoUpdate.updateLocation(geo); - } } @Override @@ -485,52 +475,27 @@ public class cgeopopup extends AbstractActivity { @Override public void onResume() { super.onResume(); - init(); - } - - @Override - public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - - super.onDestroy(); - } - - @Override - public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - - super.onStop(); + app.addGeoObserver(geoUpdate); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(geoUpdate); super.onPause(); } - private class update implements UpdateLocationCallback { + private class UpdateLocation extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + protected void updateLocation(final IGeoData geo) { try { - if (geo.coordsNow != null && cache != null && cache.getCoords() != null) { - cacheDistance.setText(HumanDistance.getHumanDistance(geo.coordsNow.distanceTo(cache.getCoords()))); + if (geo.getCoords() != null && cache != null && cache.getCoords() != null) { + cacheDistance.setText(HumanDistance.getHumanDistance(geo.getCoords().distanceTo(cache.getCoords()))); cacheDistance.bringToFront(); } } catch (Exception e) { - Log.w("Failed to update location."); + Log.w("Failed to UpdateLocation location."); } } } @@ -541,7 +506,7 @@ public class cgeopopup extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); } private void cachesAround() { @@ -651,7 +616,7 @@ public class cgeopopup extends AbstractActivity { showToast(res.getString(R.string.cache_coordinates_no)); return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, cache, null, null); finish(); } @@ -663,7 +628,7 @@ public class cgeopopup extends AbstractActivity { showToast(res.getString(R.string.cache_coordinates_no)); return; } - NavigationAppFactory.startDefaultNavigationApplication2(geo, this, cache, null, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, cache, null, null); finish(); } diff --git a/main/src/cgeo/geocaching/cgeotouch.java b/main/src/cgeo/geocaching/cgeotouch.java index a0c7d03..fc6c2bf 100644 --- a/main/src/cgeo/geocaching/cgeotouch.java +++ b/main/src/cgeo/geocaching/cgeotouch.java @@ -59,33 +59,28 @@ public class cgeotouch extends AbstractActivity implements DateDialog.DateDialog private Handler loadDataHandler = new Handler() { @Override - public void handleMessage(Message msg) { - if (MSG_UPDATE_TYPE == msg.what) { + public void handleMessage(final Message msg) { + if (msg.what == MSG_UPDATE_TYPE) { setType((LogType) msg.obj); showToast(res.getString(R.string.info_log_type_changed)); } else { - if (Login.isEmpty(viewstates) && attempts < 2) { - showToast(res.getString(R.string.err_log_load_data_again)); + if (Login.isEmpty(viewstates)) { + if (attempts < 2) { + showToast(res.getString(R.string.err_log_load_data_again)); + new loadData(guid).start(); + } else { + showToast(res.getString(R.string.err_log_load_data)); + showProgress(false); + } + } else { + gettingViewstate = false; // we're done, user can post log - loadData thread; - thread = new loadData(guid); - thread.start(); + final Button buttonPost = (Button) findViewById(R.id.post); + buttonPost.setEnabled(true); + buttonPost.setOnClickListener(new postListener()); - return; - } else if (Login.isEmpty(viewstates) && attempts >= 2) { - showToast(res.getString(R.string.err_log_load_data)); showProgress(false); - - return; } - - gettingViewstate = false; // we're done, user can post log - - Button buttonPost = (Button) findViewById(R.id.post); - buttonPost.setEnabled(true); - buttonPost.setOnClickListener(new postListener()); - - showProgress(false); } } }; @@ -193,10 +188,10 @@ public class cgeotouch extends AbstractActivity implements DateDialog.DateDialog public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); - EditText text = null; - String textContent = null; - String dateString = null; - String timeString = null; + EditText text; + String textContent; + String dateString; + String timeString; String addText = ""; if ((id >= 0x1 && id <= 0x7)) { diff --git a/main/src/cgeo/geocaching/cgeotrackable.java b/main/src/cgeo/geocaching/cgeotrackable.java index 554abf2..005711c 100644 --- a/main/src/cgeo/geocaching/cgeotrackable.java +++ b/main/src/cgeo/geocaching/cgeotrackable.java @@ -88,7 +88,7 @@ public class cgeotrackable extends AbstractActivity { addDetail(R.string.trackable_name, StringUtils.isNotBlank(trackable.getName()) ? Html.fromHtml(trackable.getName()).toString() : res.getString(R.string.trackable_unknown)); // trackable type - String tbType = null; + String tbType; if (StringUtils.isNotBlank(trackable.getType())) { tbType = Html.fromHtml(trackable.getType()).toString(); } else { @@ -111,7 +111,7 @@ public class cgeotrackable extends AbstractActivity { trackable.getSpottedType() == cgTrackable.SPOTTED_UNKNOWN || trackable.getSpottedType() == cgTrackable.SPOTTED_OWNER ) { - String text = null; + String text; if (trackable.getSpottedType() == cgTrackable.SPOTTED_CACHE) { text = res.getString(R.string.trackable_spotted_in_cache) + " " + Html.fromHtml(trackable.getSpottedName()).toString(); @@ -207,7 +207,7 @@ public class cgeotrackable extends AbstractActivity { @Override public void run() { - BitmapDrawable image = null; + BitmapDrawable image; try { HtmlImage imgGetter = new HtmlImage(cgeotrackable.this, geocode, true, 0, false); @@ -350,21 +350,20 @@ public class cgeotrackable extends AbstractActivity { } @Override - public boolean onContextItemSelected(MenuItem item) { - final int id = item.getItemId(); - - if (id == 1) { - cgeocaches.startActivityOwner(this, contextMenuUser); - return true; - } else if (id == 2) { - cgeocaches.startActivityUserName(this, contextMenuUser); - return true; - } else if (id == 3) { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/profile/?u=" + URLEncoder.encode(contextMenuUser)))); - - return true; + public boolean onContextItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case 1: + cgeocaches.startActivityOwner(this, contextMenuUser); + return true; + case 2: + 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)))); + return true; + default: + return false; } - return false; } @Override @@ -460,7 +459,7 @@ public class cgeotrackable extends AbstractActivity { TextView logView = (TextView) rowView.findViewById(R.id.log); logView.setMovementMethod(LinkMovementMethod.getInstance()); - logView.setText(Html.fromHtml(log.log, new HtmlImage(cgeotrackable.this, null, false, StoredList.TEMPORARY_LIST_ID, false), null), TextView.BufferType.SPANNABLE); + logView.setText(Html.fromHtml(log.log, new HtmlImage(this, null, false, StoredList.TEMPORARY_LIST_ID, false), null), TextView.BufferType.SPANNABLE); // add LogImages LinearLayout logLayout = (LinearLayout) rowView.findViewById(R.id.log_layout); @@ -555,7 +554,7 @@ public class cgeotrackable extends AbstractActivity { return; } - BitmapDrawable image = null; + BitmapDrawable image; try { HtmlImage imgGetter = new HtmlImage(cgeotrackable.this, trackable.getGeocode(), false, 0, false); diff --git a/main/src/cgeo/geocaching/cgeowaypoint.java b/main/src/cgeo/geocaching/cgeowaypoint.java index 7d1f4b8..ca3182d 100644 --- a/main/src/cgeo/geocaching/cgeowaypoint.java +++ b/main/src/cgeo/geocaching/cgeowaypoint.java @@ -4,6 +4,7 @@ import cgeo.geocaching.activity.AbstractActivity; import cgeo.geocaching.apps.cache.navi.NavigationAppFactory; import cgeo.geocaching.enumerations.LoadFlags; import cgeo.geocaching.enumerations.LoadFlags.SaveFlag; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -27,7 +28,7 @@ import android.widget.TextView; import java.util.EnumSet; -public class cgeowaypoint extends AbstractActivity { +public class cgeowaypoint extends AbstractActivity implements IObserver<IGeoData> { private static final int MENU_ID_NAVIGATION = 0; private static final int MENU_ID_CACHES_AROUND = 5; @@ -36,8 +37,6 @@ public class cgeowaypoint extends AbstractActivity { private cgWaypoint waypoint = null; private int id = -1; private ProgressDialog waitDialog = null; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private Handler loadWaypointHandler = new Handler() { @Override @@ -142,10 +141,6 @@ public class cgeowaypoint extends AbstractActivity { return; } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); waitDialog.setCancelable(true); @@ -165,10 +160,7 @@ public class cgeowaypoint extends AbstractActivity { public void onResume() { super.onResume(); - - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (waitDialog == null) { waitDialog = ProgressDialog.show(this, null, res.getString(R.string.waypoint_loading), true); @@ -180,28 +172,17 @@ public class cgeowaypoint extends AbstractActivity { @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -236,21 +217,22 @@ public class cgeowaypoint extends AbstractActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { - final int menuItem = item.getItemId(); - if (menuItem == MENU_ID_DEFAULT_NAVIGATION) { - goDefaultNavigation(null); - return true; - } else if (menuItem == MENU_ID_CACHES_AROUND) { - cachesAround(); - return true; - } else if (menuItem == MENU_ID_OPEN_GEOCACHE) { - goToGeocache(); - return true; - } else if (menuItem == MENU_ID_NAVIGATION) { - NavigationAppFactory.showNavigationMenu(geo, this, null, waypoint, null); - return true; + switch (item.getItemId()) { + case MENU_ID_DEFAULT_NAVIGATION: + goDefaultNavigation(null); + return true; + case MENU_ID_CACHES_AROUND: + cachesAround(); + return true; + case MENU_ID_OPEN_GEOCACHE: + goToGeocache(); + return true; + case MENU_ID_NAVIGATION: + NavigationAppFactory.showNavigationMenu(app.currentGeo(), this, null, waypoint, null); + return true; + default: + return false; } - return false; } private void cachesAround() { @@ -287,12 +269,9 @@ public class cgeowaypoint extends AbstractActivity { } } - private static class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - // nothing - } + @Override + public void update(final IGeoData geo) { + // nothing } private class editWaypointListener implements View.OnClickListener { @@ -330,7 +309,7 @@ public class cgeowaypoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication(geo, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication(app.currentGeo(), this, null, waypoint, null); } /** @@ -341,7 +320,7 @@ public class cgeowaypoint extends AbstractActivity { return; } - NavigationAppFactory.startDefaultNavigationApplication2(geo, this, null, waypoint, null); + NavigationAppFactory.startDefaultNavigationApplication2(app.currentGeo(), this, null, waypoint, null); } private boolean navigationPossible() { @@ -367,7 +346,7 @@ public class cgeowaypoint extends AbstractActivity { if (handled) { return true; } - return NavigationAppFactory.onMenuItemSelected(item, geo, this, null, waypoint, null); + return NavigationAppFactory.onMenuItemSelected(item, app.currentGeo(), this, null, waypoint, null); } public static void startActivity(final Context context, final int waypointId) { diff --git a/main/src/cgeo/geocaching/cgeowaypointadd.java b/main/src/cgeo/geocaching/cgeowaypointadd.java index 3d4c4c1..9c02eef 100644 --- a/main/src/cgeo/geocaching/cgeowaypointadd.java +++ b/main/src/cgeo/geocaching/cgeowaypointadd.java @@ -9,6 +9,7 @@ import cgeo.geocaching.geopoint.DistanceParser; import cgeo.geocaching.geopoint.Geopoint; import cgeo.geocaching.geopoint.GeopointFormatter; import cgeo.geocaching.utils.BaseUtils; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.Log; import org.apache.commons.lang3.StringUtils; @@ -31,12 +32,10 @@ import java.util.ArrayList; import java.util.EnumSet; import java.util.List; -public class cgeowaypointadd extends AbstractActivity { +public class cgeowaypointadd extends AbstractActivity implements IObserver<IGeoData> { private String geocode = null; private int id = -1; - private cgGeo geo = null; - private UpdateLocationCallback geoUpdate = new update(); private ProgressDialog waitDialog = null; private cgWaypoint waypoint = null; private Geopoint gpTemp = null; @@ -104,10 +103,6 @@ public class cgeowaypointadd extends AbstractActivity { setContentView(R.layout.waypoint_new); setTitle("waypoint"); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - // get parameters Bundle extras = getIntent().getExtras(); if (extras != null) { @@ -170,10 +165,7 @@ public class cgeowaypointadd extends AbstractActivity { public void onResume() { super.onResume(); - - if (geo == null) { - geo = app.startGeo(geoUpdate); - } + app.addGeoObserver(this); if (id > 0) { if (waitDialog == null) { @@ -187,28 +179,17 @@ public class cgeowaypointadd extends AbstractActivity { @Override public void onDestroy() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onDestroy(); } @Override public void onStop() { - if (geo != null) { - geo = app.removeGeo(); - } - super.onStop(); } @Override public void onPause() { - if (geo != null) { - geo = app.removeGeo(); - } - + app.deleteGeoObserver(this); super.onPause(); } @@ -249,23 +230,20 @@ public class cgeowaypointadd extends AbstractActivity { distanceUnitSelector.setOnItemSelectedListener(new changeDistanceUnit(this)); } - private class update implements UpdateLocationCallback { - - @Override - public void updateLocation(cgGeo geo) { - Log.d("cgeowaypointadd.updateLocation called"); - if (geo == null || geo.coordsNow == null) { - return; - } + @Override + public void update(final IGeoData geo) { + Log.d("cgeowaypointadd.updateLocation called"); + if (geo.getCoords() == null) { + return; + } - try { - Button bLat = (Button) findViewById(R.id.buttonLatitude); - Button bLon = (Button) findViewById(R.id.buttonLongitude); - bLat.setHint(geo.coordsNow.format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); - bLon.setHint(geo.coordsNow.format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); - } catch (Exception e) { - Log.w("Failed to update location."); - } + try { + Button bLat = (Button) findViewById(R.id.buttonLatitude); + Button bLon = (Button) findViewById(R.id.buttonLongitude); + bLat.setHint(geo.getCoords().format(GeopointFormatter.Format.LAT_DECMINUTE_RAW)); + bLon.setHint(geo.getCoords().format(GeopointFormatter.Format.LON_DECMINUTE_RAW)); + } catch (Exception e) { + Log.w("Failed to update location."); } } @@ -293,7 +271,7 @@ public class cgeowaypointadd extends AbstractActivity { gp = gpTemp; } cgCache cache = app.loadCache(geocode, LoadFlags.LOAD_WAYPOINTS); - cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, cache, gp, geo); + cgeocoords coordsDialog = new cgeocoords(cgeowaypointadd.this, cache, gp, app.currentGeo()); coordsDialog.setCancelable(true); coordsDialog.setOnCoordinateUpdate(new cgeocoords.CoordinateUpdate() { @Override @@ -378,16 +356,18 @@ public class cgeowaypointadd extends AbstractActivity { showToast(res.getString(e.resource)); return; } - } else if (geo == null || geo.coordsNow == null) { - showToast(res.getString(R.string.err_point_curr_position_unavailable)); - return; } else { - coords = geo.coordsNow; + final IGeoData geo = app.currentGeo(); + if (geo.getCoords() == null) { + showToast(res.getString(R.string.err_point_curr_position_unavailable)); + return; + } + coords = geo.getCoords(); } if (StringUtils.isNotBlank(bearingText) && StringUtils.isNotBlank(distanceText)) { // bearing & distance - double bearing = 0; + double bearing; try { bearing = Double.parseDouble(bearingText); } catch (NumberFormatException e) { diff --git a/main/src/cgeo/geocaching/connector/OXConnector.java b/main/src/cgeo/geocaching/connector/OXConnector.java index 755dbaa..cfde92f 100644 --- a/main/src/cgeo/geocaching/connector/OXConnector.java +++ b/main/src/cgeo/geocaching/connector/OXConnector.java @@ -32,4 +32,10 @@ public class OXConnector extends AbstractConnector { return "www.opencaching.com"; } + @Override + public String getLicenseText(cgCache cache) { + // NOT TO BE TRANSLATED + return "<a href=\"" + getCacheUrl(cache) + "\">" + getName() + "</a> data licensed under the Creative Commons BY-SA 3.0 License"; + } + } diff --git a/main/src/cgeo/geocaching/connector/gc/GCBase.java b/main/src/cgeo/geocaching/connector/gc/GCBase.java index 4ba1be6..d7f6241 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCBase.java +++ b/main/src/cgeo/geocaching/connector/gc/GCBase.java @@ -68,7 +68,7 @@ public class GCBase { public static SearchResult searchByViewport(final Viewport viewport, final String[] tokens) { Strategy strategy = Settings.getLiveMapStrategy(); if (strategy == Strategy.AUTO) { - float speedNow = cgeoapplication.getInstance().getSpeedFromGeo(); + float speedNow = cgeoapplication.getInstance().currentGeo().getSpeed(); strategy = speedNow >= 8 ? Strategy.FAST : Strategy.DETAILED; // 8 m/s = 30 km/h } // return searchByViewport(viewport, tokens, strategy); @@ -77,7 +77,7 @@ public class GCBase { { SearchResult result = searchByViewport(viewport, tokens, strategy); String text = Formatter.SEPARATOR + strategy.getL10n() + Formatter.SEPARATOR; - int speed = (int) cgeoapplication.getInstance().getSpeedFromGeo(); + int speed = (int) cgeoapplication.getInstance().currentGeo().getSpeed(); if (Settings.isUseMetricUnits()) { text += speed + " km/h"; } else { @@ -376,7 +376,7 @@ public class GCBase { try { final Parameters params = new Parameters("i", geocodeList, "_", String.valueOf(System.currentTimeMillis())); - final String data = Tile.requestMapInfo(referer, params, referer); + final String data = StringUtils.defaultString(Tile.requestMapInfo(referer, params, referer)); // Example JSON information // {"status":"success", diff --git a/main/src/cgeo/geocaching/connector/gc/GCConstants.java b/main/src/cgeo/geocaching/connector/gc/GCConstants.java index ecaa964..083626d 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCConstants.java +++ b/main/src/cgeo/geocaching/connector/gc/GCConstants.java @@ -75,8 +75,12 @@ public final class GCConstants { * Patterns for parsing trackables */ public final static Pattern PATTERN_TRACKABLE_GUID = Pattern.compile("<a id=\"ctl00_ContentBody_lnkPrint\" title=\"[^\"]*\" href=\".*sheet\\.aspx\\?guid=([a-z0-9\\-]+)\"[^>]*>[^<]*</a>"); - public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<span id=\"ctl00_ContentBody_BugDetails_BugTBNum\" String=\"[^\"]*\">Use[^<]*<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item.[^<]*</span>"); - public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("<h2[^>]*>(?:[^<]*<img[^>]*>)?[^<]*<span id=\"ctl00_ContentBody_lbHeading\">([^<]+)</span>[^<]*</h2>"); + public final static Pattern PATTERN_TRACKABLE_GEOCODE = Pattern.compile("<strong>(TB[0-9A-Z]+)[^<]*</strong> to reference this item."); + /** + * some parts of the webpage don't correctly encode the name, therefore this pattern must be checked with a + * trackable name that needs HTML encoding + */ + public final static Pattern PATTERN_TRACKABLE_NAME = Pattern.compile("name=\"og:title\" content=\"([^\"]+)\""); /** Two groups ! */ public final static Pattern PATTERN_TRACKABLE_OWNER = Pattern.compile("<dt>\\W*Owner:[^<]*</dt>[^<]*<dd>[^<]*<a id=\"ctl00_ContentBody_BugDetails_BugOwner\" title=\"[^\"]*\" href=\"[^\"]*/profile/\\?guid=([a-z0-9\\-]+)\">([^<]+)<\\/a>[^<]*</dd>"); public final static Pattern PATTERN_TRACKABLE_RELEASES = Pattern.compile("<dt>\\W*Released:[^<]*</dt>[^<]*<dd>[^<]*<span id=\"ctl00_ContentBody_BugDetails_BugReleaseDate\">([^<]+)<\\/span>[^<]*</dd>"); diff --git a/main/src/cgeo/geocaching/connector/gc/GCParser.java b/main/src/cgeo/geocaching/connector/gc/GCParser.java index 9c61c10..c3325f0 100644 --- a/main/src/cgeo/geocaching/connector/gc/GCParser.java +++ b/main/src/cgeo/geocaching/connector/gc/GCParser.java @@ -68,7 +68,6 @@ public abstract class GCParser { } final List<String> cids = new ArrayList<String>(); - final List<String> guids = new ArrayList<String>(); String recaptchaChallenge = null; String recaptchaText = null; String page = pageContent; @@ -134,8 +133,6 @@ public abstract class GCParser { while (matcherGuidAndDisabled.find()) { if (matcherGuidAndDisabled.groupCount() > 0) { - guids.add(matcherGuidAndDisabled.group(1)); - cache.setGuid(matcherGuidAndDisabled.group(1)); if (matcherGuidAndDisabled.group(4) != null) { cache.setName(Html.fromHtml(matcherGuidAndDisabled.group(4).trim()).toString()); @@ -630,8 +627,8 @@ public abstract class GCParser { } // waypoints - int wpBegin = 0; - int wpEnd = 0; + int wpBegin; + int wpEnd; wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints @@ -994,7 +991,7 @@ public abstract class GCParser { final StringBuilder hdnSelected = new StringBuilder(); for (TrackableLog tb : trackables) { - String ctl = null; + String ctl; final String action = Integer.toString(tb.id) + tb.action.action; if (tb.ctl < 10) { @@ -1191,7 +1188,7 @@ public abstract class GCParser { trackable.setIconUrl(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_ICON, true, trackable.getIconUrl())); // trackable name - trackable.setName(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_NAME, true, trackable.getName())); + trackable.setName(Html.fromHtml(BaseUtils.getMatch(page, GCConstants.PATTERN_TRACKABLE_NAME, true, "")).toString()); // trackable type if (StringUtils.isNotBlank(trackable.getName())) { @@ -1353,7 +1350,7 @@ public abstract class GCParser { * retrieve friend logs */ private static List<LogEntry> loadLogsFromDetails(final String page, final cgCache cache, final boolean friends, final boolean getDataFromPage) { - String rawResponse = null; + String rawResponse; if (!getDataFromPage) { final Matcher userTokenMatcher = GCConstants.PATTERN_USERTOKEN2.matcher(page); @@ -1505,7 +1502,7 @@ public abstract class GCParser { final Integer ctl = Integer.valueOf(trackableMatcher.group(3)); final Integer id = Integer.valueOf(trackableMatcher.group(5)); if (trackCode != null && name != null && ctl != null && id != null) { - final TrackableLog entry = new TrackableLog(trackCode, name, id.intValue(), ctl.intValue()); + final TrackableLog entry = new TrackableLog(trackCode, name, id, ctl); Log.i("Trackable in inventory (#" + entry.ctl + "/" + entry.id + "): " + entry.trackCode + " - " + entry.name); trackableLogs.add(entry); diff --git a/main/src/cgeo/geocaching/connector/gc/IconDecoder.java b/main/src/cgeo/geocaching/connector/gc/IconDecoder.java index e052f60..74e78cc 100644 --- a/main/src/cgeo/geocaching/connector/gc/IconDecoder.java +++ b/main/src/cgeo/geocaching/connector/gc/IconDecoder.java @@ -153,7 +153,6 @@ public abstract class IconDecoder { } if ((bitmap.getPixel(x + POSX_FOUND, y + POSY_FOUND) & 0x00FFFFFF) == COLOR_FOUND) { cache.setFound(true); - return; } } catch (IllegalArgumentException e) { // intentionally left blank diff --git a/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java b/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java index ce59901..165e277 100644 --- a/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java +++ b/main/src/cgeo/geocaching/connector/opencaching/OkapiClient.java @@ -226,7 +226,7 @@ final public class OkapiClient { if ("Found it".equalsIgnoreCase(logType)) { return LogType.LOG_FOUND_IT; } - else if ("Didn't find it".equalsIgnoreCase(logType)) { + if ("Didn't find it".equalsIgnoreCase(logType)) { return LogType.LOG_DIDNT_FIND_IT; } return LogType.LOG_NOTE; @@ -280,11 +280,14 @@ final public class OkapiClient { private static CacheType getCacheType(final String cacheType) { if (cacheType.equalsIgnoreCase("Traditional")) { return CacheType.TRADITIONAL; - } else if (cacheType.equalsIgnoreCase("Multi")) { + } + if (cacheType.equalsIgnoreCase("Multi")) { return CacheType.MULTI; - } else if (cacheType.equalsIgnoreCase("Quiz")) { + } + if (cacheType.equalsIgnoreCase("Quiz")) { return CacheType.MYSTERY; - } else if (cacheType.equalsIgnoreCase("Virtual")) { + } + if (cacheType.equalsIgnoreCase("Virtual")) { return CacheType.VIRTUAL; } return CacheType.UNKNOWN; diff --git a/main/src/cgeo/geocaching/export/FieldnoteExport.java b/main/src/cgeo/geocaching/export/FieldnoteExport.java index 50cc620..babc4b6 100644 --- a/main/src/cgeo/geocaching/export/FieldnoteExport.java +++ b/main/src/cgeo/geocaching/export/FieldnoteExport.java @@ -169,7 +169,7 @@ class FieldnoteExport extends AbstractExport { SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt"); - OutputStream os = null; + OutputStream os; Writer fw = null; try { os = new FileOutputStream(exportFile); diff --git a/main/src/cgeo/geocaching/files/FileParser.java b/main/src/cgeo/geocaching/files/FileParser.java index 20e757c..090573a 100644 --- a/main/src/cgeo/geocaching/files/FileParser.java +++ b/main/src/cgeo/geocaching/files/FileParser.java @@ -52,7 +52,7 @@ public abstract class FileParser { final BufferedReader input = new BufferedReader(new InputStreamReader(progressInputStream)); try { - String line = null; + String line; while ((line = input.readLine()) != null) { buffer.append(line); showProgressMessage(progressHandler, progressInputStream.getProgress()); diff --git a/main/src/cgeo/geocaching/files/GPXParser.java b/main/src/cgeo/geocaching/files/GPXParser.java index ec8c307..7870a16 100644 --- a/main/src/cgeo/geocaching/files/GPXParser.java +++ b/main/src/cgeo/geocaching/files/GPXParser.java @@ -193,7 +193,7 @@ public abstract class GPXParser extends FileParser { return null; // id not found } // get text for string - String stringName = null; + String stringName; try { stringName = cgeoapplication.getInstance().getResources().getResourceName(stringId); } catch (NullPointerException e) { @@ -436,7 +436,7 @@ public abstract class GPXParser extends FileParser { @Override public void end(String watchList) { - cache.setOnWatchlist(Boolean.valueOf(watchList.trim()).booleanValue()); + cache.setOnWatchlist(Boolean.valueOf(watchList.trim())); } }); diff --git a/main/src/cgeo/geocaching/files/LocalStorage.java b/main/src/cgeo/geocaching/files/LocalStorage.java index f37d22f..6853c08 100644 --- a/main/src/cgeo/geocaching/files/LocalStorage.java +++ b/main/src/cgeo/geocaching/files/LocalStorage.java @@ -61,12 +61,7 @@ public class LocalStorage { */ static String getExtension(final String url) { final String urlExt = StringUtils.substringAfterLast(url, "."); - if (urlExt.length() > 4) { - return ""; - } else if (urlExt.length() > 0) { - return "." + urlExt; - } - return ""; + return urlExt.length() >= 1 && urlExt.length() <= 4 ? "." + urlExt : ""; } /** @@ -145,7 +140,7 @@ public class LocalStorage { * the entity whose content will be saved * @param targetFile * the target file, which will be created if necessary - * @return true if the operation was successful, false otherwise + * @return true if the operation was successful, false otherwise, in which case the file will not exist */ public static boolean saveEntityToFile(final HttpResponse response, final File targetFile) { if (response == null) { @@ -154,8 +149,8 @@ public class LocalStorage { try { final boolean saved = saveToFile(response.getEntity().getContent(), targetFile); - saveHeader("etag", response, targetFile); - saveHeader("last-modified", response, targetFile); + saveHeader("etag", saved ? response : null, targetFile); + saveHeader("last-modified", saved ? response : null, targetFile); return saved; } catch (IOException e) { Log.e("LocalStorage.saveEntityToFile", e); @@ -165,7 +160,7 @@ public class LocalStorage { } private static void saveHeader(final String name, final HttpResponse response, final File baseFile) { - final Header header = response.getFirstHeader(name); + final Header header = response != null ? response.getFirstHeader(name) : null; final File file = filenameForHeader(baseFile, name); if (header == null) { file.delete(); @@ -209,6 +204,9 @@ public class LocalStorage { /** * Save an HTTP response to a file. + * <p/> + * If the response could not be saved to the file due, for example, to a network error, + * the file will not exist when this method returns. * * @param entity * the entity whose content will be saved @@ -224,16 +222,18 @@ public class LocalStorage { try { try { final FileOutputStream fos = new FileOutputStream(targetFile); - try { - return copy(inputStream, fos); - } finally { - fos.close(); + final boolean written = copy(inputStream, fos); + fos.close(); + if (!written) { + targetFile.delete(); } + return written; } finally { inputStream.close(); } } catch (IOException e) { Log.e("LocalStorage.saveToFile", e); + targetFile.delete(); } return false; } diff --git a/main/src/cgeo/geocaching/filter/TypeFilter.java b/main/src/cgeo/geocaching/filter/TypeFilter.java index 11321c7..05b97e0 100644 --- a/main/src/cgeo/geocaching/filter/TypeFilter.java +++ b/main/src/cgeo/geocaching/filter/TypeFilter.java @@ -34,7 +34,7 @@ class TypeFilter extends AbstractFilter { filters.add(new TypeFilter(cacheType)); } } - return filters.toArray(new TypeFilter[filters.size()]); + return filters.toArray(new IFilter[filters.size()]); } } diff --git a/main/src/cgeo/geocaching/gcvote/GCVote.java b/main/src/cgeo/geocaching/gcvote/GCVote.java index c8976b8..5a00009 100644 --- a/main/src/cgeo/geocaching/gcvote/GCVote.java +++ b/main/src/cgeo/geocaching/gcvote/GCVote.java @@ -98,7 +98,7 @@ public final class GCVote { return null; } - String voteData = null; + String voteData; final Matcher matcherVoteElement = patternVoteElement.matcher(page); while (matcherVoteElement.find()) { voteData = matcherVoteElement.group(1); diff --git a/main/src/cgeo/geocaching/go4cache/Go4CacheUser.java b/main/src/cgeo/geocaching/go4cache/Go4CacheUser.java index 606d8f3..08fd02e 100644 --- a/main/src/cgeo/geocaching/go4cache/Go4CacheUser.java +++ b/main/src/cgeo/geocaching/go4cache/Go4CacheUser.java @@ -44,14 +44,16 @@ public class Go4CacheUser { } public int getIconId() { - if (null == client) { + if (client == null) { return -1; } if (client.equalsIgnoreCase("c:geo")) { return R.drawable.client_cgeo; - } else if (client.equalsIgnoreCase("preCaching")) { + } + if (client.equalsIgnoreCase("preCaching")) { return R.drawable.client_precaching; - } else if (client.equalsIgnoreCase("Handy Geocaching")) { + } + if (client.equalsIgnoreCase("Handy Geocaching")) { return R.drawable.client_handygeocaching; } return -1; diff --git a/main/src/cgeo/geocaching/maps/CGeoMap.java b/main/src/cgeo/geocaching/maps/CGeoMap.java index 9a1dfce..d64b6a0 100644 --- a/main/src/cgeo/geocaching/maps/CGeoMap.java +++ b/main/src/cgeo/geocaching/maps/CGeoMap.java @@ -1,20 +1,19 @@ package cgeo.geocaching.maps; +import cgeo.geocaching.DirectionProvider; +import cgeo.geocaching.GeoObserver; +import cgeo.geocaching.IGeoData; import cgeo.geocaching.IWaypoint; import cgeo.geocaching.LiveMapInfo; import cgeo.geocaching.R; import cgeo.geocaching.SearchResult; import cgeo.geocaching.Settings; import cgeo.geocaching.StoredList; -import cgeo.geocaching.UpdateDirectionCallback; -import cgeo.geocaching.UpdateLocationCallback; +import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.cgCache; -import cgeo.geocaching.cgDirection; -import cgeo.geocaching.cgGeo; import cgeo.geocaching.cgWaypoint; import cgeo.geocaching.cgeoapplication; import cgeo.geocaching.cgeocaches; -import cgeo.geocaching.activity.ActivityMixin; import cgeo.geocaching.connector.ConnectorFactory; import cgeo.geocaching.connector.gc.GCBase; import cgeo.geocaching.connector.gc.Login; @@ -36,6 +35,7 @@ import cgeo.geocaching.maps.interfaces.MapViewImpl; import cgeo.geocaching.maps.interfaces.OnMapDragListener; import cgeo.geocaching.maps.interfaces.OtherCachersOverlayItemImpl; import cgeo.geocaching.utils.CancellableHandler; +import cgeo.geocaching.utils.IObserver; import cgeo.geocaching.utils.LeastRecentlyUsedSet; import cgeo.geocaching.utils.Log; @@ -121,10 +121,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto private MapViewImpl mapView = null; private MapControllerImpl mapController = null; private cgeoapplication app = null; - private cgGeo geo = null; - private cgDirection dir = null; - private UpdateLocationCallback geoUpdate = new UpdateLoc(); - private UpdateDirectionCallback dirUpdate = new UpdateDir(); + final private GeoObserver geoUpdate = new UpdateLoc(); + final private IObserver<Float> dirUpdate = new UpdateDir(); private SearchResult searchIntent = null; private String geocodeIntent = null; private Geopoint coordsIntent = null; @@ -283,11 +281,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto waitDialog.setOnCancelListener(null); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(activity, dirUpdate); + if (Settings.isUseCompass()) { + app.addDirectionObserver(dirUpdate); } } } @@ -298,11 +293,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto loadDetailsThread.stopIt(); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(activity, dirUpdate); + if (Settings.isUseCompass()) { + app.addDirectionObserver(dirUpdate); } } } @@ -402,13 +394,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto activity.setContentView(mapProvider.getMapLayoutId()); ActivityMixin.setTitle(activity, res.getString(R.string.map_map)); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(activity, dirUpdate); - } - // initialize map mapView = (MapViewImpl) activity.findViewById(mapProvider.getMapViewId()); mapView.setMapSource(); @@ -441,15 +426,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto mapController = mapView.getMapController(); mapController.setZoom(Settings.getMapZoom()); - // start location and directory services - if (geo != null) { - geoUpdate.updateLocation(geo); - } - if (dir != null) { - dirUpdate.updateDirection(dir); - } - - // live map, if no arguments are given live = (searchIntent == null && geocodeIntent == null && coordsIntent == null); @@ -498,18 +474,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } app.setAction(StringUtils.defaultIfBlank(geocodeIntent, null)); - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(activity, dirUpdate); - } - geoUpdate.updateLocation(geo); - - if (dir != null) { - dirUpdate.updateDirection(dir); - } + addGeoDirObservers(); if (!CollectionUtils.isEmpty(dirtyCaches)) { for (String geocode : dirtyCaches) { @@ -526,32 +492,16 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto startTimer(); } - @Override - public void onStop() { - if (loadTimer != null) { - loadTimer.stopIt(); - loadTimer = null; - } - - if (go4CacheTimer != null) { - go4CacheTimer.stopIt(); - go4CacheTimer = null; - } - - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } - - savePrefs(); - - if (mapView != null) { - mapView.destroyDrawingCache(); + private void addGeoDirObservers() { + app.addGeoObserver(geoUpdate); + if (Settings.isUseCompass()) { + app.addDirectionObserver(dirUpdate); } + } - super.onStop(); + private void deleteGeoDirObservers() { + app.deleteGeoObserver(geoUpdate); + app.deleteDirectionObserver(dirUpdate); } @Override @@ -566,12 +516,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto go4CacheTimer = null; } - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } + deleteGeoDirObservers(); savePrefs(); @@ -583,34 +528,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } @Override - public void onDestroy() { - if (loadTimer != null) { - loadTimer.stopIt(); - loadTimer = null; - } - - if (go4CacheTimer != null) { - go4CacheTimer.stopIt(); - go4CacheTimer = null; - } - - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } - - savePrefs(); - - if (mapView != null) { - mapView.destroyDrawingCache(); - } - - super.onDestroy(); - } - - @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu submenu = menu.addSubMenu(1, MENU_SELECT_MAPVIEW, 0, res.getString(R.string.map_view_map)).setIcon(R.drawable.ic_menu_mapmode); @@ -746,11 +663,8 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto loadDetailsThread.stopIt(); } - if (geo == null) { - geo = app.startGeo(geoUpdate); - } - if (Settings.isUseCompass() && dir == null) { - dir = app.startDir(activity, dirUpdate); + if (Settings.isUseCompass()) { + app.addDirectionObserver(dirUpdate); } } catch (Exception e) { Log.e("cgeocaches.onPrepareOptionsMenu.onCancel: " + e.toString()); @@ -897,21 +811,17 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } // Set center of map to my location if appropriate. - private void myLocationInMiddle() { - if (followMyLocation && geo != null) { - centerMap(geo.coordsNow); + private void myLocationInMiddle(final IGeoData geo) { + if (followMyLocation) { + centerMap(geo.getCoords()); } } // class: update location - private class UpdateLoc implements UpdateLocationCallback { + private class UpdateLoc extends GeoObserver { @Override - public void updateLocation(cgGeo geo) { - if (geo == null) { - return; - } - + protected void updateLocation(final IGeoData geo) { try { boolean repaintRequired = false; @@ -919,20 +829,20 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto overlayPosition = mapView.createAddPositionOverlay(activity); } - if (overlayPosition != null && geo.location != null) { - overlayPosition.setCoordinates(geo.location); + if (overlayPosition != null && geo.getLocation() != null) { + overlayPosition.setCoordinates(geo.getLocation()); } - if (geo.coordsNow != null) { + if (geo.getCoords() != null) { if (followMyLocation) { - myLocationInMiddle(); + myLocationInMiddle(geo); } else { repaintRequired = true; } } - if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h - overlayPosition.setHeading(geo.bearingNow); + if (!Settings.isUseCompass() || geo.getSpeed() > 5) { // use GPS when speed is higher than 18 km/h + overlayPosition.setHeading(geo.getBearing()); repaintRequired = true; } @@ -947,16 +857,12 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } // class: update direction - private class UpdateDir implements UpdateDirectionCallback { + private class UpdateDir implements IObserver<Float> { @Override - public void updateDirection(cgDirection dir) { - if (dir == null || dir.directionNow == null) { - return; - } - - if (overlayPosition != null && mapView != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h - overlayPosition.setHeading(dir.directionNow); + public void update(final Float direction) { + if (overlayPosition != null && mapView != null && (app.currentGeo().getSpeed() <= 5)) { // use compass when speed is lower than 18 km/h + overlayPosition.setHeading(DirectionProvider.getDirectionNow(activity, direction)); mapView.repaintRequired(overlayPosition); } } @@ -1361,7 +1267,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto List<OtherCachersOverlayItemImpl> items = new ArrayList<OtherCachersOverlayItemImpl>(); int counter = 0; - OtherCachersOverlayItemImpl item = null; + OtherCachersOverlayItemImpl item; for (Go4CacheUser userOne : users) { if (userOne.getCoords() == null) { @@ -1459,14 +1365,9 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto return; } - if (dir != null) { - dir = app.removeDir(); - } - if (geo != null) { - geo = app.removeGeo(); - } + deleteGeoDirObservers(); - for (String geocode : geocodes) { + for (final String geocode : geocodes) { try { if (handler.isCancelled()) { break; @@ -1510,6 +1411,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto // we're done handler.sendEmptyMessage(FINISHED_LOADING_DETAILS); + addGeoDirObservers(); } } @@ -1591,7 +1493,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto private void switchMyLocationButton() { if (followMyLocation) { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_on); - myLocationInMiddle(); + myLocationInMiddle(app.currentGeo()); } else { myLocSwitch.setImageResource(R.drawable.actionbar_mylocation_off); } @@ -1692,12 +1594,10 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto * Waypoint. Mutally exclusive with cache * @return */ - private CachesOverlayItemImpl getItem(IWaypoint coord, cgCache cache, cgWaypoint waypoint) { + private CachesOverlayItemImpl getItem(final IWaypoint coord, final cgCache cache, final cgWaypoint waypoint) { if (cache != null) { - - CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, cache.getType()); - - int hashcode = new HashCodeBuilder() + final CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, cache.getType()); + final int hashcode = new HashCodeBuilder() .append(cache.isReliableLatLon()) .append(cache.getType().id) .append(cache.isDisabled() || cache.isArchived()) @@ -1709,23 +1609,20 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto .append(cache.getListId() > 0) .toHashCode(); - LayerDrawable ldFromCache = CGeoMap.overlaysCache.get(hashcode); + final LayerDrawable ldFromCache = CGeoMap.overlaysCache.get(hashcode); if (ldFromCache != null) { item.setMarker(ldFromCache); return item; } - ArrayList<Drawable> layers = new ArrayList<Drawable>(); - ArrayList<int[]> insets = new ArrayList<int[]>(); - + // Set initial capacities to the maximum of layers and insets to avoid dynamic reallocation + final ArrayList<Drawable> layers = new ArrayList<Drawable>(9); + final ArrayList<int[]> insets = new ArrayList<int[]>(8); // background: disabled or not - Drawable marker = getResources().getDrawable(R.drawable.marker); - if (cache.isDisabled() || cache.isArchived()) { - marker = getResources().getDrawable(R.drawable.marker_disabled); - } + final Drawable marker = getResources().getDrawable(cache.isDisabled() || cache.isArchived() ? R.drawable.marker_disabled : R.drawable.marker); layers.add(marker); - int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0; + final int resolution = marker.getIntrinsicWidth() > 40 ? 1 : 0; // reliable or not if (!cache.isReliableLatLon()) { insets.add(INSET_RELIABLE[resolution]); @@ -1735,7 +1632,7 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto layers.add(getResources().getDrawable(cache.getType().markerId)); insets.add(INSET_TYPE[resolution]); // own - if ( cache.isOwn() ) { + if (cache.isOwn()) { layers.add(getResources().getDrawable(R.drawable.marker_own)); insets.add(INSET_OWN[resolution]); // if not, checked if stored @@ -1763,11 +1660,10 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto insets.add(INSET_PERSONALNOTE[resolution]); } - - LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()])); + final LayerDrawable ld = new LayerDrawable(layers.toArray(new Drawable[layers.size()])); int index = 1; - for ( int[] inset : insets) { + for (final int[] inset : insets) { ld.setLayerInset(index++, inset[0], inset[1], inset[2], inset[3]); } @@ -1775,10 +1671,10 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto item.setMarker(ld); return item; + } - } else if (waypoint != null) { - - CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, null); + if (waypoint != null) { + final CachesOverlayItemImpl item = mapProvider.getCachesOverlayItem(coord, null); Drawable[] layers = new Drawable[2]; layers[0] = getResources().getDrawable(R.drawable.marker); layers[1] = getResources().getDrawable(waypoint.getWaypointType().markerId); @@ -1794,7 +1690,6 @@ public class CGeoMap extends AbstractMap implements OnMapDragListener, ViewFacto } return null; - } } diff --git a/main/src/cgeo/geocaching/maps/OtherCachersOverlayItem.java b/main/src/cgeo/geocaching/maps/OtherCachersOverlayItem.java index d71bbcf..9844e83 100644 --- a/main/src/cgeo/geocaching/maps/OtherCachersOverlayItem.java +++ b/main/src/cgeo/geocaching/maps/OtherCachersOverlayItem.java @@ -16,7 +16,7 @@ public class OtherCachersOverlayItem { } public Drawable getMarker() { - Drawable marker = null; + Drawable marker; if (user != null && user.getDate() != null && user.getDate().getTime() >= (System.currentTimeMillis() - (20 * 60 * 1000))) { marker = context.getResources().getDrawable(R.drawable.user_location_active); diff --git a/main/src/cgeo/geocaching/maps/PositionOverlay.java b/main/src/cgeo/geocaching/maps/PositionOverlay.java index a09b6de..9099498 100644 --- a/main/src/cgeo/geocaching/maps/PositionOverlay.java +++ b/main/src/cgeo/geocaching/maps/PositionOverlay.java @@ -150,7 +150,7 @@ public class PositionOverlay implements GeneralOverlay { if (Settings.isMapTrail()) { int size = history.size(); if (size > 1) { - int alpha = 0; + int alpha; int alphaCnt = size - 201; if (alphaCnt < 1) { alphaCnt = 1; @@ -210,7 +210,7 @@ public class PositionOverlay implements GeneralOverlay { marginTop = center.y - heightArrowHalf; Matrix matrix = new Matrix(); - matrix.setRotate(heading.floatValue(), widthArrowHalf, heightArrowHalf); + matrix.setRotate(heading, widthArrowHalf, heightArrowHalf); matrix.postTranslate(marginLeft, marginTop); canvas.drawBitmap(arrow, matrix, null); diff --git a/main/src/cgeo/geocaching/network/Parameters.java b/main/src/cgeo/geocaching/network/Parameters.java index 9cf51d2..90965e4 100644 --- a/main/src/cgeo/geocaching/network/Parameters.java +++ b/main/src/cgeo/geocaching/network/Parameters.java @@ -97,7 +97,8 @@ public class Parameters extends ArrayList<NameValuePair> { public static Parameters merge(final Parameters params, final Parameters extra) { if (params == null) { return extra; - } else if (extra != null) { + } + if (extra != null) { params.addAll(extra); } return params; diff --git a/main/src/cgeo/geocaching/sorting/AbstractCacheComparator.java b/main/src/cgeo/geocaching/sorting/AbstractCacheComparator.java index 9c3f15b..2015375 100644 --- a/main/src/cgeo/geocaching/sorting/AbstractCacheComparator.java +++ b/main/src/cgeo/geocaching/sorting/AbstractCacheComparator.java @@ -11,7 +11,7 @@ import cgeo.geocaching.utils.Log; public abstract class AbstractCacheComparator implements CacheComparator { @Override - public final int compare(cgCache cache1, cgCache cache2) { + public final int compare(final cgCache cache1, final cgCache cache2) { try { // first check that we have all necessary data for the comparison if (!canCompare(cache1, cache2)) { @@ -25,7 +25,7 @@ public abstract class AbstractCacheComparator implements CacheComparator { } /** - * check necessary preconditions (like missing fields) before running the comparison itself + * Check necessary preconditions (like missing fields) before running the comparison itself * * @param cache1 * @param cache2 @@ -34,7 +34,10 @@ public abstract class AbstractCacheComparator implements CacheComparator { protected abstract boolean canCompare(final cgCache cache1, final cgCache cache2); /** - * compares two caches. Logging and exception handling is implemented outside this method already. + * Compares two caches. Logging and exception handling is implemented outside this method already. + * <p/> + * A cache is smaller than another cache if it is desirable to show it first when presented to the user. + * For example, a highly rated cache must be considered smaller than a poorly rated one. * * @param cache1 * @param cache2 diff --git a/main/src/cgeo/geocaching/sorting/DifficultyComparator.java b/main/src/cgeo/geocaching/sorting/DifficultyComparator.java index 0d65660..123bab9 100644 --- a/main/src/cgeo/geocaching/sorting/DifficultyComparator.java +++ b/main/src/cgeo/geocaching/sorting/DifficultyComparator.java @@ -15,11 +15,6 @@ public class DifficultyComparator extends AbstractCacheComparator { @Override protected int compareCaches(final cgCache cache1, final cgCache cache2) { - if (cache1.getDifficulty() > cache2.getDifficulty()) { - return 1; - } else if (cache2.getDifficulty() > cache1.getDifficulty()) { - return -1; - } - return 0; + return Float.compare(cache1.getDifficulty(), cache2.getDifficulty()); } }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/sorting/EventDateComparator.java b/main/src/cgeo/geocaching/sorting/EventDateComparator.java index 0092901..ac49e66 100644 --- a/main/src/cgeo/geocaching/sorting/EventDateComparator.java +++ b/main/src/cgeo/geocaching/sorting/EventDateComparator.java @@ -1,8 +1,5 @@ package cgeo.geocaching.sorting; -import cgeo.geocaching.cgCache; - - /** * Compares caches by date. Used only for event caches. * @@ -11,13 +8,4 @@ import cgeo.geocaching.cgCache; */ public class EventDateComparator extends DateComparator { - @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { - return super.canCompare(cache1, cache2); - } - - @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - return super.compareCaches(cache1, cache2); - } } diff --git a/main/src/cgeo/geocaching/sorting/GeocodeComparator.java b/main/src/cgeo/geocaching/sorting/GeocodeComparator.java index 1377cce..fb93c0e 100644 --- a/main/src/cgeo/geocaching/sorting/GeocodeComparator.java +++ b/main/src/cgeo/geocaching/sorting/GeocodeComparator.java @@ -17,12 +17,8 @@ public class GeocodeComparator extends AbstractCacheComparator { } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.getGeocode().length() > cache2.getGeocode().length()) { - return 1; - } else if (cache2.getGeocode().length() > cache1.getGeocode().length()) { - return -1; - } - return cache1.getGeocode().compareToIgnoreCase(cache2.getGeocode()); + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + final int lengthDiff = cache1.getGeocode().length() - cache2.getGeocode().length(); + return lengthDiff != 0 ? lengthDiff : cache1.getGeocode().compareToIgnoreCase(cache2.getGeocode()); } } diff --git a/main/src/cgeo/geocaching/sorting/InventoryComparator.java b/main/src/cgeo/geocaching/sorting/InventoryComparator.java index b1842d7..d4e9f5e 100644 --- a/main/src/cgeo/geocaching/sorting/InventoryComparator.java +++ b/main/src/cgeo/geocaching/sorting/InventoryComparator.java @@ -11,19 +11,12 @@ import cgeo.geocaching.cgCache; public class InventoryComparator extends AbstractCacheComparator { @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { + protected boolean canCompare(final cgCache cache1, final cgCache cache2) { return true; } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - int itemCount1 = cache1.getInventoryItems(); - int itemCount2 = cache2.getInventoryItems(); - if (itemCount1 < itemCount2) { - return 1; - } else if (itemCount2 < itemCount1) { - return -1; - } - return 0; + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + return cache2.getInventoryItems() - cache1.getInventoryItems(); } } diff --git a/main/src/cgeo/geocaching/sorting/PopularityComparator.java b/main/src/cgeo/geocaching/sorting/PopularityComparator.java index 9fe254a..62ad9a9 100644 --- a/main/src/cgeo/geocaching/sorting/PopularityComparator.java +++ b/main/src/cgeo/geocaching/sorting/PopularityComparator.java @@ -9,17 +9,12 @@ import cgeo.geocaching.cgCache; public class PopularityComparator extends AbstractCacheComparator { @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { + protected boolean canCompare(final cgCache cache1, final cgCache cache2) { return true; } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.getFavoritePoints() < cache2.getFavoritePoints()) { - return 1; - } else if (cache2.getFavoritePoints() < cache1.getFavoritePoints()) { - return -1; - } - return 0; + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + return cache2.getFavoritePoints() - cache1.getFavoritePoints(); } } diff --git a/main/src/cgeo/geocaching/sorting/RatingComparator.java b/main/src/cgeo/geocaching/sorting/RatingComparator.java index 935ccd8..be071c5 100644 --- a/main/src/cgeo/geocaching/sorting/RatingComparator.java +++ b/main/src/cgeo/geocaching/sorting/RatingComparator.java @@ -9,28 +9,15 @@ import cgeo.geocaching.cgCache; public class RatingComparator extends AbstractCacheComparator { @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { + protected boolean canCompare(final cgCache cache1, final cgCache cache2) { return true; } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - float rating1 = cache1.getRating(); - float rating2 = cache2.getRating(); - - // voting can be disabled for caches, then assume an average rating instead - if (rating1 == 0.0) { - rating1 = 2.5f; - } - if (rating2 == 0.0) { - rating2 = 2.5f; - } - - if (rating1 < rating2) { - return 1; - } else if (rating2 < rating1) { - return -1; - } - return 0; + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + final float rating1 = cache1.getRating(); + final float rating2 = cache2.getRating(); + // Voting can be disabled for caches, then assume an average rating instead + return Float.compare(rating2 != 0.0 ? rating2 : 2.5f, rating1 != 0.0 ? rating1 : 2.5f); } }
\ No newline at end of file diff --git a/main/src/cgeo/geocaching/sorting/TerrainComparator.java b/main/src/cgeo/geocaching/sorting/TerrainComparator.java index c0590cb..9058a3c 100644 --- a/main/src/cgeo/geocaching/sorting/TerrainComparator.java +++ b/main/src/cgeo/geocaching/sorting/TerrainComparator.java @@ -9,17 +9,12 @@ import cgeo.geocaching.cgCache; public class TerrainComparator extends AbstractCacheComparator { @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { + protected boolean canCompare(final cgCache cache1, final cgCache cache2) { return cache1.getTerrain() != 0.0 && cache2.getTerrain() != 0.0; } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.getTerrain() > cache2.getTerrain()) { - return 1; - } else if (cache2.getTerrain() > cache1.getTerrain()) { - return -1; - } - return 0; + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + return Float.compare(cache1.getTerrain(), cache2.getTerrain()); } } diff --git a/main/src/cgeo/geocaching/sorting/VisitComparator.java b/main/src/cgeo/geocaching/sorting/VisitComparator.java index a580f2a..548ec7a 100644 --- a/main/src/cgeo/geocaching/sorting/VisitComparator.java +++ b/main/src/cgeo/geocaching/sorting/VisitComparator.java @@ -9,17 +9,12 @@ import cgeo.geocaching.cgCache; public class VisitComparator extends AbstractCacheComparator { @Override - protected boolean canCompare(cgCache cache1, cgCache cache2) { + protected boolean canCompare(final cgCache cache1, final cgCache cache2) { return cache1.getVisitedDate() > 0 && cache2.getVisitedDate() > 0; } @Override - protected int compareCaches(cgCache cache1, cgCache cache2) { - if (cache1.getVisitedDate() > cache2.getVisitedDate()) { - return -1; - } else if (cache1.getVisitedDate() < cache2.getVisitedDate()) { - return 1; - } - return 0; + protected int compareCaches(final cgCache cache1, final cgCache cache2) { + return Long.valueOf(cache2.getVisitedDate()).compareTo(cache1.getVisitedDate()); } } diff --git a/main/src/cgeo/geocaching/sorting/VoteComparator.java b/main/src/cgeo/geocaching/sorting/VoteComparator.java index 82ebdd3..8d9f907 100644 --- a/main/src/cgeo/geocaching/sorting/VoteComparator.java +++ b/main/src/cgeo/geocaching/sorting/VoteComparator.java @@ -18,15 +18,6 @@ public class VoteComparator extends AbstractCacheComparator { @Override protected int compareCaches(cgCache cache1, cgCache cache2) { // if there is no vote available, put that cache at the end of the list - float vote1 = cache1.getMyVote(); - float vote2 = cache2.getMyVote(); - - // compare - if (vote1 < vote2) { - return 1; - } else if (vote2 < vote1) { - return -1; - } - return 0; + return Float.compare(cache2.getMyVote(), cache1.getMyVote()); } } diff --git a/main/src/cgeo/geocaching/ui/AddressListAdapter.java b/main/src/cgeo/geocaching/ui/AddressListAdapter.java index d77d6cc..327b71d 100644 --- a/main/src/cgeo/geocaching/ui/AddressListAdapter.java +++ b/main/src/cgeo/geocaching/ui/AddressListAdapter.java @@ -21,24 +21,22 @@ import java.util.ArrayList; public class AddressListAdapter extends ArrayAdapter<Address> { - private LayoutInflater inflater; - private Geopoint location; + final private LayoutInflater inflater; + final private Geopoint location; public AddressListAdapter(final Context context) { super(context, 0); + inflater = ((Activity) context).getLayoutInflater(); + location = cgeoapplication.getInstance().currentGeo().getCoords(); } @Override - public View getView(int position, View convertView, ViewGroup parent) { - if (inflater == null) { - inflater = ((Activity) getContext()).getLayoutInflater(); - } - + public View getView(final int position, final View convertView, final ViewGroup parent) { final Address address = getItem(position); // holder pattern implementation + final AddressListView holder; View view = convertView; - AddressListView holder; if (view == null) { view = inflater.inflate(R.layout.addresses_item, null); @@ -55,8 +53,8 @@ public class AddressListAdapter extends ArrayAdapter<Address> { view.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View v) { - Activity activity = (Activity) v.getContext(); + public void onClick(final View v) { + final Activity activity = (Activity) v.getContext(); cgeocaches.startActivityAddress(activity, new Geopoint(address.getLatitude(), address.getLongitude()), StringUtils.defaultString(address.getAddressLine(0))); activity.finish(); } @@ -69,10 +67,6 @@ public class AddressListAdapter extends ArrayAdapter<Address> { } private CharSequence getDistanceText(final Address address) { - if (location == null) { - location = cgeoapplication.getInstance().getLastCoords(); - } - if (location != null && address.hasLatitude() && address.hasLongitude()) { return HumanDistance.getHumanDistance(location.distanceTo(new Geopoint(address.getLatitude(), address.getLongitude()))); } @@ -84,7 +78,7 @@ public class AddressListAdapter extends ArrayAdapter<Address> { final int maxIndex = address.getMaxAddressLineIndex(); final ArrayList<String> lines = new ArrayList<String>(); for (int i = 0; i <= maxIndex; i++) { - String line = address.getAddressLine(i); + final String line = address.getAddressLine(i); if (StringUtils.isNotBlank(line)) { lines.add(line); } diff --git a/main/src/cgeo/geocaching/ui/CacheListAdapter.java b/main/src/cgeo/geocaching/ui/CacheListAdapter.java index 9f2d69d..5d54359 100644 --- a/main/src/cgeo/geocaching/ui/CacheListAdapter.java +++ b/main/src/cgeo/geocaching/ui/CacheListAdapter.java @@ -35,7 +35,6 @@ import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.AccelerateDecelerateInterpolator; -import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.TranslateAnimation; @@ -73,7 +72,6 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { private static final int SWIPE_MIN_DISTANCE = 60; private static final int SWIPE_MAX_OFF_PATH = 100; private static final int SWIPE_DISTANCE = 80; - private static final float SWIPE_OPACITY = 0.5f; /** * time in milliseconds after which the list may be resorted due to position updates */ @@ -303,7 +301,7 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { } for (final CompassMiniView compass : compasses) { - compass.updateCoords(coordsIn); + compass.updateCurrentCoords(coordsIn); } } @@ -443,7 +441,7 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { distances.add(holder.distance); holder.distance.setContent(cache.getCoords()); compasses.add(holder.direction); - holder.direction.setContent(cache.getCoords()); + holder.direction.setTargetCoords(cache.getCoords()); if (cache.isFound() && cache.isLogOffline()) { holder.logStatusMark.setImageResource(R.drawable.mark_green_orange); @@ -472,7 +470,7 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { holder.inventory.removeAllViews(); } - ImageView tbIcon = null; + ImageView tbIcon; if (cache.getInventoryItems() > 0) { tbIcon = (ImageView) inflater.inflate(R.layout.trackable_icon, null); tbIcon.setImageResource(R.drawable.trackable_all); @@ -489,7 +487,7 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { holder.direction.updateAzimuth(azimuth); if (coords != null) { holder.distance.update(coords); - holder.direction.updateCoords(coords); + holder.direction.updateCurrentCoords(coords); } setDiDi = true; } else { @@ -798,21 +796,12 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { showCheckbox.setFillAfter(true); showCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); - // dim cache info - final Animation dimInfo = new AlphaAnimation(1.0f, SWIPE_OPACITY); - dimInfo.setRepeatCount(0); - dimInfo.setDuration(force ? 0 : 400); - dimInfo.setFillEnabled(true); - dimInfo.setFillAfter(true); - dimInfo.setInterpolator(new AccelerateDecelerateInterpolator()); - // animation set (container) final AnimationSet selectAnimation = new AnimationSet(true); selectAnimation.setFillEnabled(true); selectAnimation.setFillAfter(true); selectAnimation.addAnimation(showCheckbox); - selectAnimation.addAnimation(dimInfo); holder.oneInfo.startAnimation(selectAnimation); cache.setStatusCheckedView(true); @@ -833,21 +822,12 @@ public class CacheListAdapter extends ArrayAdapter<cgCache> { hideCheckbox.setFillAfter(true); hideCheckbox.setInterpolator(new AccelerateDecelerateInterpolator()); - // brighten cache info - final Animation brightenInfo = new AlphaAnimation(SWIPE_OPACITY, 1.0f); - brightenInfo.setRepeatCount(0); - brightenInfo.setDuration(force ? 0 : 400); - brightenInfo.setFillEnabled(true); - brightenInfo.setFillAfter(true); - brightenInfo.setInterpolator(new AccelerateDecelerateInterpolator()); - // animation set (container) final AnimationSet selectAnimation = new AnimationSet(true); selectAnimation.setFillEnabled(true); selectAnimation.setFillAfter(true); selectAnimation.addAnimation(hideCheckbox); - selectAnimation.addAnimation(brightenInfo); holder.oneInfo.startAnimation(selectAnimation); cache.setStatusCheckedView(false); diff --git a/main/src/cgeo/geocaching/ui/CompassMiniView.java b/main/src/cgeo/geocaching/ui/CompassMiniView.java index 1fa4cfb..a0aaeaf 100644 --- a/main/src/cgeo/geocaching/ui/CompassMiniView.java +++ b/main/src/cgeo/geocaching/ui/CompassMiniView.java @@ -1,10 +1,10 @@ package cgeo.geocaching.ui; import cgeo.geocaching.R; +import cgeo.geocaching.Settings; import cgeo.geocaching.geopoint.Geopoint; import android.content.Context; -import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; @@ -13,88 +13,114 @@ import android.graphics.PaintFlagsDrawFilter; import android.util.AttributeSet; import android.view.View; -public class CompassMiniView extends View { - private int arrowSkin = R.drawable.compass_arrow_mini_white; - private Context context = null; - private Geopoint cacheCoords = null; - private Bitmap compassArrow = null; +final public class CompassMiniView extends View { + private Geopoint targetCoords = null; private float azimuth = 0; private float heading = 0; - private PaintFlagsDrawFilter setfil = null; - private PaintFlagsDrawFilter remfil = null; - public CompassMiniView(Context contextIn) { - super(contextIn); - context = contextIn; + /** + * lazy initialized bitmap resource depending on selected skin + */ + private static int arrowSkin = 0; + /** + * bitmap shared by all instances of the view + */ + private static Bitmap compassArrow; + /** + * bitmap width + */ + private static int compassArrowWidth; + /** + * bitmap height + */ + private static int compassArrowHeight; + /** + * view instance counter for bitmap recycling + */ + private static int instances = 0; + + /** + * pixel size of the square arrow bitmap + */ + private static final int ARROW_BITMAP_SIZE = 21; + private static final PaintFlagsDrawFilter FILTER_SET = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG); + private static final PaintFlagsDrawFilter FILTER_REMOVE = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG, 0); + + public CompassMiniView(Context context) { + super(context); + initializeResources(context); } - public CompassMiniView(Context contextIn, AttributeSet attrs) { - super(contextIn, attrs); - context = contextIn; + public CompassMiniView(Context context, AttributeSet attrs) { + super(context, attrs); + initializeResources(context); + } - TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.cgCompassMini); - int usedSkin = attributes.getInt(R.styleable.cgCompassMini_skin, 0); - if (usedSkin == 1) { - arrowSkin = R.drawable.compass_arrow_mini_black; - } else { - arrowSkin = R.drawable.compass_arrow_mini_white; + private static void initializeResources(final Context context) { + if (arrowSkin == 0) { + if (Settings.isLightSkin()) { + arrowSkin = R.drawable.compass_arrow_mini_black; + } else { + arrowSkin = R.drawable.compass_arrow_mini_white; + } + } + if (compassArrow == null) { + compassArrow = BitmapFactory.decodeResource(context.getResources(), arrowSkin); + compassArrowWidth = compassArrow.getWidth(); + compassArrowHeight = compassArrow.getWidth(); } } @Override public void onAttachedToWindow() { - compassArrow = BitmapFactory.decodeResource(context.getResources(), arrowSkin); - - setfil = new PaintFlagsDrawFilter(0, Paint.FILTER_BITMAP_FLAG); - remfil = new PaintFlagsDrawFilter(Paint.FILTER_BITMAP_FLAG, 0); + instances++; } @Override public void onDetachedFromWindow() { - if (compassArrow != null) { - compassArrow.recycle(); - compassArrow = null; + instances--; + if (instances == 0) { + if (compassArrow != null) { + compassArrow.recycle(); + compassArrow = null; + } } } - public void setContent(final Geopoint cacheCoordsIn) { - cacheCoords = cacheCoordsIn; + public void setTargetCoords(final Geopoint point) { + targetCoords = point; } - protected void updateAzimuth(float azimuthIn) { - azimuth = azimuthIn; - + protected void updateAzimuth(float azimuth) { + this.azimuth = azimuth; updateDirection(); } - protected void updateHeading(float headingIn) { - heading = headingIn; - + protected void updateHeading(float heading) { + this.heading = heading; updateDirection(); } - protected void updateCoords(final Geopoint coordsIn) { - if (coordsIn == null || cacheCoords == null) { + protected void updateCurrentCoords(final Geopoint currentCoords) { + if (currentCoords == null || targetCoords == null) { return; } - heading = coordsIn.bearingTo(cacheCoords); - + heading = currentCoords.bearingTo(targetCoords); updateDirection(); } - protected void updateDirection() { + private void updateDirection() { if (compassArrow == null || compassArrow.isRecycled()) { return; } // compass margins - int compassRoseWidth = compassArrow.getWidth(); - int compassRoseHeight = compassArrow.getWidth(); - int marginLeft = (getWidth() - compassRoseWidth) / 2; - int marginTop = (getHeight() - compassRoseHeight) / 2; - invalidate(marginLeft, marginTop, (marginLeft + compassRoseWidth), (marginTop + compassRoseHeight)); + final int marginLeft = (getWidth() - compassArrowWidth) / 2; + final int marginTop = (getHeight() - compassArrowHeight) / 2; + + invalidate(marginLeft, marginTop, (marginLeft + compassArrowWidth), (marginTop + compassArrowHeight)); } @Override @@ -109,25 +135,20 @@ public class CompassMiniView extends View { } // compass margins - canvas.setDrawFilter(setfil); - - int marginLeft = 0; - int marginTop = 0; + canvas.setDrawFilter(FILTER_SET); - int compassArrowWidth = compassArrow.getWidth(); - int compassArrowHeight = compassArrow.getWidth(); - int canvasCenterX = (compassArrowWidth / 2) + ((getWidth() - compassArrowWidth) / 2); - int canvasCenterY = (compassArrowHeight / 2) + ((getHeight() - compassArrowHeight) / 2); + final int canvasCenterX = (compassArrowWidth / 2) + ((getWidth() - compassArrowWidth) / 2); + final int canvasCenterY = (compassArrowHeight / 2) + ((getHeight() - compassArrowHeight) / 2); - marginLeft = (getWidth() - compassArrowWidth) / 2; - marginTop = (getHeight() - compassArrowHeight) / 2; + final int marginLeft = (getWidth() - compassArrowWidth) / 2; + final int marginTop = (getHeight() - compassArrowHeight) / 2; canvas.rotate(-azimuthRelative, canvasCenterX, canvasCenterY); canvas.drawBitmap(compassArrow, marginLeft, marginTop, null); canvas.rotate(azimuthRelative, canvasCenterX, canvasCenterY); - canvas.setDrawFilter(remfil); + canvas.setDrawFilter(FILTER_REMOVE); } @Override @@ -136,36 +157,34 @@ public class CompassMiniView extends View { } private int measureWidth(int measureSpec) { - int result = 0; - int specMode = MeasureSpec.getMode(measureSpec); - int specSize = MeasureSpec.getSize(measureSpec); + final int specMode = MeasureSpec.getMode(measureSpec); + final int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { - result = specSize; - } else { - result = 21 + getPaddingLeft() + getPaddingRight(); + return specSize; + } - if (specMode == MeasureSpec.AT_MOST) { - result = Math.min(result, specSize); - } + int result = ARROW_BITMAP_SIZE + getPaddingLeft() + getPaddingRight(); + + if (specMode == MeasureSpec.AT_MOST) { + result = Math.min(result, specSize); } return result; } private int measureHeight(int measureSpec) { - int result = 0; - int specMode = MeasureSpec.getMode(measureSpec); - int specSize = MeasureSpec.getSize(measureSpec); + final int specMode = MeasureSpec.getMode(measureSpec); + final int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { - result = specSize; - } else { - result = 21 + getPaddingTop() + getPaddingBottom(); + return specSize; + } - if (specMode == MeasureSpec.AT_MOST) { - result = Math.min(result, specSize); - } + int result = ARROW_BITMAP_SIZE + getPaddingTop() + getPaddingBottom(); + + if (specMode == MeasureSpec.AT_MOST) { + result = Math.min(result, specSize); } return result; diff --git a/main/src/cgeo/geocaching/ui/CompassView.java b/main/src/cgeo/geocaching/ui/CompassView.java index f9fb569..8a295c3 100644 --- a/main/src/cgeo/geocaching/ui/CompassView.java +++ b/main/src/cgeo/geocaching/ui/CompassView.java @@ -209,8 +209,8 @@ public class CompassView extends View { int canvasCenterX = (compassRoseWidth / 2) + ((getWidth() - compassRoseWidth) / 2); int canvasCenterY = (compassRoseHeight / 2) + ((getHeight() - compassRoseHeight) / 2); - int marginLeftTemp = 0; - int marginTopTemp = 0; + int marginLeftTemp; + int marginTopTemp; super.onDraw(canvas); @@ -251,7 +251,7 @@ public class CompassView extends View { } private int measureWidth(int measureSpec) { - int result = 0; + int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); @@ -269,7 +269,7 @@ public class CompassView extends View { } private int measureHeight(int measureSpec) { - int result = 0; + int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); diff --git a/main/src/cgeo/geocaching/ui/GPXListAdapter.java b/main/src/cgeo/geocaching/ui/GPXListAdapter.java index c62fa8c..76dc10e 100644 --- a/main/src/cgeo/geocaching/ui/GPXListAdapter.java +++ b/main/src/cgeo/geocaching/ui/GPXListAdapter.java @@ -39,7 +39,7 @@ public class GPXListAdapter extends ArrayAdapter<File> { final File file = getItem(position); View v = rowView; - GPXListView holder = null; + GPXListView holder; if (v == null) { v = inflater.inflate(R.layout.gpx_item, null); diff --git a/main/src/cgeo/geocaching/utils/IObserver.java b/main/src/cgeo/geocaching/utils/IObserver.java new file mode 100644 index 0000000..c7842aa --- /dev/null +++ b/main/src/cgeo/geocaching/utils/IObserver.java @@ -0,0 +1,22 @@ +package cgeo.geocaching.utils; + +/** + * Observer interface. + * <p/> + * An observer will receive updates about the observed object (implementing the {@link ISubject} interface) + * through its {@link #update(T)} method. + * + * @param <T> + * the kind of data to observe + */ +public interface IObserver<T> { + + /** + * Called when an observed object has updated its data. + * + * @param data + * the updated data + */ + void update(final T data); + +} diff --git a/main/src/cgeo/geocaching/utils/ISubject.java b/main/src/cgeo/geocaching/utils/ISubject.java new file mode 100644 index 0000000..f332ee8 --- /dev/null +++ b/main/src/cgeo/geocaching/utils/ISubject.java @@ -0,0 +1,57 @@ +package cgeo.geocaching.utils; + +/** + * Interface for subjects objects. Those can be observed by objects implementing the {@link IObserver} interface. + * + * @param <T> + * the kind of data to observe + */ + +public interface ISubject<T> { + + /** + * Add an observer to the observers list. + * <p/> + * Observers will be notified with no particular order. + * + * @param observer + * the observer to add + * @return true if the observer has been added, false if it was present already + */ + public boolean addObserver(final IObserver<? super T> observer); + + /** + * Delete an observer from the observers list. + * + * @param observer + * the observer to remove + * @return true if the observer has been removed, false if it was not in the list of observers + */ + public boolean deleteObserver(final IObserver<? super T> observer); + + /** + * Number of observers currently observing the object. + * + * @return the number of observers + */ + public int sizeObservers(); + + /** + * Notify all the observers that new data is available. + * <p/> + * The {@link IObserver#update(T)} method of each observer will be called with no particular order. + * + * @param data + * the updated data + * @return true if at least one observer was notified, false if there were no observers + */ + public boolean notifyObservers(final T data); + + /** + * Clear the observers list. + * + * @return true if there were observers before calling this method, false if the observers list was empty + */ + public boolean clearObservers(); + +} diff --git a/main/src/cgeo/geocaching/utils/MemorySubject.java b/main/src/cgeo/geocaching/utils/MemorySubject.java new file mode 100644 index 0000000..c424528 --- /dev/null +++ b/main/src/cgeo/geocaching/utils/MemorySubject.java @@ -0,0 +1,45 @@ +package cgeo.geocaching.utils; + +/** + * Synchronized implementation of the {@link ISubject} interface with an added pull interface. + * + * @param <T> + * the kind of data to observe + */ +public class MemorySubject<T> extends Subject<T> { + + /** + * The latest version of the observed data. + * <p/> + * A child class implementation may want to set this field from its constructors, in case early observers request + * the data before it got a chance to get updated. Otherwise, <code>null</code> will be returned until updated + * data is available. + */ + private T memory; + + @Override + public synchronized boolean addObserver(final IObserver<? super T> observer) { + final boolean added = super.addObserver(observer); + if (added && memory != null) { + observer.update(memory); + } + return added; + } + + @Override + public synchronized boolean notifyObservers(final T data) { + memory = data; + return super.notifyObservers(data); + } + + /** + * Get the memorized version of the data. + * + * @return the initial data set by the subject (which may be <code>null</code>), + * or the updated data if it is available + */ + public synchronized T getMemory() { + return memory; + } + +} diff --git a/main/src/cgeo/geocaching/utils/Subject.java b/main/src/cgeo/geocaching/utils/Subject.java new file mode 100644 index 0000000..b1754cc --- /dev/null +++ b/main/src/cgeo/geocaching/utils/Subject.java @@ -0,0 +1,76 @@ +package cgeo.geocaching.utils; + +import java.util.LinkedHashSet; +import java.util.Set; + +/** + * Synchronized implementation of the {@link ISubject} interface. + * + * @param <T> + * the kind of data to observe + */ +public class Subject<T> implements ISubject<T> { + + /** + * Collection of observers. + */ + protected final Set<IObserver<? super T>> observers = new LinkedHashSet<IObserver<? super T>>(); + + @Override + public synchronized boolean addObserver(final IObserver<? super T> observer) { + final boolean added = observers.add(observer); + if (added && observers.size() == 1) { + onFirstObserver(); + } + return added; + } + + @Override + public synchronized boolean deleteObserver(final IObserver<? super T> observer) { + final boolean removed = observers.remove(observer); + if (removed && observers.isEmpty()) { + onLastObserver(); + } + return removed; + } + + @Override + public synchronized boolean notifyObservers(final T arg) { + final boolean nonEmpty = !observers.isEmpty(); + for (final IObserver<? super T> observer : observers) { + observer.update(arg); + } + return nonEmpty; + } + + @Override + public synchronized int sizeObservers() { + return observers.size(); + } + + @Override + public synchronized boolean clearObservers() { + final boolean nonEmpty = !observers.isEmpty(); + for (final IObserver<? super T> observer : observers) { + deleteObserver(observer); + } + return nonEmpty; + } + + /** + * Method called when the collection of observers goes from empty to non-empty. + * <p/> + * The default implementation does nothing and may be overwritten by child classes. + */ + protected void onFirstObserver() { + } + + /** + * Method called when the collection of observers goes from non-empty to empty. + * <p/> + * The default implementation does nothing and may be overwritten by child classes. + */ + protected void onLastObserver() { + } + +} diff --git a/main/src/com/viewpagerindicator/TitlePageIndicator.java b/main/src/com/viewpagerindicator/TitlePageIndicator.java index 248a96f..a181fed 100644 --- a/main/src/com/viewpagerindicator/TitlePageIndicator.java +++ b/main/src/com/viewpagerindicator/TitlePageIndicator.java @@ -686,7 +686,7 @@ public class TitlePageIndicator extends View implements PageIndicator { * @return The width of the view, honoring constraints from measureSpec */ private int measureWidth(int measureSpec) { - int result = 0; + int result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); @@ -705,7 +705,7 @@ public class TitlePageIndicator extends View implements PageIndicator { * @return The height of the view, honoring constraints from measureSpec */ private int measureHeight(int measureSpec) { - float result = 0; + float result; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); |
