code
stringlengths
3
1.18M
language
stringclasses
1 value
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import android.content.SharedPreferences; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; /** Responsible for providing an up-to-date location and compass direction */ @SuppressWarnings("deprecation") public class GeoFixProviderLive implements LocationListener, SensorListener, GeoFixProvider { private GeoFix mLocation; private final LocationManager mLocationManager; private float mAzimuth; /** A refresh is sent whenever a sensor changes */ private final ArrayList<Refresher> mObservers = new ArrayList<Refresher>(); private final SensorManager mSensorManager; private boolean mUseNetwork = true; private final SharedPreferences mSharedPreferences; public GeoFixProviderLive(LocationManager locationManager, SensorManager sensorManager, SharedPreferences sharedPreferences) { mLocationManager = locationManager; mSensorManager = sensorManager; mSharedPreferences = sharedPreferences; // mLocation = getLastKnownLocation(); //work in constructor.. } public GeoFix getLocation() { if (mLocation == null) { Location lastKnownLocation = getLastKnownLocation(); if (lastKnownLocation != null) mLocation = new GeoFix(lastKnownLocation); else mLocation = GeoFix.NO_FIX; } return mLocation; } public void addObserver(Refresher refresher) { if (!mObservers.contains(refresher)) mObservers.add(refresher); } private void notifyObservers() { for (Refresher refresher : mObservers) { refresher.refresh(); } } /** * Choose the better of two locations: If one location is newer and more * accurate, choose that. (This favors the gps). Otherwise, if one location * is newer, less accurate, but farther away than the sum of the two * accuracies, choose that. (This favors the network locator if you've * driven a distance and haven't been able to get a gps fix yet.) */ private static GeoFix choose(GeoFix oldLocation, GeoFix newLocation) { if (oldLocation == null) return newLocation; if (newLocation == null) return oldLocation; if (newLocation.getTime() > oldLocation.getTime()) { float distance = newLocation.distanceTo(oldLocation); // Log.d("GeoBeagle", "onLocationChanged distance="+distance + // " provider=" + newLocation.getProvider()); if (distance < 1) // doesn't take changing accuracy into account return oldLocation; // TODO: Handle network and gps different return newLocation; /* * if (newLocation.getAccuracy() <= oldLocation.getAccuracy()) * return newLocation; else if (oldLocation.distanceTo(newLocation) * >= oldLocation.getAccuracy() + newLocation.getAccuracy()) { * return newLocation; } */ } return oldLocation; } @Override public void onLocationChanged(Location location) { if (location == null) return; GeoFix chosen = choose(mLocation, new GeoFix(location)); if (chosen != mLocation) { mLocation = chosen; notifyObservers(); } } @Override public void onProviderDisabled(String provider) { Log.d("GeoBeagle", "onProviderDisabled(" + provider + ")"); } @Override public void onProviderEnabled(String provider) { Log.d("GeoBeagle", "onProviderEnabled(" + provider + ")"); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onAccuracyChanged(int sensor, int accuracy) { // Log.d("GeoBeagle", "onAccuracyChanged " + sensor + " accuracy " + // accuracy); } @Override public void onSensorChanged(int sensor, float[] values) { final float currentAzimuth = values[0]; if (Math.abs(currentAzimuth - mAzimuth) > 5) { // Log.d("GeoBeagle", "azimuth now " + sensor +", " + // currentAzimuth); mAzimuth = currentAzimuth; notifyObservers(); } } public void onResume() { mUseNetwork = mSharedPreferences.getBoolean("use-network-location", true); mSensorManager.registerListener(this, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); long minTime = 1000; // ms float minDistance = 1; // meters mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, this); if (mUseNetwork) mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, minTime, minDistance, this); onLocationChanged(getLastKnownLocation()); } public void onPause() { mSensorManager.unregisterListener(this); mLocationManager.removeUpdates(this); } public boolean isProviderEnabled() { return mLocationManager.isProviderEnabled("gps") || (mUseNetwork && mLocationManager .isProviderEnabled("network")); } private Location getLastKnownLocation() { Location gpsLocation = mLocationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (gpsLocation != null) return gpsLocation; if (mUseNetwork) return mLocationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); return null; } public float getAzimuth() { return mAzimuth; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import android.app.Activity; import android.app.Dialog; import android.content.res.Resources; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; /** Show a dialog to let the user edit the current filter * for which geocaches to display */ public class MenuActionEditFilter extends ActionStaticLabel implements MenuAction { private final Activity mActivity; private final FilterTypeCollection mFilterTypeCollection; private final CacheFilterUpdater mCacheFilterUpdater; private final Refresher mRefresher; private CacheFilter mFilter; public MenuActionEditFilter(Activity activity, CacheFilterUpdater cacheFilterUpdater, Refresher refresher, FilterTypeCollection filterTypeCollection, Resources resources) { super(resources, R.string.menu_edit_filter); mActivity = activity; mCacheFilterUpdater = cacheFilterUpdater; mRefresher = refresher; mFilterTypeCollection = filterTypeCollection; } @Override public String getLabel() { return mActivity.getResources().getString(R.string.menu_edit_filter); } private class DialogFilterGui implements CacheFilter.FilterGui { private Dialog mDialog; public DialogFilterGui(Dialog dialog) { mDialog = dialog; } @Override public boolean getBoolean(int id) { return ((CompoundButton)mDialog.findViewById(id)).isChecked(); } @Override public String getString(int id) { return ((EditText)mDialog.findViewById(id)).getText().toString(); } @Override public void setBoolean(int id, boolean value) { ((CompoundButton)mDialog.findViewById(id)).setChecked(value); } @Override public void setString(int id, String value) { ((EditText)mDialog.findViewById(id)).setText(value); } }; @Override public void act() { final Dialog dialog = new Dialog(mActivity); final DialogFilterGui gui = new DialogFilterGui(dialog); final OnClickListener mOnApply = new OnClickListener() { @Override public void onClick(View v) { mFilter.loadFromGui(gui); mFilter.saveToPreferences(); dialog.dismiss(); mCacheFilterUpdater.loadActiveFilter(); mRefresher.forceRefresh(); } }; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.filter); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireFavorites, R.id.CheckBoxForbidFavorites); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireFound, R.id.CheckBoxForbidFound); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireDNF, R.id.CheckBoxForbidDNF); mFilter = mFilterTypeCollection.getActiveFilter(); TextView title = (TextView)dialog.findViewById(R.id.TextFilterTitle); title.setText("Editing filter \"" + mFilter.getName() + "\""); mFilter.pushToGui(gui); Button apply = (Button) dialog.findViewById(R.id.ButtonApplyFilter); apply.setOnClickListener(mOnApply); dialog.show(); } private static final OnClickListener OnCheck = new OnClickListener() { @Override public void onClick(View v) { final CheckBox checkBox = (CheckBox)v; if (checkBox.isChecked()) ((CheckBox)checkBox.getTag()).setChecked(false); } }; /** Registers two checkboxes to be opposing -- * selecting one will unselect the other */ private static void SetOpposingCheckBoxes(Dialog dialog, int id1, int id2) { CheckBox checkBox1 = (CheckBox)dialog.findViewById(id1); CheckBox checkBox2 = (CheckBox)dialog.findViewById(id2); checkBox1.setTag(checkBox2); checkBox1.setOnClickListener(OnCheck); checkBox2.setTag(checkBox1); checkBox2.setOnClickListener(OnCheck); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.preferences.EditPreferences; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionSettings extends ActionStaticLabel implements MenuAction { private final Activity mActivity; public MenuActionSettings(Activity activity, Resources resources) { super(resources, R.string.menu_settings); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, EditPreferences.class)); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import android.app.Activity; import android.app.Dialog; import android.content.res.Resources; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; /** Show a popup dialog to let the user choose what filter to use */ public class MenuActionFilterListPopup extends ActionStaticLabel implements MenuAction { private final Activity mActivity; private final FilterTypeCollection mFilterTypeCollection; private final CacheFilterUpdater mCacheFilterUpdater; private final Refresher mRefresher; public MenuActionFilterListPopup(Activity activity, CacheFilterUpdater cacheFilterUpdater, Refresher refresher, FilterTypeCollection filterTypeCollection, Resources resources) { super(resources, R.string.menu_choose_filter); mActivity = activity; mCacheFilterUpdater = cacheFilterUpdater; mRefresher = refresher; mFilterTypeCollection = filterTypeCollection; } @Override public void act() { final Dialog dialog = new Dialog(mActivity); final RadioGroup radioGroup = new RadioGroup(mActivity); LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); final OnClickListener mOnSelect = new OnClickListener() { @Override public void onClick(View v) { int ix = radioGroup.getCheckedRadioButtonId(); CacheFilter cacheFilter = mFilterTypeCollection.get(ix); Log.d("GeoBeagle", "Setting active filter to " + cacheFilter.getName() + " with id " + cacheFilter.mId); mFilterTypeCollection.setActiveFilter(cacheFilter); dialog.dismiss(); mCacheFilterUpdater.loadActiveFilter(); mRefresher.forceRefresh(); } }; radioGroup.setOnClickListener(mOnSelect); for (int i = 0; i < mFilterTypeCollection.getCount(); i++) { CacheFilter cacheFilter = mFilterTypeCollection.get(i); RadioButton newRadioButton = new RadioButton(mActivity); newRadioButton.setOnClickListener(mOnSelect); newRadioButton.setText(cacheFilter.getName()); newRadioButton.setId(i); radioGroup.addView(newRadioButton, layoutParams); } int selected = mFilterTypeCollection.getIndexOf(mFilterTypeCollection. getActiveFilter()); radioGroup.check(selected); //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setTitle("Choose filter"); //dialog.setContentView(R.layout.filterlist); dialog.setContentView(radioGroup); //TextView title = (TextView)dialog.findViewById(R.id.TextFilterTitle); //title.setText(getLabel()); dialog.show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.searchonline.SearchOnlineActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionSearchOnline extends ActionStaticLabel implements MenuAction { private final Activity mActivity; public MenuActionSearchOnline(Activity activity, Resources resources) { super(resources, R.string.menu_search_online); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, SearchOnlineActivity.class)); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; /** Deletes all caches in the database */ public class MenuActionDeleteAll extends ActionStaticLabel implements MenuAction { private final DbFrontend mDbFrontend; private final CachesProviderDb mCachesToFlush; private final TitleUpdater mTitleUpdater; private final CacheListAdapter mCacheListAdapter; public MenuActionDeleteAll(DbFrontend dbFrontend, Resources resources, CachesProviderDb cachesToFlush, CacheListAdapter cacheListAdapter, TitleUpdater titleUpdater, int labelId) { super(resources, labelId); mDbFrontend = dbFrontend; mCachesToFlush = cachesToFlush; mCacheListAdapter = cacheListAdapter; mTitleUpdater = titleUpdater; } @Override public void act() { mDbFrontend.deleteAll(); mCachesToFlush.notifyOfDbChange(); //Reload the cache list from the database mTitleUpdater.refresh(); mCacheListAdapter.forceRefresh(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; public class MenuActionFromCacheAction implements MenuAction { private CacheAction mCacheAction; private Geocache mTarget; public MenuActionFromCacheAction(CacheAction cacheAction, Geocache target) { mCacheAction = cacheAction; mTarget = target; } @Override public void act() { mCacheAction.act(mTarget); } public String getLabel() { return mCacheAction.getLabel(mTarget); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; public interface CacheAction { public void act(Geocache cache); /** Returns the text to show to the user for this action. * The text is allowed to change depending on runtime circumstances. * @param geocache */ public String getLabel(Geocache geocache); }
Java
package com.google.code.geobeagle.actions; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** Adds a confirm dialog before carrying out the nested MenuAction */ public class MenuActionConfirm implements MenuAction { private final Activity mActivity; private final MenuAction mMenuAction; //May Builder only be used once? private final AlertDialog.Builder mBuilder; private final String mTitle; private final String mBody; public MenuActionConfirm(Activity activity, AlertDialog.Builder builder, MenuAction menuAction, String title, String body) { mActivity = activity; mBuilder = builder; mMenuAction = menuAction; mTitle = title; mBody = body; } private AlertDialog buildAlertDialog() { mBuilder.setTitle(mTitle); mBuilder.setMessage(mBody) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); mMenuAction.act(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = mBuilder.create(); alertDialog.setOwnerActivity(mActivity); return alertDialog; } @Override public void act() { AlertDialog alertDialog = buildAlertDialog(); alertDialog.show(); } @Override public String getLabel() { return mMenuAction.getLabel(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.prox.ProximityActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionProximity extends ActionStaticLabel implements CacheAction { private Activity mActivity; public CacheActionProximity(Activity activity, Resources resources) { super(resources, R.string.menu_proximity); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mActivity, ProximityActivity.class); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import android.content.res.Resources; public class ActionStaticLabel { private final Resources mResources; private final int mLabelId; public ActionStaticLabel(Resources resources, int labelId) { super(); mResources = resources; mLabelId = labelId; } public String getLabel() { return mResources.getString(mLabelId); } public String getLabel(Geocache geocache) { return getLabel(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; public interface MenuAction { public void act(); /** Returns the text to show to the user for this action. May change. */ public String getLabel(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; public class MenuActions { private ArrayList<MenuAction> mMenuActions = new ArrayList<MenuAction>(); public MenuActions() { } public MenuActions(MenuAction[] menuActions) { for (int ix = 0; ix < menuActions.length; ix++) { add(menuActions[ix]); } } public boolean act(int itemId) { if (itemId < 0 || itemId >= mMenuActions.size()) return false; mMenuActions.get(itemId).act(); return true; } public void add(MenuAction action) { mMenuActions.add(action); } /** Creates an Options Menu from the items in this MenuActions */ public boolean onCreateOptionsMenu(Menu menu) { if (mMenuActions.isEmpty()) { Log.w("GeoBeagle", "MenuActions.onCreateOptionsMenu: menu is empty, will not be shown"); return false; } menu.clear(); int ix = 0; for (MenuAction action : mMenuActions) { menu.add(0, ix, ix, action.getLabel()); ix++; } return true; } /** Give the menu items a chance to update the text */ public boolean onMenuOpened(Menu menu) { int ix = 0; for (MenuAction action : mMenuActions) { MenuItem item = menu.getItem(ix); String label = action.getLabel(); if (!item.getTitle().equals(label)) item.setTitle(label); ix++; } return true; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.database.CachesProviderDb; import java.util.List; //TODO: Rename class CacheFilterUpdater.. "reload cache list from cachefilter" public class CacheFilterUpdater { private final FilterTypeCollection mFilterTypeCollection; private final List<CachesProviderDb> mCachesProviderDb; public CacheFilterUpdater(FilterTypeCollection filterTypeCollection, List<CachesProviderDb> cachesProviderDb) { mCachesProviderDb = cachesProviderDb; mFilterTypeCollection = filterTypeCollection; } public void loadActiveFilter() { CacheFilter filter = mFilterTypeCollection.getActiveFilter(); //Log.d("GeoBeagle", "CacheFilterUpdater loading " + filter.mId); for (CachesProviderDb provider : mCachesProviderDb) { provider.setFilter(filter); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; public class CacheActionToggleFavorite implements CacheAction { private final DbFrontend mDbFrontend; private final CacheListAdapter mCacheList; private final CacheFilterUpdater mCacheFilterUpdater; public CacheActionToggleFavorite(DbFrontend dbFrontend, CacheListAdapter cacheList, CacheFilterUpdater cacheFilterUpdater) { mDbFrontend = dbFrontend; mCacheList = cacheList; mCacheFilterUpdater = cacheFilterUpdater; } @Override public void act(Geocache geocache) { boolean isFavorite = mDbFrontend.geocacheHasTag(geocache.getId(), Tags.FAVORITES); mDbFrontend.setGeocacheTag(geocache.getId(), Tags.FAVORITES, !isFavorite); mCacheFilterUpdater.loadActiveFilter(); mCacheList.forceRefresh(); } @Override public String getLabel(Geocache geocache) { boolean isFavorite = mDbFrontend.geocacheHasTag(geocache.getId(), Tags.FAVORITES); return isFavorite ? "Remove from Favorites" : "Add to Favorites"; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** Adds a confirm dialog before carrying out the nested CacheAction */ public class CacheActionConfirm implements CacheAction { private final Activity mActivity; private final CacheAction mCacheAction; //May Builder only be used once? private final AlertDialog.Builder mBuilder; private final String mTitle; private final String mBody; public CacheActionConfirm(Activity activity, AlertDialog.Builder builder, CacheAction cacheAction, String title, String body) { mActivity = activity; mBuilder = builder; mCacheAction = cacheAction; mTitle = title; mBody = body; } private AlertDialog buildAlertDialog(final Geocache cache) { final String title = String.format(mTitle, cache.getId()); final String message = String.format(mBody, cache.getId(), cache.getName()); mBuilder.setTitle(title); mBuilder.setMessage(message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); mCacheAction.act(cache); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = mBuilder.create(); alertDialog.setOwnerActivity(mActivity); return alertDialog; } @Override public void act(Geocache cache) { AlertDialog alertDialog = buildAlertDialog(cache); alertDialog.show(); } @Override public String getLabel(Geocache geocache) { return mCacheAction.getLabel(geocache); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.database.ICachesProvider; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView.AdapterContextMenuInfo; public class CacheContextMenu implements OnCreateContextMenuListener { private final ICachesProvider mCachesProvider; private final CacheAction mCacheActions[]; /** The geocache for which the menu was launched */ private Geocache mGeocache = null; public CacheContextMenu(ICachesProvider cachesProvider, CacheAction cacheActions[]) { mCachesProvider = cachesProvider; mCacheActions = cacheActions; } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; if (acmi.position > 0) { mGeocache = mCachesProvider.getCaches().get(acmi.position - 1); menu.setHeaderTitle(mGeocache.getId()); for (int ix = 0; ix < mCacheActions.length; ix++) { menu.add(0, ix, ix, mCacheActions[ix].getLabel(mGeocache)); } } } public boolean onContextItemSelected(MenuItem menuItem) { Log.d("GeoBeagle", "Context menu doing action " + menuItem.getItemId() + " = " + mCacheActions[menuItem.getItemId()].getClass().toString()); mCacheActions[menuItem.getItemId()].act(mGeocache); return true; } public Geocache getGeocache() { return mGeocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.CacheListActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionCacheList extends ActionStaticLabel implements MenuAction { private Activity mActivity; public MenuActionCacheList(Activity activity, Resources resources) { super(resources, R.string.menu_cache_list); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, CacheListActivity.class)); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.map.GeoMapActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; /** Show the map, centered around the current location */ public class MenuActionMap extends ActionStaticLabel implements MenuAction { private final GeoFixProvider mLocationControl; private final Activity mActivity; public MenuActionMap(Activity activity, GeoFixProvider locationControl, Resources resources) { super(resources, R.string.menu_map); mActivity = activity; mLocationControl = locationControl; } @Override public void act() { GeoFix location = mLocationControl.getLocation(); final Intent intent = new Intent(mActivity, GeoMapActivity.class); intent.putExtra("latitude", (float)location.getLatitude()); intent.putExtra("longitude", (float)location.getLongitude()); mActivity.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.prox.ProximityActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionProximity extends ActionStaticLabel implements MenuAction { Activity mActivity; public MenuActionProximity(Activity activity, Resources resources) { super(resources, R.string.menu_proximity); mActivity = activity; } @Override public void act() { final Intent intent = new Intent(mActivity, ProximityActivity.class); mActivity.startActivity(intent); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import java.util.Map; public class CacheActionAssignTags implements CacheAction { private final Activity mActivity; private final DbFrontend mDbFrontend; private final CacheListAdapter mCacheListAdapter; public CacheActionAssignTags(Activity activity, DbFrontend dbFrontend, CacheListAdapter cacheListAdapter) { mActivity = activity; mDbFrontend = dbFrontend; mCacheListAdapter = cacheListAdapter; } private boolean hasChanged = false; @Override public void act(final Geocache cache) { final Dialog dialog = new Dialog(mActivity); View rootView = mActivity.getLayoutInflater().inflate(R.layout.assign_tags, null); LinearLayout linearLayout = (LinearLayout)rootView.findViewById(R.id.AssignTagsLinearLayout); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); final OnClickListener mOnSelect = new OnClickListener() { @Override public void onClick(View v) { CheckBox checkbox = (CheckBox)v; int tagId = v.getId(); boolean checked = checkbox.isChecked(); Log.d("GeoBeagle", "Setting tag " + tagId + " to " + (checked?"true":"false")); mDbFrontend.setGeocacheTag(cache.getId(), tagId, checked); hasChanged = true; cache.flushIcons(); } }; final OnDismissListener onDismiss = new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (hasChanged) mCacheListAdapter.notifyDataSetChanged(); } }; dialog.setOnDismissListener(onDismiss); Map<Integer, String> allTags = Tags.GetAllTags(); for (Integer i : allTags.keySet()) { String tagName = allTags.get(i); boolean hasTag = mDbFrontend.geocacheHasTag(cache.getId(), i); CheckBox checkbox = new CheckBox(mActivity); checkbox.setChecked(hasTag); checkbox.setOnClickListener(mOnSelect); checkbox.setText(tagName); checkbox.setId(i); linearLayout.addView(checkbox, layoutParams); } //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setTitle("Assign tags to " + cache.getId()); dialog.setContentView(linearLayout); dialog.show(); } @Override public String getLabel(Geocache geocache) { return mActivity.getResources().getString(R.string.assign_tags); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.EditCacheActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionEdit extends ActionStaticLabel implements CacheAction { private final Activity mActivity; public CacheActionEdit(Activity activity, Resources resources) { super(resources, R.string.menu_edit_geocache); mActivity = activity; } @Override public void act(Geocache cache) { Intent intent = new Intent(mActivity, EditCacheActivity.class); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivityForResult(intent, 0); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; public class CacheActionDelete extends ActionStaticLabel implements CacheAction { private final CacheListAdapter mCacheListAdapter; private final DbFrontend mDbFrontend; private final TitleUpdater mTitleUpdater; private final CachesProviderDb mCachesToFlush; public CacheActionDelete(CacheListAdapter cacheListAdapter, TitleUpdater titleUpdater, DbFrontend dbFrontend, CachesProviderDb cachesToFlush, Resources resources) { super(resources, R.string.menu_delete_cache); mCacheListAdapter = cacheListAdapter; mTitleUpdater = titleUpdater; mDbFrontend = dbFrontend; mCachesToFlush = cachesToFlush; } @Override public void act(Geocache cache) { mDbFrontend.getCacheWriter().deleteCache(cache.getId()); mCachesToFlush.notifyOfDbChange(); //Reload the cache list from the database mTitleUpdater.refresh(); mCacheListAdapter.forceRefresh(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.content.res.Resources; public class CacheActionGoogleMaps extends ActionStaticLabel implements CacheAction { private final CacheActionViewUri mCacheActionViewUri; public CacheActionGoogleMaps(CacheActionViewUri cacheActionViewUri, Resources resources) { super(resources, R.string.menu_google_maps); mCacheActionViewUri = cacheActionViewUri; } @Override public void act(Geocache cache) { mCacheActionViewUri.act(cache); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.filterlist.FilterListActivity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; public class MenuActionFilterList extends ActionStaticLabel implements MenuAction { private final Context mContext; public MenuActionFilterList(Context context, Resources resources) { super(resources, R.string.menu_filterlist); mContext = context; } @Override public void act() { final Intent intent = new Intent(mContext, FilterListActivity.class); mContext.startActivity(intent); } @Override public String getLabel() { return mContext.getString(R.string.menu_filterlist); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.map.GeoMapActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionMap extends ActionStaticLabel implements CacheAction { Activity mActivity; public CacheActionMap(Activity activity, Resources resources) { super(resources, R.string.menu_cache_map); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mActivity, GeoMapActivity.class); intent.putExtra("latitude", (float)cache.getLatitude()); intent.putExtra("longitude", (float)cache.getLongitude()); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivity(intent); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; public class MenuActionClearTagNew implements MenuAction { private final DbFrontend mDbFrontend; private final GeocacheFactory mGeocacheFactory; private final CacheListAdapter mCacheListAdapter; public MenuActionClearTagNew(DbFrontend dbFrontend, GeocacheFactory geocacheFactory, CacheListAdapter cacheListAdapter) { mDbFrontend = dbFrontend; mGeocacheFactory = geocacheFactory; mCacheListAdapter = cacheListAdapter; } @Override public void act() { mDbFrontend.clearTagForAllCaches(Tags.NEW); mGeocacheFactory.flushCacheIcons(); mCacheListAdapter.notifyDataSetChanged(); } @Override public String getLabel() { return "Clear all 'new'"; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionRadar extends ActionStaticLabel implements CacheAction { Activity mActivity; public CacheActionRadar(Activity activity, Resources resources) { super(resources, R.string.radar); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent("com.google.android.radar.SHOW_RADAR"); intent.putExtra("latitude", (float)cache.getLatitude()); intent.putExtra("longitude", (float)cache.getLongitude()); mActivity.startActivity(intent); } @Override public String getLabel(Geocache geocache) { return mActivity.getResources().getString(R.string.radar); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.code.geobeagle.activity.main.intents.GeocacheToUri; import com.google.code.geobeagle.activity.main.intents.IntentFactory; import android.content.Intent; import android.content.res.Resources; public class CacheActionViewUri extends ActionStaticLabel implements CacheAction { private final GeoBeagle mGeoBeagle; private final GeocacheToUri mGeocacheToUri; private final IntentFactory mIntentFactory; public CacheActionViewUri(GeoBeagle geoBeagle, IntentFactory intentFactory, GeocacheToUri geocacheToUri, Resources resources) { super(resources, R.string.cache_page); mGeoBeagle = geoBeagle; mGeocacheToUri = geocacheToUri; mIntentFactory = intentFactory; } @Override public void act(Geocache cache) { mGeoBeagle.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, mGeocacheToUri.convert(cache))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.content.Context; import android.content.Intent; import android.content.res.Resources; public class CacheActionView extends ActionStaticLabel implements CacheAction { private final Context mContext; public CacheActionView(Context context, Resources resources) { super(resources, R.string.menu_view_geocache); mContext = context; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mContext, GeoBeagle.class); intent.setAction(GeocacheListController.SELECT_CACHE); intent.putExtra("geocacheId", cache.getId()); mContext.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; /** * Strategy to only invalidate/reload the list of caches when the bounds are * changed to outside the previous bounds. Also returns an empty list if the * count is greater than MAX_COUNT. */ public class CachesProviderLazyArea implements ICachesProviderArea { public static class CoordinateManager { private final double mExpandRatio; // The bounds of the loaded area private double mLatLow; private double mLatHigh; private double mLonLow; private double mLonHigh; public CoordinateManager(double expandRatio) { mExpandRatio = expandRatio; } boolean atLeastOneSideIsSmaller(double latLow, double lonLow, double latHigh, double lonHigh) { boolean fAtLeastOneSideIsSmaller = latLow < mLatLow || lonLow < mLonLow || latHigh > mLatHigh || lonHigh > mLonHigh; return fAtLeastOneSideIsSmaller; } boolean everySideIsBigger(double latLow, double lonLow, double latHigh, double lonHigh) { return latLow <= mLatLow && lonLow <= mLonLow && latHigh >= mLatHigh && lonHigh >= mLonHigh; } void expandCoordinates(double latLow, double lonLow, double latHigh, double lonHigh) { double latExpand = (latHigh - latLow) * mExpandRatio / 2.0; double lonExpand = (lonHigh - lonLow) * mExpandRatio / 2.0; mLatLow = latLow - latExpand; mLonLow = lonLow - lonExpand; mLatHigh = latHigh + latExpand; mLonHigh = lonHigh + lonExpand; } } /** Maximum number of caches to show */ public static final int MAX_COUNT = 1000; private final ICachesProviderArea mCachesProviderArea; private final CoordinateManager mCoordinateManager; /** If the user of this instance thinks the list has changed */ private boolean mHasChanged = true; private final PeggedCacheProvider mPeggedCacheProvider; public CachesProviderLazyArea(ICachesProviderArea cachesProviderArea, PeggedCacheProvider peggedCacheProvider, CoordinateManager coordinateManager) { mCachesProviderArea = cachesProviderArea; mPeggedCacheProvider = peggedCacheProvider; mCoordinateManager = coordinateManager; } @Override public void clearBounds() { mCachesProviderArea.clearBounds(); } @Override public AbstractList<Geocache> getCaches() { return getCaches(MAX_COUNT); } @Override public AbstractList<Geocache> getCaches(int maxCount) { // Reading one extra cache to see if there are too many AbstractList<Geocache> caches = mCachesProviderArea.getCaches(maxCount + 1); mCachesProviderArea.resetChanged(); return mPeggedCacheProvider.pegCaches(maxCount, caches); } public int getCount() { // Not perfectly efficient but it's not used anyway return getCaches().size(); } @Override public int getTotalCount() { return mCachesProviderArea.getTotalCount(); } @Override public boolean hasChanged() { return mHasChanged || mCachesProviderArea.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; mCachesProviderArea.resetChanged(); } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { boolean tooManyCaches = mPeggedCacheProvider.isTooManyCaches(); if (tooManyCaches && mCoordinateManager.everySideIsBigger(latLow, lonLow, latHigh, lonHigh)) { // The new bounds are strictly bigger but the old ones // already contained too many caches return; } if (tooManyCaches || mCoordinateManager.atLeastOneSideIsSmaller(latLow, lonLow, latHigh, lonHigh)) { mCoordinateManager.expandCoordinates(latLow, lonLow, latHigh, lonHigh); mCachesProviderArea.setBounds(mCoordinateManager.mLatLow, mCoordinateManager.mLonLow, mCoordinateManager.mLatHigh, mCoordinateManager.mLonHigh); mHasChanged = true; } } public void showToastIfTooManyCaches() { mPeggedCacheProvider.showToastIfTooManyCaches(); } public boolean tooManyCaches() { return mPeggedCacheProvider.isTooManyCaches(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Tags; import android.util.Log; public class OpenHelperDelegate { public void onCreate(ISQLiteDatabase db) { db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V11); db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10); db.execSQL(Database.SQL_CREATE_IDX_LATITUDE); db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE); db.execSQL(Database.SQL_CREATE_IDX_SOURCE); db.execSQL(Database.SQL_CREATE_CACHETAGS_TABLE_V12); db.execSQL(Database.SQL_CREATE_IDX_CACHETAGS); } public void onUpgrade(ISQLiteDatabase db, int oldVersion) { Log.i("GeoBeagle", "database onUpgrade oldVersion="+ oldVersion); if (oldVersion < 9) { db.execSQL(Database.SQL_DROP_CACHE_TABLE); db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V08); db.execSQL(Database.SQL_CREATE_IDX_LATITUDE); db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE); db.execSQL(Database.SQL_CREATE_IDX_SOURCE); } if (oldVersion < 10) { db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DELETE_ME); db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10); } if (oldVersion < 11) { db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CACHE_TYPE); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CONTAINER); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DIFFICULTY); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_TERRAIN); // This date has to precede 2000-01-01 (due to a bug in // CacheTagSqlWriter.java in v10). db.execSQL("UPDATE GPX SET ExportTime = \"1990-01-01\""); } if (oldVersion == 12) { db.execSQL("DROP TABLE IF EXISTS LABELS"); db.execSQL("DROP TABLE IF EXISTS CACHELABELS"); } if (oldVersion < 13) { Log.i("GeoBeagle", "Upgrading database to v13"); db.execSQL(Database.SQL_CREATE_TAGS_TABLE_V12); db.execSQL(Database.SQL_REPLACE_TAG, Tags.FOUND, "Found", true); db.execSQL(Database.SQL_REPLACE_TAG, Tags.DNF, "DNF", true); db.execSQL(Database.SQL_REPLACE_TAG, Tags.FAVORITES, "Favorites", true); db.execSQL(Database.SQL_CREATE_CACHETAGS_TABLE_V12); db.execSQL(Database.SQL_CREATE_IDX_CACHETAGS); } } }
Java
package com.google.code.geobeagle.database; public interface ICachesProviderCenter extends ICachesProvider { public void setCenter(double latitude, double longitude); }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.IPausable; import com.google.code.geobeagle.Refresher; import android.os.Handler; import android.util.Log; import java.util.AbstractList; /** Runs the decorated ICachesProviderCenter asynchronously. * setCenter() therefore takes an extra parameter. * * getCaches() and getCount() only returns pre-calculated data, * ensuring quick execution. * * hasChanged() will only return true when the thread has completed calculating * new (and differing) data. * * If a new center is set before the geocache list for the previous one finished * calculating, the calculation is finished and then the latest center is used * for a new calculation. */ public class CachesProviderCenterThread implements ICachesProvider, IPausable { private final ICachesProviderCenter mProvider; /** Only replaced from the extra thread */ private AbstractList<Geocache> mGeocaches = GeocacheListPrecomputed.EMPTY; private boolean mHasChanged = true; /** The coordinates for which mGeocaches is currently valid */ private double mCalculatedLatitude; private double mCalculatedLongitude; /** When current calculation is done, continue with these center coordinates */ private double mNextLatitude; private double mNextLongitude; private boolean mIsCalculating = false; private Thread mThread; /** Used to execute listener notification on the main thread */ private final Handler mHandler; private Refresher mObserver; private class CalculationThread extends Thread { private final double mLatitude; private final double mLongitude; public CalculationThread(double latitude, double longitude) { mLatitude = latitude; mLongitude = longitude; } @Override public void run() { Log.d("GeoBeagle", "Thread starting to calculate"); /* try { sleep(2000); } catch (InterruptedException e) { } Log.d("GeoBeagle", "Thread has slept for 2 sec"); */ mProvider.setCenter(mLatitude, mLongitude); AbstractList<Geocache> result = mProvider.getCaches(); if (result.equals(mGeocaches)) { Log.d("GeoBeagle", "Thread finished calculating: the list didn't change"); registerResult(mLatitude, mLongitude, mGeocaches, false); } else { Log.d("GeoBeagle", "Thread finished calculating: the list did change"); registerResult(mLatitude, mLongitude, result, true); } startCalculation(); } } /** Called by the extra thread to atomically update the state */ private synchronized void registerResult(double latitude, double longitude, AbstractList<Geocache> geocacheList, boolean changed) { mCalculatedLatitude = latitude; mCalculatedLongitude = longitude; mGeocaches = geocacheList; mIsCalculating = false; //Thread will die soon mThread = null; if (changed) { mHasChanged = true; mHandler.post(mObserverNotifier); } } public CachesProviderCenterThread(ICachesProviderCenter provider) { mProvider = provider; //Create here to assure that main thread gets to execute notifications: mHandler = new Handler(); } /** Start an asynchronous calculation and notify a refresher when the * list has changed (if it does change) */ public synchronized void setCenter(double latitude, double longitude, Refresher notifyAfter) { mNextLatitude = latitude; mNextLongitude = longitude; mObserver = notifyAfter; startCalculation(); } private synchronized void startCalculation() { if (mIsCalculating) return; //Will be started when current calculation finishes if (mIsPaused) return; if (mCalculatedLatitude == mNextLatitude && mCalculatedLongitude == mNextLongitude) { return; //No need to calculate again } Log.d("GeoBeagle", "startCalculation starts thread for coordinate diff latitude="+ (mNextLatitude-mCalculatedLatitude) + " longitude=" + (mNextLongitude-mCalculatedLongitude)); mIsCalculating = true; mThread = new CalculationThread(mNextLatitude, mNextLongitude); if (true) { //mThread.setPriority(); mThread.start(); } else { Log.d("GeoBeagle", "Running thread inline instead!"); mThread.run(); } } @Override public AbstractList<Geocache> getCaches() { //Don't calculate anything here -- just present previous results return mGeocaches; } @Override public int getCount() { //Don't calculate anything here -- just present previous results return mGeocaches.size(); } @Override public boolean hasChanged() { return mHasChanged; } @Override public synchronized void resetChanged() { mHasChanged = false; } //Run this on the main thread private final Runnable mObserverNotifier = new Runnable() { @Override public void run() { if (mObserver != null) mObserver.refresh(); } }; private boolean mIsPaused = false; public synchronized void onResume() { mIsPaused = false; startCalculation(); //There might be a pending update } public void onPause() { synchronized (this) { mIsPaused = true; mObserver = null; //Don't report any pending result } try { if (mThread != null) mThread.join(); } catch (InterruptedException e) { } } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import java.util.AbstractList; public class CachesProviderWaitForInit implements ICachesProviderCenter { private final ICachesProviderCenter mProvider; private boolean mInited = false; public CachesProviderWaitForInit(ICachesProviderCenter provider) { mProvider = provider; } @Override public void setCenter(double latitude, double longitude) { mInited = true; mProvider.setCenter(latitude, longitude); } @Override public AbstractList<Geocache> getCaches() { if (!mInited) return GeocacheListPrecomputed.EMPTY; return mProvider.getCaches(); } @Override public int getCount() { if (!mInited) { return 0; } return mProvider.getCount(); } //Could cause a bug if the first setCenter() doesn't make mProvider report hasChanged() @Override public boolean hasChanged() { if (!mInited) return false; return mProvider.hasChanged(); } @Override public void resetChanged() { if (mInited) { mProvider.resetChanged(); } } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; //TODO: Remove this class and replace by a mechanism to change CachesProvider in CacheListAdapter public class CachesProviderToggler implements ICachesProviderCenter { private ICachesProviderCenter mCachesProviderCenter; private ICachesProvider mCachesProviderAll; private boolean mNearest; private boolean mHasChanged; public CachesProviderToggler(ICachesProviderCenter cachesProviderCenter, ICachesProvider cachesProviderAll) { mCachesProviderCenter = cachesProviderCenter; mCachesProviderAll = cachesProviderAll; mNearest = true; mHasChanged = true; } public void toggle() { mNearest = !mNearest; mHasChanged = true; } public boolean isShowingNearest() { return mNearest; } @Override public AbstractList<Geocache> getCaches() { return (mNearest ? mCachesProviderCenter : mCachesProviderAll).getCaches(); } @Override public int getCount() { return (mNearest ? mCachesProviderCenter : mCachesProviderAll).getCount(); } @Override public void setCenter(double latitude, double longitude) { mCachesProviderCenter.setCenter(latitude, longitude); } @Override public boolean hasChanged() { return mHasChanged || (mNearest ? mCachesProviderCenter : mCachesProviderAll).hasChanged(); } @Override public void resetChanged() { mHasChanged = false; (mNearest ? mCachesProviderCenter : mCachesProviderAll).resetChanged(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.activity.main.Util; import com.google.code.geobeagle.database.DistanceAndBearing.IDistanceAndBearingProvider; import android.util.Log; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.WeakHashMap; /** Wraps another CachesProvider to make it sorted. Geocaches closer to * the provided center come first in the getCaches list. * Until setCenter has been called, the list will not be sorted. */ public class CachesProviderSorted implements ICachesProviderCenter, IDistanceAndBearingProvider { private final ICachesProvider mCachesProvider; private boolean mHasChanged = true; private double mLatitude; private double mLongitude; /** Value is null if the list needs to be re-sorted */ private AbstractList<Geocache> mSortedList = null; private DistanceComparator mDistanceComparator; private boolean isInitialized = false; private class DistanceComparator implements Comparator<Geocache> { public int compare(Geocache geocache1, Geocache geocache2) { final float d1 = getDistanceAndBearing(geocache1).getDistance(); final float d2 = getDistanceAndBearing(geocache2).getDistance(); if (d1 < d2) return -1; if (d1 > d2) return 1; return 0; } } public CachesProviderSorted(ICachesProvider cachesProvider) { mCachesProvider = cachesProvider; mDistanceComparator = new DistanceComparator(); isInitialized = false; } private WeakHashMap<Geocache, DistanceAndBearing> mDistances = new WeakHashMap<Geocache, DistanceAndBearing>(); public DistanceAndBearing getDistanceAndBearing(Geocache cache) { DistanceAndBearing d = mDistances.get(cache); if (d == null) { float distance = cache.getDistanceTo(mLatitude, mLongitude); float bearing = (float)GeoUtils.bearing(mLatitude, mLongitude, cache.getLatitude(), cache.getLongitude()); d = new DistanceAndBearing(cache, distance, bearing); mDistances.put(cache, d); } return d; } /** Updates mSortedList to a sorted version of the current underlying cache list*/ private void updateSortedList() { if (mSortedList != null && !mCachesProvider.hasChanged()) //No need to update return; final AbstractList<Geocache> unsortedList = mCachesProvider.getCaches(); ArrayList<Geocache> sortedList = new ArrayList<Geocache>(unsortedList); Collections.sort(sortedList, mDistanceComparator); mSortedList = new GeocacheListPrecomputed(sortedList); } @Override public AbstractList<Geocache> getCaches() { if (!isInitialized) { return mCachesProvider.getCaches(); } updateSortedList(); return mSortedList; } @Override public int getCount() { return mCachesProvider.getCount(); } @Override public boolean hasChanged() { return mHasChanged || mCachesProvider.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; if (mCachesProvider.hasChanged()) mSortedList = null; mCachesProvider.resetChanged(); } @Override public void setCenter(double latitude, double longitude) { if (isInitialized && Util.approxEquals(latitude, mLatitude) && Util.approxEquals(longitude, mLongitude)) return; //This only sets what position the caches are sorted against, //not which caches are selected for sorting! mLatitude = latitude; mLongitude = longitude; mHasChanged = true; isInitialized = true; mSortedList = null; mDistances.clear(); } public double getFurthestCacheDistance() { if (!isInitialized) { Log.e("GeoBeagle", "getFurthestCacheDistance called before setCenter"); return 0; } if (mSortedList == null || mCachesProvider.hasChanged()) { updateSortedList(); } if (mSortedList.size() == 0) return 0; return mSortedList.get(mSortedList.size()-1).getDistanceTo(mLatitude, mLongitude); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; public class DistanceAndBearing { public interface IDistanceAndBearingProvider { DistanceAndBearing getDistanceAndBearing(Geocache cache); } private Geocache mGeocache; private float mDistance; private float mBearing; public DistanceAndBearing(Geocache geocache, float distance, float bearing) { mGeocache = geocache; mDistance = distance; mBearing = bearing; } /** Which unit? */ public float getDistance() { return mDistance; } public float getBearing() { return mBearing; } public Geocache getGeocache() { return mGeocache; } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.main.GeoUtils; import java.util.AbstractList; /** Currently this class doesn't serve a purpose since the same functionality * is in GeoFixProviderLive. */ public class CachesProviderLazy implements ICachesProviderCenter { private final ICachesProviderCenter mProvider; /** The position mBufferedList reflects */ private double mBufferedLat; private double mBufferedLon; private AbstractList<Geocache> mBufferedList; /** The current center as asked for by the user of this object */ private double mLastLat; private double mLastLon; private long mLastUpdateTime; private boolean mHasChanged; private double mMinDistanceKm; private Clock mClock; private final long mMinTimeDiff; public CachesProviderLazy(ICachesProviderCenter provider, double minDistanceKm, long minTimeDiff, Clock clock) { mProvider = provider; mMinDistanceKm = minDistanceKm; mMinTimeDiff = minTimeDiff; mBufferedList = null; mClock = clock; } @Override public void setCenter(double latitude, double longitude) { mLastLat = latitude; mLastLon = longitude; if (mBufferedList == null) return; if (mClock.getCurrentTime() - mLastUpdateTime < mMinTimeDiff) return; if (GeoUtils.distanceKm(mBufferedLat, mBufferedLon, latitude, longitude) > mMinDistanceKm) { mProvider.setCenter(latitude, longitude); mBufferedList = null; } } @Override public AbstractList<Geocache> getCaches() { if (mBufferedList == null) { mBufferedList = mProvider.getCaches(); mProvider.resetChanged(); mLastUpdateTime = mClock.getCurrentTime(); } return mBufferedList; } @Override public int getCount() { return getCaches().size(); } @Override public boolean hasChanged() { if (mHasChanged) return true; //Update mHasChanged if (mClock.getCurrentTime() - mLastUpdateTime >= mMinTimeDiff) { if (GeoUtils.distanceKm(mBufferedLat, mBufferedLon, mLastLat, mLastLon) > mMinDistanceKm) mHasChanged = true; else mHasChanged = mProvider.hasChanged(); } return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import android.util.Log; import java.util.AbstractList; /** * Finds the caches that are closest to a certain point. */ public class CachesProviderCount implements ICachesProviderCenter { private static final double MAX_RADIUS = 1; //180; /** Maximum number of times a search is allowed to call the underlying * CachesProvider before yielding a best-effort result */ public static final int MAX_ITERATIONS = 10; private static final float DISTANCE_MULTIPLIER = 1.8f; //1.414f; private ICachesProviderArea mCachesProviderArea; private CachesProviderRadius mCachesProviderRadius; /** The least acceptable number of caches */ private int mMinCount; /* The max acceptable number of caches */ private int mMaxCount; private double mRadius; private AbstractList<Geocache> mCaches; /** Number of caches within mRadius */ private int mCount; /** True if mCount has been calculated for the current values */ private boolean mIsCountValid; /** Used for hasChanged() / setChanged() */ private boolean mHasChanged = true; public CachesProviderCount(ICachesProviderArea area, int minCount, int maxCount) { mCachesProviderArea = area; mCachesProviderRadius = new CachesProviderRadius(area); mMinCount = minCount; mMaxCount = maxCount; mRadius = 0.04; mIsCountValid = false; } @Override public void setCenter(double latitude, double longitude) { mCachesProviderRadius.setCenter(latitude, longitude); } @Override public AbstractList<Geocache> getCaches() { if (mCachesProviderRadius.hasChanged()) { mCaches = null; mIsCountValid = false; //TODO: Is this test fast enough to be worth the effort? int total = mCachesProviderArea.getTotalCount(); if (total <= mMaxCount) { Log.d("GeoBeagle", "CachesProviderCount.getCaches: Total number is few enough"); mCachesProviderArea.clearBounds(); mCaches = mCachesProviderArea.getCaches(); mCount = total; mIsCountValid = true; mCachesProviderRadius.resetChanged(); return mCaches; } } if (mCaches != null) return mCaches; if (!mIsCountValid) { Clock clock = new Clock(); long start = clock.getCurrentTime(); findRadius(mRadius); Log.d("GeoBeagle", "CachesProviderCount calculated in " + (clock.getCurrentTime()-start) + " ms"); mIsCountValid = true; } mCachesProviderRadius.setRadius(mRadius); mCaches = mCachesProviderRadius.getCaches(); mCachesProviderRadius.resetChanged(); return mCaches; } @Override public int getCount() { if (!mIsCountValid || mCachesProviderRadius.hasChanged()) { findRadius(mRadius); mIsCountValid = true; mCachesProviderRadius.resetChanged(); } return mCount; } private int countHitsUsingRadius(double radius) { mCachesProviderRadius.setRadius(radius); return mCachesProviderRadius.getCount(); } /** * @param radiusToTry Starting radius (in degrees) in search * @return Radius setting that satisfy mMinCount <= count <= mMaxCount */ private void findRadius(double radiusToTry) { int count = countHitsUsingRadius(radiusToTry); int iterationsLeft = MAX_ITERATIONS - 1; Log.d("GeoBeagle", "CachesProviderCount first count = " + count); if (count > mMaxCount) { while (count > mMaxCount && iterationsLeft > 1) { radiusToTry /= DISTANCE_MULTIPLIER; count = countHitsUsingRadius(radiusToTry); iterationsLeft -= 1; Log.d("GeoBeagle", "CachesProviderCount search inward count = " + count); } } else if (count < mMinCount) { while (count < mMinCount && radiusToTry < MAX_RADIUS / DISTANCE_MULTIPLIER && iterationsLeft > 1) { radiusToTry *= DISTANCE_MULTIPLIER; count = countHitsUsingRadius(radiusToTry); iterationsLeft -= 1; Log.d("GeoBeagle", "CachesProviderCount search outward count = " + count); } } if (count < mMinCount && iterationsLeft > 0) { findWithinLimits(radiusToTry, radiusToTry * DISTANCE_MULTIPLIER, iterationsLeft); } else if (count > mMaxCount && iterationsLeft > 0) { findWithinLimits(radiusToTry / DISTANCE_MULTIPLIER, radiusToTry, iterationsLeft); } else { mCount = count; mRadius = radiusToTry; } } private void findWithinLimits(double minRadius, double maxRadius, int iterationsLeft) { double radiusToTry = (minRadius + maxRadius) / 2.0; int count = countHitsUsingRadius(radiusToTry); if (count <= mMaxCount && count >= mMinCount) { Log.d("GeoBeagle", "CachesProviderCount.findWithinLimits: Found count = " + count); mCount = count; mRadius = radiusToTry; return; } if (iterationsLeft <= 1) { Log.d("GeoBeagle", "CachesProviderCount.findWithinLimits: Giving up with count = " + count); mCount = count; mRadius = radiusToTry; return; } if (count > mMaxCount) { findWithinLimits(minRadius, radiusToTry, iterationsLeft - 1); return; } findWithinLimits(radiusToTry, maxRadius, iterationsLeft - 1); } @Override public boolean hasChanged() { return mHasChanged || mCachesProviderRadius.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; mCachesProviderRadius.resetChanged(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; public class CachesProviderRadius implements ICachesProviderCenter { private ICachesProviderArea mCachesProviderArea; private double mLatitude; private double mLongitude; private double mDegrees; public CachesProviderRadius(ICachesProviderArea area) { mCachesProviderArea = area; } @Override public AbstractList<Geocache> getCaches() { return mCachesProviderArea.getCaches(); } @Override public int getCount() { return mCachesProviderArea.getCount(); } @Override public boolean hasChanged() { return mCachesProviderArea.hasChanged(); } @Override public void resetChanged() { mCachesProviderArea.resetChanged(); } public void setRadius(double radius) { mDegrees = radius; updateBounds(); } @Override public void setCenter(double latitude, double longitude) { mLatitude = latitude; mLongitude = longitude; updateBounds(); } private void updateBounds() { double latLow = mLatitude - mDegrees; double latHigh = mLatitude + mDegrees; double lonLow = mLongitude - mDegrees; double lonHigh = mLongitude + mDegrees; /* double lat_radians = Math.toRadians(mLatitude); double cos_lat = Math.cos(lat_radians); double lonLow = Math.max(-180, mLongitude - mDegrees / cos_lat); double lonHigh = Math.min(180, mLongitude + mDegrees / cos_lat); */ mCachesProviderArea.setBounds(latLow, lonLow, latHigh, lonHigh); } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; /** Interface to access a subset of the cache database. * Used to form a Decorator pattern. */ public interface ICachesProvider { /** Returns true if the result of getCaches() may have changed since the * last call to resetChanged() */ public boolean hasChanged(); /** Reset the change flag (never done from within the class) */ public void resetChanged(); public int getCount(); /** If the count is bigger than maxRelevantCount, the implementation may * return maxRelevantCount if that is more efficient. */ //public int getCount(int maxRelevantCount); /** The returned list is considered immutable */ public AbstractList<Geocache> getCaches(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheListLazy; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.database.DatabaseDI.GeoBeagleSqliteOpenHelper; import com.google.code.geobeagle.database.DatabaseDI.SQLiteWrapper; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.AbstractList; import java.util.ArrayList; /** * Represents the front-end to access a database. It takes * responsibility to open and close the actual database connection without * involving the clients of this class. */ public class DbFrontend { private Context mContext; private GeoBeagleSqliteOpenHelper mOpenHelper; private boolean mIsDatabaseOpen; private CacheWriter mCacheWriter; private ISQLiteDatabase mDatabase; private final GeocacheFactory mGeocacheFactory; private final Clock mClock = new Clock(); /** The total number of geocaches and waypoints in the database. * -1 means not initialized */ private int mTotalCacheCount = -1; private SourceNameTranslator mSourceNameTranslator; private SQLiteWrapper mSqliteWrapper; private static final String[] READER_COLUMNS = new String[] { "Latitude", "Longitude", "Id", "Description", "Source", "CacheType", "Difficulty", "Terrain", "Container" }; public DbFrontend(Context context, GeocacheFactory geocacheFactory) { mContext = context; mIsDatabaseOpen = false; mGeocacheFactory = geocacheFactory; mSourceNameTranslator = new SourceNameTranslator(); } //TODO: Redesign the threads so synchronized isn't needed for database access public synchronized void openDatabase() { if (mIsDatabaseOpen) return; //Log.d("GeoBeagle", "DbFrontend.openDatabase()"); mIsDatabaseOpen = true; mOpenHelper = new GeoBeagleSqliteOpenHelper(mContext); final SQLiteDatabase sqDb = mOpenHelper.getReadableDatabase(); mDatabase = new DatabaseDI.SQLiteWrapper(sqDb); mSqliteWrapper = mOpenHelper.getWritableSqliteWrapper(); } public synchronized void closeDatabase() { if (!mIsDatabaseOpen) return; //Log.d("GeoBeagle", "DbFrontend.closeDatabase()"); mIsDatabaseOpen = false; mOpenHelper.close(); mCacheWriter = null; mDatabase = null; } public AbstractList<Geocache> loadCachesPrecomputed(String where) { return loadCachesPrecomputed(where, -1); } /** If 'where' is null, returns all caches * @param maxResults if <= 0, means no limit */ public AbstractList<Geocache> loadCachesPrecomputed(String where, int maxResults) { openDatabase(); String limit = null; if (maxResults > 0) { limit = "0, " + maxResults; } long start = mClock.getCurrentTime(); //CacheReaderCursor cursor = mCacheReader.open(where, limit); Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, READER_COLUMNS, where, null, null, null, limit); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Geocache> geocaches = new ArrayList<Geocache>(); do { Geocache geocache = mGeocacheFactory.fromCursor(cursor, mSourceNameTranslator); geocaches.add(geocache); } while (cursor.moveToNext()); cursor.close(); Log.d("GeoBeagle", "DbFrontend.loadCachesPrecomputed took " + (mClock.getCurrentTime()-start) + " ms (loaded " + geocaches.size() + " caches)"); return new GeocacheListPrecomputed(geocaches); } /** If 'where' is null, returns all caches */ public AbstractList<Geocache> loadCaches(String where) { return loadCaches(where, -1); } /** If 'where' is null, returns all caches. * Loads the caches when first used, not from this method. * @param maxResults if <= 0, means no limit */ public AbstractList<Geocache> loadCaches(String where, int maxResults) { openDatabase(); String limit = null; if (maxResults > 0) { limit = "0, " + maxResults; } long start = mClock.getCurrentTime(); final String fields[] = { "Id" }; Cursor cursor = mDatabase.query(Database.TBL_CACHES, fields, where, null, null, null, limit); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Object> idList = new ArrayList<Object>(); if (cursor != null) { do { idList.add(cursor.getString(0)); } while (cursor.moveToNext()); cursor.close(); } Log.d("GeoBeagle", "DbFrontend.loadCachesLazy took " + (mClock.getCurrentTime()-start) + " ms (loaded " + idList.size() + " caches)"); return new GeocacheListLazy(this, idList); } /** @param sqlQuery A complete SQL query to be executed. * The query must return the id's of geocaches. */ public AbstractList<Geocache> loadCachesRaw(String sqlQuery) { openDatabase(); long start = mClock.getCurrentTime(); Cursor cursor = mDatabase.rawQuery(sqlQuery, new String[]{} ); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Object> idList = new ArrayList<Object>(); do { idList.add(cursor.getString(0)); } while (cursor.moveToNext()); cursor.close(); Log.d("GeoBeagle", "DbFrontend.loadCachesRaw took " + (mClock.getCurrentTime()-start) + " ms to load " + idList.size() + " caches from query " + sqlQuery); return new GeocacheListLazy(this, idList); } /** @return null if the cache id is not in the database */ public Geocache loadCacheFromId(String id) { Geocache loadedGeocache = mGeocacheFactory.getFromId(id); if (loadedGeocache != null) { return loadedGeocache; } openDatabase(); Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, READER_COLUMNS, "Id='"+id+"'", null, null, null, null); if (!cursor.moveToFirst()) { cursor.close(); return null; } Geocache geocache = mGeocacheFactory.fromCursor(cursor, mSourceNameTranslator); cursor.close(); return geocache; } public CacheWriter getCacheWriter() { if (mCacheWriter != null) return mCacheWriter; openDatabase(); mCacheWriter = DatabaseDI.createCacheWriter(mDatabase, mGeocacheFactory, this); return mCacheWriter; } private int countAll() { if (mTotalCacheCount != -1) return mTotalCacheCount; openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor; countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES, null); countCursor.moveToFirst(); mTotalCacheCount = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.countAll took " + (mClock.getCurrentTime()-start) + " ms (" + mTotalCacheCount + " caches)"); return mTotalCacheCount; } /** If 'where' is empty, returns the total number of caches */ public int count(String where) { if (where == null || where.equals("")) return countAll(); openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES + " WHERE " + where, null); countCursor.moveToFirst(); int count = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.count took " + (mClock.getCurrentTime()-start) + " ms (" + count + " caches)"); return count; } /** 'sql' must be a complete SQL query that returns a single row * with the result in the first column */ public int countRaw(String sql) { openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor = mDatabase.rawQuery(sql, null); countCursor.moveToFirst(); int count = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.countRaw took " + (mClock.getCurrentTime()-start) + " ms (" + count + " caches)"); return count; } public void flushTotalCount() { mTotalCacheCount = -1; } public boolean geocacheHasTag(CharSequence geocacheId, int tagId) { if (geocacheId == null) //Work-around for unexplained crash return false; openDatabase(); if (mDatabase == null) { //TODO: Remove. This only occurs when there's a //thread interleaving bug which seems to be fixed. Log.e("GeoBeagle", "DbFrontend.geocacheHasTag: mDatabase=null"); return false; } Cursor cursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHETAGS + " WHERE CacheId='" + geocacheId + "' AND TagId=" + tagId, null); if (cursor == null) { return false; } cursor.moveToFirst(); int count = cursor.getInt(0); cursor.close(); return (count > 0); } /** Sets or clear a tag for a geocache */ public void setGeocacheTag(CharSequence geocacheId, int tagId, boolean set) { openDatabase(); //Log.d("GeoBeagle", "setGeocacheTag(" + geocacheId + ", " + tagId // + ", " + (set?"true":"false")+ ")"); if (set) mSqliteWrapper.execSQL(Database.SQL_REPLACE_CACHETAG, geocacheId, tagId); else mSqliteWrapper.execSQL(Database.SQL_DELETE_CACHETAG, geocacheId, tagId); } public void clearTagForAllCaches(int tag) { openDatabase(); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_TAGS, tag); mGeocacheFactory.flushCacheIcons(); //The ones with 'tag' would be enough } public void deleteAll() { Log.i("GeoBeagle", "DbFrontend.deleteAll()"); clearTagForAllCaches(Tags.LOCKED_FROM_OVERWRITING); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_CACHES); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_GPX); mGeocacheFactory.flushCache(); mTotalCacheCount = 0; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.GeocacheFactory.Source; public class SourceNameTranslator { public Source sourceNameToSourceType(String sourceName) { if (sourceName.equals("intent")) return Source.WEB_URL; else if (sourceName.equals("mylocation")) return Source.MY_LOCATION; else if (sourceName.toLowerCase().endsWith((".loc"))) return Source.LOC; return Source.GPX; } public String sourceTypeToSourceName(Source source, String sourceName) { if (source == Source.MY_LOCATION) return "mylocation"; else if (source == Source.WEB_URL) return "intent"; return sourceName; } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; public interface ICachesProviderArea extends ICachesProvider { void setBounds(double latLow, double lonLow, double latHigh, double lonHigh); /** @param maxResults If bigger than zero, the result may be limited to * this number if there is a performance gain. */ AbstractList<Geocache> getCaches(int maxResults); /** @return The number of caches returned if there aren't any bounds. */ int getTotalCount(); void clearBounds(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.IToaster; import android.util.Log; import java.util.AbstractList; public class PeggedCacheProvider { /** True if the last getCaches() was capped because too high cache count */ private boolean mTooManyCaches = false; private final IToaster mOneTimeToaster; public PeggedCacheProvider(IToaster toaster) { mOneTimeToaster = toaster; } AbstractList<Geocache> pegCaches(int maxCount, AbstractList<Geocache> caches) { mTooManyCaches = (caches.size() > maxCount); if (mTooManyCaches) { return GeocacheListPrecomputed.EMPTY; } return caches; } private void logStack() { StackTraceElement[] stackTrace = new Exception().getStackTrace(); for (StackTraceElement e : stackTrace) { Log.d("GeoBeagle", "stack: " + " " + e.getClassName() + ":" + e.getMethodName() + "[" + e.getLineNumber() + "]"); } } void showToastIfTooManyCaches() { mOneTimeToaster.showToast(mTooManyCaches); } public boolean isTooManyCaches() { return mTooManyCaches; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.main.Util; /** * @author sng */ public class CacheWriter { public static final String SQLS_CLEAR_EARLIER_LOADS[] = { Database.SQL_DELETE_OLD_CACHES, Database.SQL_DELETE_OLD_GPX, Database.SQL_RESET_DELETE_ME_CACHES, Database.SQL_RESET_DELETE_ME_GPX }; private final SourceNameTranslator mDbToGeocacheAdapter; private final ISQLiteDatabase mSqlite; private final GeocacheFactory mGeocacheFactory; private final DbFrontend mDbFrontend; CacheWriter(ISQLiteDatabase sqlite, DbFrontend dbFrontend, SourceNameTranslator dbToGeocacheAdapter, GeocacheFactory geocacheFactory) { mSqlite = sqlite; mDbToGeocacheAdapter = dbToGeocacheAdapter; mGeocacheFactory = geocacheFactory; mDbFrontend = dbFrontend; } public void clearCaches(String source) { mGeocacheFactory.flushCache(); mDbFrontend.flushTotalCount(); mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source); } /** * Deletes any cache/gpx entries marked delete_me, then marks all remaining * gpx-based caches, and gpx entries with delete_me = 1. */ public void clearEarlierLoads() { for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) { mSqlite.execSQL(sql); } } public void deleteCache(CharSequence id) { mGeocacheFactory.flushGeocache(id); mDbFrontend.flushTotalCount(); mSqlite.execSQL(Database.SQL_DELETE_CACHE, id); } /** Checks if the geocache is different from the previously existing one. * @return True if the geocache was updated in the database. */ public boolean conditionallyWriteCache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container) { Geocache geocache = mDbFrontend.loadCacheFromId(id.toString()); if (geocache != null && geocache.getName().equals(name) && Util.approxEquals(geocache.getLatitude(), latitude) && Util.approxEquals(geocache.getLongitude(), longitude) && geocache.getSourceType().equals(sourceType) && geocache.getSourceName().equals(sourceName) && geocache.getCacheType() == cacheType && geocache.getDifficulty() == difficulty && geocache.getTerrain() == terrain && geocache.getContainer() == container) return false; /* if (geocache != null) { if (!geocache.getName().equals(name)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of name"); if (!Util.approxEquals(geocache.getLatitude(), latitude)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of lat"); if (!Util.approxEquals(geocache.getLongitude(), longitude)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of long"); if (!geocache.getSourceType().equals(sourceType)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of sourceType"); if (!geocache.getSourceName().equals(sourceName)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of sourceName"); if (geocache.getCacheType() != cacheType) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of type"); if (geocache.getDifficulty() != difficulty) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of diff"); if (geocache.getTerrain() != terrain) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of terrain"); if (geocache.getContainer() != container) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of container"); } else { Log.d("GeoBeagle", "CacheWriter creating cache "+id); } */ insertAndUpdateCache(id, name, latitude, longitude, sourceType, sourceName, cacheType, difficulty, terrain, container); return true; } /** Unconditionally update the geocache in the database */ public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container) { mGeocacheFactory.flushGeocache(id); mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double( longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName), cacheType.toInt(), difficulty, terrain, container); } public void updateTag(CharSequence id, int tag, boolean set) { mDbFrontend.setGeocacheTag(id, tag, set); } public boolean isLockedFromUpdating(CharSequence id) { return mDbFrontend.geocacheHasTag(id, Tags.LOCKED_FROM_OVERWRITING); } /** * Return True if the gpx is already loaded. Mark this gpx and its caches in * the database to protect them from being nuked when the load is complete. * * @param gpxName * @param gpxTime * @return */ public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) { // TODO:countResults is slow; replace with a query, and moveToFirst. boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX, Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0; if (gpxAlreadyLoaded) { mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName); mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName); } return gpxAlreadyLoaded; } public void startWriting() { mSqlite.beginTransaction(); } public void stopWriting() { // TODO: abort if no writes--otherwise sqlite is unhappy. mSqlite.setTransactionSuccessful(); mSqlite.endTransaction(); } public void writeGpx(String gpxName, String pocketQueryExportTime) { mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import android.database.Cursor; public interface ISQLiteDatabase { void beginTransaction(); void close(); int countResults(String table, String sql, String... args); void endTransaction(); void execSQL(String s, Object... bindArg1); Cursor query(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit, String... selectionArgs); Cursor rawQuery(String string, String[] object); void setTransactionSuccessful(); boolean isOpen(); }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.main.Util; import java.util.AbstractList; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** Uses a DB to fetch the caches within a defined region, or all caches if no * bounds were specified */ public class CachesProviderDb implements ICachesProviderArea { private DbFrontend mDbFrontend; private double mLatLow; private double mLonLow; private double mLatHigh; private double mLonHigh; /** The complete SQL query for the current coordinates and settings, * except from 'SELECT x'. If null, mSql needs to be re-calculated. */ private String mSql = null; private AbstractList<Geocache> mCaches; private boolean mHasChanged = true; private boolean mHasLimits = false; /** The 'where' part of the SQL clause that comes from the active CacheFilter */ private String mFilter = ""; /** The tag used for filtering. Tags.NULL means any tag allowed. */ private Set<Integer> mRequiredTags = new HashSet<Integer>(); private Set<Integer> mForbiddenTags = new HashSet<Integer>(); /** If greater than zero, this is the max number that mCaches * was allowed to contain when loaded. (This limit can change on subsequent loads) */ private int mCachesCappedToCount = 0; public CachesProviderDb(DbFrontend dbFrontend) { mDbFrontend = dbFrontend; } /** @param start is prepended if there are any parts */ /* private static String BuildConjunction(String start, List<String> parts) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (String part : parts) { if (first) { buffer.append(start); first = false; } else { buffer.append(" AND "); } buffer.append(part); } return buffer.toString(); } */ /** Returns a complete SQL query except from 'SELECT x' */ private String getSql() { if (mSql != null) return mSql; ArrayList<String> where = new ArrayList<String>(4); if (mHasLimits) { where.add("Latitude >= " + mLatLow + " AND Latitude < " + mLatHigh + " AND Longitude >= " + mLonLow + " AND Longitude < " + mLonHigh); } if (!mFilter.equals("")) where.add(mFilter); String join = ""; if (mForbiddenTags.size() > 0) { StringBuffer forbidden = new StringBuffer(); boolean first = true; for (Integer tagId : mForbiddenTags) { if (first) { first = false; } else { forbidden.append(" or "); } forbidden.append("TagId=" + tagId); } join = " left outer join (select CacheId from cachetags where " + forbidden + ") as FoundTags on caches.Id = FoundTags.CacheId"; where.add("FoundTags.CacheId is NULL"); } StringBuffer tables = new StringBuffer("FROM CACHES"); int ix = 1; for (Integer tagId : mRequiredTags) { String table = "tags" + ix; tables.append(", CACHETAGS " + table); where.add(table+".TagId=" + tagId + " AND " + table + ".CacheId=Id"); ix++; } StringBuffer completeSql = tables; //new StringBuffer(tables); completeSql.append(join); boolean first = true; for (String part : where) { if (first) { completeSql.append(" WHERE "); first = false; } else { completeSql.append(" AND "); } completeSql.append(part); } mSql = completeSql.toString(); //Log.d("GeoBeagle", "CachesProviderDb created sql " + mSql); return mSql; } @Override public AbstractList<Geocache> getCaches() { if (mCaches == null || mCachesCappedToCount > 0) { mCaches = mDbFrontend.loadCachesRaw("SELECT Id " + getSql()); } return mCaches; } @Override public AbstractList<Geocache> getCaches(int maxResults) { if (mCaches == null || (mCachesCappedToCount > 0 && mCachesCappedToCount < maxResults)) { mCaches = mDbFrontend.loadCachesRaw("SELECT Id " + getSql() + " LIMIT 0, " + maxResults); if (mCaches.size() == maxResults) mCachesCappedToCount = maxResults; else //The cap didn't limit the search result mCachesCappedToCount = 0; } return mCaches; } @Override public int getCount() { if (mCaches == null || mCachesCappedToCount > 0) { return mDbFrontend.countRaw("SELECT COUNT(*) " + getSql()); } return mCaches.size(); } @Override public void clearBounds() { if (!mHasLimits) return; mHasLimits = false; mCaches = null; //Flush old caches mSql = null; mHasChanged = true; } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { if (Util.approxEquals(latLow, mLatLow) && Util.approxEquals(latHigh, mLatHigh) && Util.approxEquals(lonLow, mLonLow) && Util.approxEquals(lonHigh, mLonHigh)) { return; } mLatLow = latLow; mLatHigh = latHigh; mLonLow = lonLow; mLonHigh = lonHigh; mCaches = null; //Flush old caches mSql = null; mHasChanged = true; mHasLimits = true; } @Override public boolean hasChanged() { return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } /** Tells this class that the contents in the database have changed. * The cached list isn't reliable any more. */ public void notifyOfDbChange() { mCaches = null; mHasChanged = true; } public void setFilter(CacheFilter cacheFilter) { String newFilter = cacheFilter.getSqlWhereClause(); Set<Integer> newTags = cacheFilter.getRequiredTags(); Set<Integer> newForbiddenTags = cacheFilter.getForbiddenTags(); if (newFilter.equals(mFilter) && newTags.equals(mRequiredTags) && newForbiddenTags.equals(mForbiddenTags)) return; mHasChanged = true; mFilter = newFilter; mRequiredTags = newTags; mForbiddenTags = newForbiddenTags; mSql = null; //Flush mCaches = null; //Flush old caches } public int getTotalCount() { return mDbFrontend.count(mFilter); } }
Java
package com.google.code.geobeagle; import android.location.Location; /** Wrapper for the class android.location.Location that can't be instantiated directly */ public class GeoFix { public static final GeoFix NO_FIX = new GeoFix(0f, 0f, 0d, 0d, 0L, ""); private final float mAccuracy; private final double mAltitude; private final double mLatitude; private final double mLongitude; private final long mTime; private final String mProvider; public GeoFix(Location location) { mAccuracy = location.getAccuracy(); mAltitude = location.getAltitude(); mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); mTime = location.getTime(); mProvider = location.getProvider(); } public GeoFix(float accuracy, double altitude, double latitude, double longitude, long time, String provider) { mAccuracy = accuracy; mAltitude = altitude; mLatitude = latitude; mLongitude = longitude; mTime = time; mProvider = provider; } public float getAccuracy() { return mAccuracy; } public double getAltitude() { return mAltitude; } public double getLatitude() { return mLatitude; } public double getLongitude() { return mLongitude; } public long getTime() { return mTime; } /** Returns a String with the lag given that systemTime is the current time. */ public String getLagString(long systemTime) { if (this == NO_FIX) return ""; float lagSec = (systemTime - mTime) / 1000f; if (lagSec > 3600 * 10) { // > 10 hour int lagHours = (int)(lagSec/3600); return lagHours + "h"; } else if (lagSec > 3600) { // > 1 hour int lagHours = (int)(lagSec/3600); int lagMin = (int)(lagSec/60 - lagHours*60); if (lagMin > 0) return lagHours + "h " + lagMin + "m"; else return lagHours + "h"; } else if (lagSec > 60) { int lagMin = (int)(lagSec/60); lagSec = lagSec - lagMin*60; //lagSec = ((int)(lagSec*10)) / 10f; //round if ((int)lagSec > 0) return lagMin + "m " + ((int)lagSec) + "s"; else return lagMin + "m"; } else if (lagSec >= 2) { return ((int)lagSec) + "s"; } else { //Not enough lag to be worth showing return ""; } } /** @result Approximate distance in meters */ public float distanceTo(GeoFix fix) { float results[] = { 0 }; Location.distanceBetween(mLatitude, mLongitude, fix.getLatitude(), fix.getLongitude(), results); return results[0]; } public CharSequence getProvider() { return mProvider; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface.OnClickListener; public class ErrorDisplayer { static class DisplayErrorRunnable implements Runnable { private final Builder mAlertDialogBuilder; DisplayErrorRunnable(Builder alertDialogBuilder) { mAlertDialogBuilder = alertDialogBuilder; } public void run() { mAlertDialogBuilder.create().show(); } } private final Activity mActivity; private final OnClickListener mOnClickListener; public ErrorDisplayer(Activity activity, OnClickListener onClickListener) { mActivity = activity; mOnClickListener = onClickListener; } public void displayError(int resId, Object... args) { final Builder alertDialogBuilder = new Builder(mActivity); alertDialogBuilder.setMessage(String.format((String)mActivity.getText(resId), args)); alertDialogBuilder.setNeutralButton("Ok", mOnClickListener); mActivity.runOnUiThread(new DisplayErrorRunnable(alertDialogBuilder)); } }
Java
package com.google.code.geobeagle.formatting; public class DistanceFormatterImperial implements DistanceFormatter { public CharSequence formatDistance(float distance) { if (distance == -1) { return ""; } final float miles = distance / 1609.344f; if (miles > 0.1) return String.format("%1$1.2fmi", miles); final int feet= (int)(miles * 5280); return String.format("%1$1dft", feet); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.formatting; public interface DistanceFormatter { public abstract CharSequence formatDistance(float distance); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.formatting; public class DistanceFormatterMetric implements DistanceFormatter { public CharSequence formatDistance(float distance) { if (distance == -1) { return ""; } if (distance >= 1000) { return String.format("%1$1.2fkm", distance / 1000.0); } return String.format("%1$dm", (int)distance); } }
Java
package com.google.code.geobeagle; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; /** An ordered list of geocache objects, with support for * comparing with another such list. * * A future implementation can fetch * the geocaches from the database when first needed */ public class GeocacheListPrecomputed extends AbstractList<Geocache> { private final ArrayList<Geocache> mList; public static GeocacheListPrecomputed EMPTY = new GeocacheListPrecomputed(); public GeocacheListPrecomputed() { mList = new ArrayList<Geocache>(); } public GeocacheListPrecomputed(ArrayList<Geocache> list) { mList = list; } /** 'Special' constructor used by ProximityPainter */ public GeocacheListPrecomputed(AbstractList<Geocache> list, Geocache extra) { mList = new ArrayList<Geocache>(list); mList.add(extra); } @Override public Iterator<Geocache> iterator() { return mList.iterator(); } @Override public int size() { return mList.size(); } @Override public Geocache get(int position) { return mList.get(position); } }
Java
package com.google.code.geobeagle; public interface GeoFixProvider extends IPausable { //From IPausableAndResumable: public void onResume(); public void onPause(); public GeoFix getLocation(); public void addObserver(Refresher refresher); //TODO: Rename to "areUpdatesEnabled" or something public boolean isProviderEnabled(); /* Returns the direction the device is pointing, measured in degrees. */ public float getAzimuth(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.database.DbFrontend; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; /** Fetch the geocaches from the database (or previously loaded instance) * when first needed */ public class GeocacheListLazy extends AbstractList<Geocache> { /** Elements are either String (cacheId) or Geocache */ private final ArrayList<Object> mList; private final DbFrontend mDbFrontend; public GeocacheListLazy() { mList = new ArrayList<Object>(); mDbFrontend = null; } /** @param initialList The list of cacheIds (Strings) to load */ public GeocacheListLazy(DbFrontend dbFrontend, ArrayList<Object> initialList) { mDbFrontend = dbFrontend; mList = initialList; } public boolean equals(GeocacheListLazy otherList) { if (otherList == this || otherList.mList == mList) return true; if (mList.size() != otherList.mList.size()) return false; for (int i = 0; i < mList.size(); i++) { if (mList.get(i) == otherList.mList.get(i)) continue; Object obj = mList.get(i); Object obj2 = otherList.mList.get(i); CharSequence id1; if (obj instanceof Geocache) { id1 = ((Geocache)obj).getId(); } else { id1 = (CharSequence)obj; } CharSequence id2; if (obj2 instanceof Geocache) { id2 = ((Geocache)obj2).getId(); } else { id2 = (CharSequence)obj2; } if (!id1.equals(id2)) return false; } return true; } private class LazyIterator implements Iterator<Geocache> { private int nextIx = 0; @Override public boolean hasNext() { return mList.size() > nextIx; } @Override public Geocache next() { Geocache cache = get(nextIx); nextIx++; return cache; } @Override public void remove() { //GeocacheLists are immutable throw new UnsupportedOperationException(); } } @Override public Iterator<Geocache> iterator() { return new LazyIterator(); } @Override public int size() { return mList.size(); } public Geocache get(int position) { Object nextObj = mList.get(position); if (nextObj instanceof String) { Geocache cache = mDbFrontend.loadCacheFromId((String)nextObj); mList.set(position, cache); return cache; } return (Geocache)nextObj; } }
Java
package com.google.code.geobeagle; import java.util.HashMap; import java.util.Map; public class Tags { /** This id must never occur in the database */ public final static int NULL = 0; public final static int FOUND = 1; public final static int DNF = 2; public final static int FAVORITES = 3; //TODO: Rename to FAVORITE //These attributes are actually not related to the specific user public final static int UNAVAILABLE = 4; public final static int ARCHIVED = 5; /** The cache is newly added */ public final static int NEW = 6; /** The user placed this cache */ public final static int MINE = 7; /** No logs for this cache */ public final static int FOUND_BY_NOONE = 8; /** Indicates that the user has edited the cache. * Don't overwrite when importing a newer GPX. */ public final static int LOCKED_FROM_OVERWRITING = 9; //This method will be refactored into a more elegant solution public static Map<Integer, String> GetAllTags() { HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(FOUND, "Found"); map.put(DNF, "Did Not Find"); map.put(FAVORITES, "Favorite"); map.put(NEW, "New"); map.put(MINE, "Mine"); map.put(UNAVAILABLE, "Unavailable"); map.put(LOCKED_FROM_OVERWRITING, "Locked from overwriting"); return map; } }
Java
package com.google.code.geobeagle; import android.os.Handler; import java.util.ArrayList; //Doesn't have support for faking azimuth at the moment /** Change LocationControlDi.create() to return an instance of this class * to use fake locations everywhere but in the Map view. */ public class GeoFixProviderFake implements GeoFixProvider { public static class FakeDataset { /** How often to report a new position */ public final int mReportPeriodMillisec; /** The fake positions will be interpreted to be * given relative to this location */ private final double mLatStart; private final double mLonStart; /** The period of the fix list loop, in millisec */ private final long mLoopTime; /** A number of GeoFixes with values relative some starting point. * The first fix must have relative time 0 */ private GeoFix[] mFixes; public FakeDataset(int reportPeriodMillisec, double latStart, double lonStart, long loopTime, GeoFix[] fixes) { mReportPeriodMillisec = reportPeriodMillisec; mLatStart = latStart; mLonStart = lonStart; mLoopTime = loopTime; mFixes = fixes; } /** @param time in millisec */ public GeoFix getGeoFixAtTime(long time) { long relTime = time % mLoopTime; //Initialize to avoid compiler warning GeoFix lastFix = mFixes[0]; GeoFix nextFix = mFixes[0]; float ratio = 0; //Between 0 and 1 if (relTime > mFixes[mFixes.length - 1].getTime()) { lastFix = mFixes[mFixes.length - 1]; nextFix = mFixes[0]; ratio = ((relTime-lastFix.getTime()) / (mLoopTime-lastFix.getTime())); } else { for (int i = 1; i < mFixes.length; i++) { if (mFixes[i].getTime() == relTime) { lastFix = mFixes[i]; nextFix = mFixes[i]; ratio = 0; break; } else if (mFixes[i].getTime() > relTime) { lastFix = mFixes[i-1]; nextFix = mFixes[i]; //Must convert to float to avoid integer division: ratio = (((float)relTime-lastFix.getTime()) / (nextFix.getTime()-lastFix.getTime())); break; } } } //float accuracy, double altitude, //double latitude, double longitude, long time, String provider return new GeoFix(lastFix.getAccuracy(), lastFix.getAltitude() + (nextFix.getAltitude()-lastFix.getAltitude())*ratio, mLatStart + lastFix.getLatitude() + (nextFix.getLatitude()-lastFix.getLatitude())*ratio, mLonStart + lastFix.getLongitude() + (nextFix.getLongitude()-lastFix.getLongitude())*ratio, time, (String)lastFix.getProvider()); } } /** Move slowly between three locations */ public static FakeDataset YOKOHAMA = new FakeDataset(2000, 35.4583162355423, 139.62289574623108, 10000, new GeoFix[] { new GeoFix(192, 40, 0, 0, 0, "gps"), new GeoFix(128, 40, 0.001, -0.0001, 5000, "gps"), new GeoFix(8, 40, 0.002, -0.0001, 7000, "gps"), }); /** A single location */ public static FakeDataset TOKYO = new FakeDataset(10000, 35.690448, 139.756225, 10000, new GeoFix[] { new GeoFix(16, 10, 0, 0, 0, "gps"), }); /** Another single location */ public static FakeDataset LINKOPING = new FakeDataset(10000, 58.398050, 15.612208, 10000, new GeoFix[] { new GeoFix(8, 20, 0, 0, 0, "gps"), }); /** Simulate moving at highway speeds and report location every second */ public static FakeDataset CAR_JOURNEY = new FakeDataset(1000, 58.398050, 15.612208, 70*60*1000, new GeoFix[] { new GeoFix(8, 20, 0, 0, 0, "gps"), new GeoFix(16, 30, 58.432729-58.398050, 15.669937-15.612208, 5*60*1000, "gps"), new GeoFix(32, 40, 58.591698-58.398050, 16.12896-15.612208, 35*60*1000, "gps"), new GeoFix(24, 30, 58.432729-58.398050, 15.669937-15.612208,65*60*1000, "gps"), }); private final FakeDataset mFakeDataset; private GeoFix mCurrentGeoFix; private boolean mUpdatesEnabled = false; private final Handler mHandler; private ArrayList<Refresher> mObservers = new ArrayList<Refresher>(); private class FixTimer extends Thread { @Override public void run() { while (mUpdatesEnabled) { try { if (mUpdatesEnabled) { mCurrentGeoFix = mFakeDataset.getGeoFixAtTime(System.currentTimeMillis()); mHandler.post(mObserverNotifier); } Thread.sleep(mFakeDataset.mReportPeriodMillisec); } catch (InterruptedException e) { return; } } } } private FixTimer mFixTimer; public GeoFixProviderFake(FakeDataset fakeDataset) { //Create here to assure that main thread gets to execute notifications: mHandler = new Handler(); mFakeDataset = fakeDataset; } public void addObserver(Refresher refresher) { if (!mObservers.contains(refresher)) mObservers.add(refresher); } private void notifyObservers() { for (Refresher refresher : mObservers) { refresher.refresh(); } } private final Runnable mObserverNotifier = new Runnable() { @Override public void run() { notifyObservers(); } }; @Override public float getAzimuth() { //Reports a new azimuth once a second int degreesPerSecond = 10; long time = System.currentTimeMillis(); return (time/1000 * degreesPerSecond) % 360; } @Override public GeoFix getLocation() { return mCurrentGeoFix; } @Override public boolean isProviderEnabled() { return true; } @Override public void onPause() { mUpdatesEnabled = false; } @Override public void onResume() { mUpdatesEnabled = true; mFixTimer = new FixTimer(); mFixTimer.start(); } }
Java
package com.google.code.geobeagle; /** Allow objects that need to be paused/resumed to be sent as parameters * without requiring their specific type to be exposed. */ public interface IPausable { void onPause(); void onResume(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; public interface Refresher { public void refresh(); public void forceRefresh(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.IToaster; import com.google.code.geobeagle.database.CachesProviderLazyArea; import android.util.Log; import java.util.AbstractList; import java.util.List; class DensityPatchManager { private List<DensityMatrix.DensityPatch> mDensityPatches; private final CachesProviderLazyArea mLazyArea; public static final double RESOLUTION_LATITUDE = 0.01; public static final double RESOLUTION_LONGITUDE = 0.02; public static final int RESOLUTION_LATITUDE_E6 = (int)(RESOLUTION_LATITUDE * 1E6); public static final int RESOLUTION_LONGITUDE_E6 = (int)(RESOLUTION_LONGITUDE * 1E6); private final IToaster mToaster; DensityPatchManager(List<DensityMatrix.DensityPatch> patches, CachesProviderLazyArea lazyArea, IToaster densityOverlayToaster) { mDensityPatches = patches; mLazyArea = lazyArea; mToaster = densityOverlayToaster; } public List<DensityMatrix.DensityPatch> getDensityPatches(MapView mMapView) { Projection projection = mMapView.getProjection(); GeoPoint newTopLeft = projection.fromPixels(0, 0); GeoPoint newBottomRight = projection.fromPixels(mMapView.getRight(), mMapView.getBottom()); double latLow = newBottomRight.getLatitudeE6() / 1.0E6; double latHigh = newTopLeft.getLatitudeE6() / 1.0E6; double lonLow = newTopLeft.getLongitudeE6() / 1.0E6; double lonHigh = newBottomRight.getLongitudeE6() / 1.0E6; mLazyArea.setBounds(latLow, lonLow, latHigh, lonHigh); if (!mLazyArea.hasChanged()) { return mDensityPatches; } AbstractList<Geocache> list = mLazyArea.getCaches(); mToaster.showToast(mLazyArea.tooManyCaches()); mLazyArea.resetChanged(); DensityMatrix densityMatrix = new DensityMatrix(DensityPatchManager.RESOLUTION_LATITUDE, DensityPatchManager.RESOLUTION_LONGITUDE); densityMatrix.addCaches(list); mDensityPatches = densityMatrix.getDensityPatches(); Log.d("GeoBeagle", "Density patches:" + mDensityPatches.size()); return mDensityPatches; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.Overlay; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.database.CachesProviderDb; import java.util.List; public class OverlayManager implements Refresher { static final int DENSITY_MAP_ZOOM_THRESHOLD = 12; private final CachePinsOverlayFactory mCachePinsOverlayFactory; private final DensityOverlay mDensityOverlay; private final GeoMapView mGeoMapView; private final List<Overlay> mMapOverlays; private boolean mUsesDensityMap; private final CachesProviderDb mCachesProviderDb; private final FilterTypeCollection mFilterTypeCollection; private final OverlaySelector mOverlaySelector; static class OverlaySelector { boolean selectOverlay(OverlayManager overlayManager, int zoomLevel, boolean fUsesDensityMap, List<Overlay> mapOverlays, Overlay densityOverlay, CachePinsOverlayFactory cachePinsOverlayFactory) { // Log.d("GeoBeagle", "selectOverlay Zoom: " + zoomLevel); boolean newZoomUsesDensityMap = zoomLevel < DENSITY_MAP_ZOOM_THRESHOLD; if (newZoomUsesDensityMap && fUsesDensityMap) return newZoomUsesDensityMap; if (newZoomUsesDensityMap) { mapOverlays.set(0, densityOverlay); } else { mapOverlays.set(0, cachePinsOverlayFactory .getCachePinsOverlay()); } return newZoomUsesDensityMap; } } public OverlayManager(GeoMapView geoMapView, List<Overlay> mapOverlays, DensityOverlay densityOverlay, CachePinsOverlayFactory cachePinsOverlayFactory, boolean usesDensityMap, CachesProviderDb cachesProviderArea, FilterTypeCollection filterTypeCollection, OverlaySelector overlaySelector) { mGeoMapView = geoMapView; mMapOverlays = mapOverlays; mDensityOverlay = densityOverlay; mCachePinsOverlayFactory = cachePinsOverlayFactory; mUsesDensityMap = usesDensityMap; mCachesProviderDb = cachesProviderArea; mFilterTypeCollection = filterTypeCollection; mOverlaySelector = overlaySelector; } public void selectOverlay() { mUsesDensityMap = mOverlaySelector.selectOverlay(this, mGeoMapView .getZoomLevel(), mUsesDensityMap, mMapOverlays, mDensityOverlay, mCachePinsOverlayFactory); } public boolean usesDensityMap() { return mUsesDensityMap; } @Override public void forceRefresh() { CacheFilter cacheFilter = mFilterTypeCollection.getActiveFilter(); mCachesProviderDb.setFilter(cacheFilter); selectOverlay(); // Must be called from the GUI thread: mGeoMapView.invalidate(); } @Override public void refresh() { selectOverlay(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MyLocationOverlay; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.ActionStaticLabel; import com.google.code.geobeagle.actions.MenuAction; import com.google.code.geobeagle.actions.MenuActions; import android.content.res.Resources; import android.view.Menu; import android.view.MenuItem; public class GeoMapActivityDelegate { public static class MenuActionCenterLocation extends ActionStaticLabel implements MenuAction { private final MapController mMapController; private final MyLocationOverlay mMyLocationOverlay; public MenuActionCenterLocation(Resources resources, MapController mapController, MyLocationOverlay myLocationOverlay) { super(resources, R.string.menu_center_location); mMapController = mapController; mMyLocationOverlay = myLocationOverlay; } @Override public void act() { GeoPoint geopoint = mMyLocationOverlay.getMyLocation(); if (geopoint != null) mMapController.animateTo(geopoint); } } public static class MenuActionToggleSatellite implements MenuAction { private final MapView mMapView; public MenuActionToggleSatellite(MapView mapView) { mMapView = mapView; } @Override public void act() { mMapView.setSatellite(!mMapView.isSatellite()); } @Override public String getLabel() { int stringId = mMapView.isSatellite() ? R.string.map_view : R.string.menu_toggle_satellite; return mMapView.getResources().getString(stringId); } } private final MenuActions mMenuActions; public GeoMapActivityDelegate(MenuActions menuActions) { mMenuActions = menuActions; } public boolean onCreateOptionsMenu(Menu menu) { return mMenuActions.onCreateOptionsMenu(menu); } public boolean onMenuOpened(Menu menu) { return mMenuActions.onMenuOpened(menu); } public boolean onOptionsItemSelected(MenuItem item) { return mMenuActions.act(item.getItemId()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.Projection; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI; import com.google.code.geobeagle.database.CachesProviderLazyArea; import android.content.Context; import android.graphics.drawable.Drawable; import java.util.AbstractList; public class CachePinsOverlayFactory { private final CacheItemFactory mCacheItemFactory; private CachePinsOverlay mCachePinsOverlay; private final Context mContext; private final Drawable mDefaultMarker; private final GeoMapView mGeoMapView; private CachesProviderLazyArea mLazyArea; public CachePinsOverlayFactory(GeoMapView geoMapView, Context context, Drawable defaultMarker, CacheItemFactory cacheItemFactory, CachePinsOverlay cachePinsOverlay, CachesProviderLazyArea lazyArea) { mGeoMapView = geoMapView; mContext = context; mDefaultMarker = defaultMarker; mCacheItemFactory = cacheItemFactory; mCachePinsOverlay = cachePinsOverlay; mLazyArea = lazyArea; } public CachePinsOverlay getCachePinsOverlay() { //Log.d("GeoBeagle", "CachePinsOverlayFactory.getCachePinsOverlay()"); final CacheListDelegateDI.Timing timing = new CacheListDelegateDI.Timing(); Projection projection = mGeoMapView.getProjection(); GeoPoint newTopLeft = projection.fromPixels(0, 0); GeoPoint newBottomRight = projection.fromPixels(mGeoMapView.getRight(), mGeoMapView .getBottom()); timing.start(); double latLow = newBottomRight.getLatitudeE6() / 1.0E6; double latHigh = newTopLeft.getLatitudeE6() / 1.0E6; double lonLow = newTopLeft.getLongitudeE6() / 1.0E6; double lonHigh = newBottomRight.getLongitudeE6() / 1.0E6; mLazyArea.setBounds(latLow, lonLow, latHigh, lonHigh); if (!mLazyArea.hasChanged()) return mCachePinsOverlay; mLazyArea.showToastIfTooManyCaches(); AbstractList<Geocache> list = mLazyArea.getCaches(); mLazyArea.resetChanged(); mCachePinsOverlay = new CachePinsOverlay(mCacheItemFactory, mContext, mDefaultMarker, list); timing.lap("getCachePinsOverlay took"); return mCachePinsOverlay; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Projection; import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI; import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import java.util.List; public class DensityOverlayDelegate { private static final double RESOLUTION_LATITUDE_E6 = (DensityPatchManager.RESOLUTION_LATITUDE * 1E6); private static final double RESOLUTION_LONGITUDE_E6 = (DensityPatchManager.RESOLUTION_LONGITUDE * 1E6); private final Paint mPaint; private final Rect mPatchRect; private final Point mScreenBottomRight; private final Point mScreenTopLeft; private final CacheListDelegateDI.Timing mTiming; private final DensityPatchManager mDensityPatchManager; public DensityOverlayDelegate(Rect patchRect, Paint paint, Point screenLow, Point screenHigh, DensityPatchManager densityPatchManager) { mTiming = new CacheListDelegateDI.Timing(); mPatchRect = patchRect; mPaint = paint; mScreenTopLeft = screenLow; mScreenBottomRight = screenHigh; mDensityPatchManager = densityPatchManager; } public void draw(Canvas canvas, MapView mapView, boolean shadow) { if (shadow) return; // No shadow layer // Log.d("GeoBeagle", ">>>>>>>>>>Starting draw"); List<DensityMatrix.DensityPatch> densityPatches = mDensityPatchManager .getDensityPatches(mapView); mTiming.start(); final Projection projection = mapView.getProjection(); final GeoPoint newGeoTopLeft = projection.fromPixels(0, 0); final GeoPoint newGeoBottomRight = projection.fromPixels(mapView.getRight(), mapView .getBottom()); projection.toPixels(newGeoTopLeft, mScreenTopLeft); projection.toPixels(newGeoBottomRight, mScreenBottomRight); final int topLatitudeE6 = newGeoTopLeft.getLatitudeE6(); final int leftLongitudeE6 = newGeoTopLeft.getLongitudeE6(); final int bottomLatitudeE6 = newGeoBottomRight.getLatitudeE6(); final int rightLongitudeE6 = newGeoBottomRight.getLongitudeE6(); final double pixelsPerLatE6Degrees = (double)(mScreenBottomRight.y - mScreenTopLeft.y) / (double)(bottomLatitudeE6 - topLatitudeE6); final double pixelsPerLonE6Degrees = (double)(mScreenBottomRight.x - mScreenTopLeft.x) / (double)(rightLongitudeE6 - leftLongitudeE6); int patchCount = 0; for (DensityPatch patch : densityPatches) { final int patchLatLowE6 = patch.getLatLowE6(); final int patchLonLowE6 = patch.getLonLowE6(); int xOffset = (int)((patchLonLowE6 - leftLongitudeE6) * pixelsPerLonE6Degrees); int xEnd = (int)((patchLonLowE6 + RESOLUTION_LONGITUDE_E6 - leftLongitudeE6) * pixelsPerLonE6Degrees); int yOffset = (int)((patchLatLowE6 - topLatitudeE6) * pixelsPerLatE6Degrees); int yEnd = (int)((patchLatLowE6 + RESOLUTION_LATITUDE_E6 - topLatitudeE6) * pixelsPerLatE6Degrees); mPatchRect.set(xOffset, yEnd, xEnd, yOffset); // Log.d("GeoBeagle", "patchrect: " + mPatchRect.bottom + ", " + // mPatchRect.left // + ", " + mPatchRect.top + ", " + mPatchRect.right); mPaint.setAlpha(patch.getAlpha()); canvas.drawRect(mPatchRect, mPaint); patchCount++; } // mTiming.lap("Done drawing"); // Log.d("GeoBeagle", "patchcount: " + patchCount); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.code.geobeagle.Geocache; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.TreeMap; public class DensityMatrix { public static class DensityPatch { private int mCacheCount; private final int mLatLowE6; private final int mLonLowE6; public DensityPatch(double latLow, double lonLow) { mCacheCount = 0; mLatLowE6 = (int)(latLow * 1E6); mLonLowE6 = (int)(lonLow * 1E6); } public int getAlpha() { return Math.min(210, 10 + 32 * mCacheCount); } public int getCacheCount() { return mCacheCount; } public int getLatLowE6() { return mLatLowE6; } public int getLonLowE6() { return mLonLowE6; } public void setCacheCount(int count) { mCacheCount = count; } } /** Mapping lat -> (mapping lon -> cache count) */ private TreeMap<Integer, Map<Integer, DensityPatch>> mBuckets = new TreeMap<Integer, Map<Integer, DensityPatch>>(); private double mLatResolution; private double mLonResolution; public DensityMatrix(double latResolution, double lonResolution) { mLatResolution = latResolution; mLonResolution = lonResolution; } public void addCaches(Collection<Geocache> list) { for (Geocache cache : list) { incrementBucket(cache.getLatitude(), cache.getLongitude()); } } public List<DensityPatch> getDensityPatches() { ArrayList<DensityPatch> result = new ArrayList<DensityPatch>(); for (Integer latBucket : mBuckets.keySet()) { Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket); result.addAll(lonMap.values()); } return result; } private void incrementBucket(double lat, double lon) { Integer latBucket = (int)Math.floor(lat / mLatResolution); Integer lonBucket = (int)Math.floor(lon / mLonResolution); Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket); if (lonMap == null) { // Key didn't exist in map lonMap = new TreeMap<Integer, DensityPatch>(); mBuckets.put(latBucket, lonMap); } DensityPatch patch = lonMap.get(lonBucket); if (patch == null) { patch = new DensityPatch(latBucket * mLatResolution, lonBucket * mLonResolution); lonMap.put(lonBucket, patch); } patch.setCacheCount(patch.getCacheCount() + 1); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.map; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.R; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; import android.graphics.drawable.Drawable; class CacheItemFactory { private final Resources mResources; private Geocache mSelected; private final GraphicsGenerator mGraphicsGenerator; private final DbFrontend mDbFrontend; CacheItemFactory(Resources resources, GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) { mResources = resources; mGraphicsGenerator = graphicsGenerator; mDbFrontend = dbFrontend; } void setSelectedGeocache(Geocache geocache) { mSelected = geocache; } CacheItem createCacheItem(Geocache geocache) { final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), geocache); Drawable marker = geocache.getIconMap(mResources, mGraphicsGenerator, mDbFrontend); if (geocache == mSelected) { marker = mGraphicsGenerator.superimpose(marker, mResources .getDrawable(R.drawable.glow_40px)); } cacheItem.setMarker(marker); return cacheItem; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity; import com.google.code.geobeagle.Geocache; import android.content.SharedPreferences.Editor; public class ActivitySaver { private final Editor mEditor; static final String LAST_ACTIVITY = "lastActivity"; ActivitySaver(Editor editor) { mEditor = editor; } public void save(ActivityType activityType) { mEditor.putInt("lastActivity", activityType.toInt()); mEditor.commit(); } public void save(ActivityType activityType, Geocache geocache) { mEditor.putInt("lastActivity", activityType.toInt()); mEditor.putString(Geocache.ID, geocache.getId().toString()); mEditor.commit(); } }
Java
package com.google.code.geobeagle.activity.searchonline; import com.google.code.geobeagle.IPausable; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager; import android.graphics.Color; import android.webkit.WebSettings; import android.webkit.WebView; public class SearchOnlineActivityDelegate { private final ActivitySaver mActivitySaver; private final DistanceFormatterManager mDistanceFormatterManager; private final IPausable mPausable; private final WebView mWebView; public SearchOnlineActivityDelegate(WebView webView, IPausable pausable, DistanceFormatterManager distanceFormatterManager, ActivitySaver activitySaver) { mPausable = pausable; mWebView = webView; mDistanceFormatterManager = distanceFormatterManager; mActivitySaver = activitySaver; } public void configureWebView(JsInterface jsInterface) { mWebView.loadUrl("file:///android_asset/search.html"); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setBackgroundColor(Color.BLACK); mWebView.addJavascriptInterface(jsInterface, "gb"); } public void onPause() { mPausable.onPause(); mActivitySaver.save(ActivityType.SEARCH_ONLINE); } public void onResume() { mPausable.onResume(); mDistanceFormatterManager.setFormatter(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.searchonline; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.R; import android.app.Activity; import android.content.Intent; import android.net.Uri; import java.util.Locale; class JsInterface { private final GeoFixProvider mGeoFixProvider; private final JsInterfaceHelper mHelper; static class JsInterfaceHelper { private final Activity mActivity; public JsInterfaceHelper(Activity activity) { mActivity = activity; } public void launch(String uri) { mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri))); } public String getTemplate(int ix) { return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix]; } public String getNS(double latitude) { return latitude > 0 ? "N" : "S"; } public String getEW(double longitude) { return longitude > 0 ? "E" : "W"; } } public JsInterface(GeoFixProvider geoFixProvider, JsInterfaceHelper jsInterfaceHelper) { mHelper = jsInterfaceHelper; mGeoFixProvider = geoFixProvider; } public int atlasQuestOrGroundspeak(int ix) { final GeoFix location = mGeoFixProvider.getLocation(); final String uriTemplate = mHelper.getTemplate(ix); mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location .getLongitude())); return 0; } public int openCaching(int ix) { final GeoFix location = mGeoFixProvider.getLocation(); final String uriTemplate = mHelper.getTemplate(ix); final double latitude = location.getLatitude(); final double longitude = location.getLongitude(); final String NS = mHelper.getNS(latitude); final String EW = mHelper.getEW(longitude); final double abs_latitude = Math.abs(latitude); final double abs_longitude = Math.abs(longitude); final int lat_h = (int)abs_latitude; final double lat_m = 60 * (abs_latitude - lat_h); final int lon_h = (int)abs_longitude; final double lon_m = 60 * (abs_longitude - lon_h); mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m)); return 0; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.database.DbFrontend; import android.content.Intent; public class IncomingIntentHandler { private GeocacheFactory mGeocacheFactory; private GeocacheFromIntentFactory mGeocacheFromIntentFactory; private final DbFrontend mDbFrontend; public IncomingIntentHandler(GeocacheFactory geocacheFactory, GeocacheFromIntentFactory geocacheFromIntentFactory, DbFrontend dbFrontend) { mGeocacheFactory = geocacheFactory; mGeocacheFromIntentFactory = geocacheFromIntentFactory; mDbFrontend = dbFrontend; } public Geocache maybeGetGeocacheFromIntent(Intent intent, Geocache defaultGeocache, DbFrontend dbFrontend) { if (intent == null) { return defaultGeocache; } final String action = intent.getAction(); if (action == null) { return defaultGeocache; } if (action.equals(Intent.ACTION_VIEW) && intent.getType() == null) { return mGeocacheFromIntentFactory.viewCacheFromMapsIntent(intent, defaultGeocache); } else if (action.equals(GeocacheListController.SELECT_CACHE)) { String id = intent.getStringExtra("geocacheId"); Geocache geocache = mDbFrontend.loadCacheFromId(id); if (geocache == null) geocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "", CacheType.NULL, 0, 0, 0); return geocache; } else { return defaultGeocache; } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import android.net.UrlQuerySanitizer; import android.net.UrlQuerySanitizer.ValueSanitizer; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Util { static final double APPROX_EQUALS_PRECISION = 1.0e-9; public static final String[] geocachingQueryParam = new String[] { "q" }; // #Wildwood Park, Saratoga, CA(The Nut Case #89882) private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)"); private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)"); private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.]+)[^\\d]*"); private static final Pattern PAT_LATLON = Pattern .compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)"); private static final Pattern PAT_LATLONDEC = Pattern.compile("([\\d.]+)\\s+([\\d.]+)"); private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]"); private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*"); private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]"); public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) { final double fAbsDegrees = Math.abs(fDegrees); final int dAbsDegrees = (int)fAbsDegrees; return String.format(Locale.US, (fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees, 60.0 * (fAbsDegrees - dAbsDegrees)); } public static double parseCoordinate(CharSequence string) { int sign = 1; final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string); if (negsignMatcher.find()) { sign = -1; } final Matcher signMatcher = PAT_SIGN.matcher(string); string = signMatcher.replaceAll(""); final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string); double degrees = 0.0; for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) { degrees += Double.parseDouble(dmsMatcher.group(1)) / scale; } return sign * degrees; } public static CharSequence[] parseDescription(CharSequence string) { Matcher matcher = PAT_ATLASQUEST.matcher(string); if (matcher.matches()) return new CharSequence[] { "LB" + matcher.group(2).trim(), matcher.group(1).trim() }; return new CharSequence[] { string, "" }; } public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer, ValueSanitizer valueSanitizer) { sanitizer.registerParameters(geocachingQueryParam, valueSanitizer); sanitizer.parseQuery(query); return sanitizer.getValue("q"); } public static CharSequence[] splitCoordsAndDescription(CharSequence location) { Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location); if (matcher.matches()) { return new CharSequence[] { matcher.group(2).trim(), matcher.group(1).trim() }; } matcher = PAT_PAREN_FORMAT.matcher(location); if (matcher.matches()) { return new CharSequence[] { matcher.group(1).trim(), matcher.group(2).trim() }; } // No description. return new CharSequence[] { location, "" }; } public static CharSequence[] splitLatLon(CharSequence string) { Matcher matcherDecimal = PAT_LATLONDEC.matcher(string); if (matcherDecimal.matches()) { return new String[] { matcherDecimal.group(1).trim(), matcherDecimal.group(2).trim() }; } Matcher matcher = PAT_LATLON.matcher(string); matcher.matches(); return new String[] { matcher.group(1).trim(), matcher.group(2).trim() }; } public static CharSequence[] splitLatLonDescription(CharSequence location) { CharSequence coordsAndDescription[] = splitCoordsAndDescription(location); CharSequence latLon[] = splitLatLon(coordsAndDescription[0]); CharSequence[] parseDescription = parseDescription(coordsAndDescription[1]); return new CharSequence[] { latLon[0], latLon[1], parseDescription[0], parseDescription[1] }; } /** Rounding errors might make equal floating point numbers seem to differ. */ public static boolean approxEquals(double a, double b) { return (Math.abs(a - b) < APPROX_EQUALS_PRECISION); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Provider; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.view.View; public class WebPageAndDetailsButtonEnabler { interface CheckButton { public void check(Geocache geocache); } public static class CheckButtons { private final CheckButton[] mCheckButtons; public CheckButtons(CheckButton[] checkButtons) { mCheckButtons = checkButtons; } public void check(Geocache geocache) { for (CheckButton checkButton : mCheckButtons) { checkButton.check(geocache); } } } public static class CheckDetailsButton implements CheckButton { private final View mDetailsButton; public CheckDetailsButton(View checkDetailsButton) { mDetailsButton = checkDetailsButton; } public void check(Geocache geocache) { mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX); } } public static class CheckWebPageButton implements CheckButton { private final View mWebPageButton; public CheckWebPageButton(View webPageButton) { mWebPageButton = webPageButton; } public void check(Geocache geocache) { final Provider contentProvider = geocache.getContentProvider(); mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK || contentProvider == GeocacheFactory.Provider.ATLAS_QUEST || contentProvider == GeocacheFactory.Provider.OPENCACHING); } } private final CheckButtons mCheckButtons; private final GeoBeagle mGeoBeagle; public WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, CheckButtons checkButtons) { mGeoBeagle = geoBeagle; mCheckButtons = checkButtons; } public void check() { mCheckButtons.check(mGeoBeagle.getGeocache()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.code.geobeagle.cachedetails.CacheDetailsLoader; import android.app.AlertDialog.Builder; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; public class CacheDetailsOnClickListener implements View.OnClickListener { private final Builder mAlertDialogBuilder; private final CacheDetailsLoader mCacheDetailsLoader; private final LayoutInflater mEnv; private final GeoBeagle mGeoBeagle; public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder, LayoutInflater env, CacheDetailsLoader cacheDetailsLoader) { mAlertDialogBuilder = alertDialogBuilder; mEnv = env; mCacheDetailsLoader = cacheDetailsLoader; mGeoBeagle = geoBeagle; } public void onClick(View v) { View detailsView = mEnv.inflate(R.layout.cache_details, null); CharSequence id = mGeoBeagle.getGeocache().getId(); mAlertDialogBuilder.setTitle(id); mAlertDialogBuilder.setView(detailsView); WebView webView = (WebView)detailsView.findViewById(R.id.webview); webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(id), "text/html", "utf-8", "about:blank"); mAlertDialogBuilder.create().show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.R; import com.google.code.geobeagle.database.DbFrontend; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.ImageView; /** Handles the star graphics showing if the geocache is a favorite */ public class FavoriteView extends ImageView { public static class FavoriteState { private final DbFrontend mDbFrontend; private final CharSequence mGeocacheId; private boolean mIsFavorite; public FavoriteState(DbFrontend dbFrontend, CharSequence geocacheId) { mDbFrontend = dbFrontend; mGeocacheId = geocacheId; mIsFavorite = dbFrontend.geocacheHasTag(geocacheId, Tags.FAVORITES); } public boolean isFavorite() { return mIsFavorite; } public void toggleFavorite() { mIsFavorite = !mIsFavorite; mDbFrontend .setGeocacheTag(mGeocacheId, Tags.FAVORITES, mIsFavorite); } } public static class FavoriteViewDelegate { private final FavoriteState mFavoriteState; private final FavoriteView mFavoriteView; public FavoriteViewDelegate(FavoriteView favoriteView, FavoriteState favoriteState) { mFavoriteView = favoriteView; mFavoriteState = favoriteState; } void toggleFavorite() { mFavoriteState.toggleFavorite(); updateImage(); } void updateImage() { mFavoriteView .setImageResource(mFavoriteState.isFavorite() ? R.drawable.btn_rating_star_on_normal : R.drawable.btn_rating_star_off_normal); } } static class OnFavoriteClick implements OnClickListener { private final FavoriteView mFavoriteView; OnFavoriteClick(FavoriteView favoriteView) { mFavoriteView = favoriteView; } @Override public void onClick(View v) { mFavoriteView.toggleFavorite(); } } private FavoriteViewDelegate mFavoriteViewDelegate; public FavoriteView(Context context) { super(context); setOnClickListener(new OnFavoriteClick(this)); } public FavoriteView(Context context, AttributeSet attrs) { super(context, attrs); setOnClickListener(new OnFavoriteClick(this)); } public FavoriteView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setOnClickListener(new OnFavoriteClick(this)); } public void setGeocache(FavoriteViewDelegate favoriteViewDelegate) { mFavoriteViewDelegate = favoriteViewDelegate; mFavoriteViewDelegate.updateImage(); } void toggleFavorite() { mFavoriteViewDelegate.toggleFavorite(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.Util; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; public class EditCache { public static class CancelButtonOnClickListener implements OnClickListener { private final Activity mActivity; public CancelButtonOnClickListener(Activity activity) { mActivity = activity; } public void onClick(View v) { mActivity.setResult(Activity.RESULT_CANCELED, null); mActivity.finish(); } } public static class CacheSaverOnClickListener implements OnClickListener { private final Activity mActivity; private final EditCache mGeocacheView; private final DbFrontend mDbFrontend; public CacheSaverOnClickListener(Activity activity, EditCache editCache, DbFrontend dbFrontend) { mActivity = activity; mGeocacheView = editCache; mDbFrontend = dbFrontend; } public void onClick(View v) { final Geocache geocache = mGeocacheView.get(); if (geocache.saveToDbIfNeeded(mDbFrontend)) mDbFrontend.setGeocacheTag(geocache.getId(), Tags.LOCKED_FROM_OVERWRITING, true); final Intent i = new Intent(); i.setAction(GeocacheListController.SELECT_CACHE); i.putExtra("geocacheId", geocache.getId()); mActivity.setResult(Activity.RESULT_OK, i); mActivity.finish(); } } private final GeocacheFactory mGeocacheFactory; private final EditText mId; private final EditText mLatitude; private final EditText mLongitude; private final EditText mName; private Geocache mOriginalGeocache; public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name, EditText latitude, EditText longitude) { mGeocacheFactory = geocacheFactory; mId = id; mName = name; mLatitude = latitude; mLongitude = longitude; } Geocache get() { return mGeocacheFactory.create(mId.getText(), mName.getText(), Util .parseCoordinate(mLatitude.getText()), Util.parseCoordinate(mLongitude .getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache .getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache .getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache .getContainer()); } public void set(Geocache geocache) { mOriginalGeocache = geocache; mId.setText(geocache.getId()); mName.setText(geocache.getName()); mLatitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude())); mLongitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude())); //mLatitude.setText(Double.toString(geocache.getLatitude())); //mLongitude.setText(Double.toString(geocache.getLongitude())); mLatitude.requestFocus(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.activity.main.RadarView; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class GeocacheViewer { public interface AttributeViewer { void setImage(int attributeValue); } public static class LabelledAttributeViewer implements AttributeViewer { private final AttributeViewer mUnlabelledAttributeViewer; private final TextView mLabel; public LabelledAttributeViewer(TextView label, AttributeViewer unlabelledAttributeViewer) { mUnlabelledAttributeViewer = unlabelledAttributeViewer; mLabel = label; } @Override public void setImage(int attributeValue) { mUnlabelledAttributeViewer.setImage(attributeValue); mLabel.setVisibility(attributeValue == 0 ? View.GONE : View.VISIBLE); } } public static class UnlabelledAttributeViewer implements AttributeViewer { private final Drawable[] mDrawables; private final ImageView mImageView; public UnlabelledAttributeViewer(ImageView imageView, Drawable[] drawables) { mImageView = imageView; mDrawables = drawables; } @Override public void setImage(int attributeValue) { if (attributeValue == 0) { mImageView.setVisibility(View.GONE); return; } mImageView.setImageDrawable(mDrawables[attributeValue-1]); mImageView.setVisibility(View.VISIBLE); } } public static class ResourceImages implements AttributeViewer { private final int[] mResources; private final ImageView mImageView; public ResourceImages(ImageView imageView, int[] resources) { mImageView = imageView; mResources = resources; } @Override public void setImage(int attributeValue) { mImageView.setImageResource(mResources[attributeValue]); } } public static class NameViewer { private final TextView mName; public NameViewer(TextView name) { mName = name; } void set(CharSequence name) { if (name.length() == 0) { mName.setVisibility(View.GONE); return; } mName.setText(name); mName.setVisibility(View.VISIBLE); } } public static final int CONTAINER_IMAGES[] = { R.drawable.size_1, R.drawable.size_2, R.drawable.size_3, R.drawable.size_4 }; private final ImageView mCacheTypeImageView; private final AttributeViewer mContainer; private final AttributeViewer mDifficulty; private final TextView mId; private final NameViewer mName; private final RadarView mRadarView; private final AttributeViewer mTerrain; public GeocacheViewer(RadarView radarView, TextView gcId, NameViewer gcName, ImageView cacheTypeImageView, AttributeViewer gcDifficulty, AttributeViewer gcTerrain, AttributeViewer gcContainer) { mRadarView = radarView; mId = gcId; mName = gcName; mCacheTypeImageView = cacheTypeImageView; mDifficulty = gcDifficulty; mTerrain = gcTerrain; mContainer = gcContainer; } public void set(Geocache geocache) { final double latitude = geocache.getLatitude(); final double longitude = geocache.getLongitude(); mRadarView.setTarget((int)(latitude * GeoUtils.MILLION), (int)(longitude * GeoUtils.MILLION)); mId.setText(geocache.getId()); mCacheTypeImageView.setImageResource(geocache.getCacheType().iconBig()); mContainer.setImage(geocache.getContainer()); mDifficulty.setImage(geocache.getDifficulty()); mTerrain.setImage(geocache.getTerrain()); mName.set(geocache.getName()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.view; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.CacheAction; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.content.ActivityNotFoundException; import android.view.View; import android.view.View.OnClickListener; public class CacheButtonOnClickListener implements OnClickListener { private final CacheAction mCacheAction; private final ErrorDisplayer mErrorDisplayer; private final String mActivityNotFoundErrorMessage; private final GeoBeagle mGeoBeagle; public CacheButtonOnClickListener(CacheAction cacheAction, GeoBeagle geoBeagle, String errorMessage, ErrorDisplayer errorDisplayer) { mCacheAction = cacheAction; mGeoBeagle = geoBeagle; mErrorDisplayer = errorDisplayer; mActivityNotFoundErrorMessage = errorMessage; } public void onClick(View view) { Geocache geocache = mGeoBeagle.getGeocache(); try { mCacheAction.act(geocache); } catch (final ActivityNotFoundException e) { mErrorDisplayer.displayError(R.string.error2, e.getMessage(), mActivityNotFoundErrorMessage); } catch (final Exception e) { mErrorDisplayer.displayError(R.string.error1, e.getMessage()); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.database.DbFrontend; import android.content.Intent; import android.net.UrlQuerySanitizer; public class GeocacheFromIntentFactory { private final GeocacheFactory mGeocacheFactory; DbFrontend mDbFrontend; GeocacheFromIntentFactory(GeocacheFactory geocacheFactory, DbFrontend dbFrontend) { mGeocacheFactory = geocacheFactory; mDbFrontend = dbFrontend; } public Geocache viewCacheFromMapsIntent(Intent intent, Geocache defaultGeocache) { final String query = intent.getData().getQuery(); final CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(), UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal()); if (sanitizedQuery == null) return defaultGeocache; final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery); final Geocache geocache = mGeocacheFactory.create(latlon[2], latlon[3], Util .parseCoordinate(latlon[0]), Util.parseCoordinate(latlon[1]), Source.WEB_URL, null, CacheType.NULL, 0, 0, 0); geocache.saveToDb(mDbFrontend); return geocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheFactory.Source; import android.content.SharedPreferences; public class GeocacheFromPreferencesFactory { private final GeocacheFactory mGeocacheFactory; public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) { mGeocacheFactory = geocacheFactory; } public Geocache create(SharedPreferences preferences) { final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1); final Source source = mGeocacheFactory.sourceFromInt(Math.max(Source.MIN_SOURCE, Math.min( iSource, Source.MAX_SOURCE))); final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0); final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType); return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences .getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0), preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString( Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt( Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0), preferences.getInt(Geocache.CONTAINER, 0)); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.code.geobeagle.activity.main; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ // // public static double distanceKm(GeoPoint p1, GeoPoint p2) { // double lat1 = p1.getLatitudeE6() / (double)MILLION; // double lon1 = p1.getLongitudeE6() / (double)MILLION; // double lat2 = p2.getLatitudeE6() / (double)MILLION; // double lon2 = p2.getLongitudeE6() / (double)MILLION; // // return distanceKm(lat1, lon1, lat2, lon2); // } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ // public static double bearing(GeoPoint p1, GeoPoint p2) { // double lat1 = p1.getLatitudeE6() / (double) MILLION; // double lon1 = p1.getLongitudeE6() / (double) MILLION; // double lat2 = p2.getLatitudeE6() / (double) MILLION; // double lon2 = p2.getLongitudeE6() / (double) MILLION; // // return bearing(lat1, lon1, lat2, lon2); // } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.IPausable; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.actions.MenuActions; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.main.view.FavoriteView; import com.google.code.geobeagle.activity.main.view.GeocacheViewer; import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler; import com.google.code.geobeagle.activity.main.view.FavoriteView.FavoriteState; import com.google.code.geobeagle.activity.main.view.FavoriteView.FavoriteViewDelegate; import com.google.code.geobeagle.database.DbFrontend; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.text.format.DateFormat; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import java.io.File; public class GeoBeagleDelegate { public static class LogFindClickListener implements OnClickListener { private final GeoBeagle mGeoBeagle; private final int mIdDialog; public LogFindClickListener(GeoBeagle geoBeagle, int idDialog) { mGeoBeagle = geoBeagle; mIdDialog = idDialog; } public void onClick(View v) { mGeoBeagle.showDialog(mIdDialog); } } static class RadarViewRefresher implements Refresher { private final RadarView mRadarView; private final GeoFixProvider mGeoFixProvider; public RadarViewRefresher(RadarView radarView, GeoFixProvider geoFixProvider) { mRadarView = radarView; mGeoFixProvider = geoFixProvider; } @Override public void forceRefresh() { refresh(); } @Override public void refresh() { if (mGeoFixProvider.isProviderEnabled()) mRadarView.setLocation(mGeoFixProvider.getLocation(), mGeoFixProvider.getAzimuth()); else mRadarView.handleUnknownLocation(); } } static class OptionsMenu { private final MenuActions mMenuActions; public OptionsMenu(MenuActions menuActions) { mMenuActions = menuActions; } public boolean onCreateOptionsMenu(Menu menu) { return mMenuActions.onCreateOptionsMenu(menu); } public boolean onOptionsItemSelected(MenuItem item) { return mMenuActions.act(item.getItemId()); } } public static int ACTIVITY_REQUEST_TAKE_PICTURE = 1; private final ActivitySaver mActivitySaver; private Geocache mGeocache; private final GeocacheFactory mGeocacheFactory; private final GeocacheViewer mGeocacheViewer; private final IncomingIntentHandler mIncomingIntentHandler; private final DbFrontend mDbFrontend; private final GeoBeagle mParent; private final RadarView mRadarView; private final SharedPreferences mSharedPreferences; private final WebPageAndDetailsButtonEnabler mWebPageButtonEnabler; private final IPausable mGeoFixProvider; private final FavoriteView mFavoriteView; public GeoBeagleDelegate(ActivitySaver activitySaver, GeoBeagle parent, GeocacheFactory geocacheFactory, GeocacheViewer geocacheViewer, IncomingIntentHandler incomingIntentHandler, DbFrontend dbFrontend, RadarView radarView, SharedPreferences sharedPreferences, WebPageAndDetailsButtonEnabler webPageButtonEnabler, IPausable geoFixProvider, FavoriteView favoriteView) { mParent = parent; mActivitySaver = activitySaver; mSharedPreferences = sharedPreferences; mRadarView = radarView; mGeocacheViewer = geocacheViewer; mWebPageButtonEnabler = webPageButtonEnabler; mGeocacheFactory = geocacheFactory; mIncomingIntentHandler = incomingIntentHandler; mDbFrontend = dbFrontend; mGeoFixProvider = geoFixProvider; mFavoriteView = favoriteView; } public Geocache getGeocache() { return mGeocache; } private void onCameraStart() { String filename = "/sdcard/GeoBeagle/" + mGeocache.getId() + DateFormat.format(" yyyy-MM-dd kk.mm.ss.jpg", System.currentTimeMillis()); Log.d("GeoBeagle", "capturing image to " + filename); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename))); mParent.startActivityForResult(intent, GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE); } public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_CAMERA && event.getRepeatCount() == 0) { onCameraStart(); return true; } return false; } public void onPause() { mGeoFixProvider.onPause(); mActivitySaver.save(ActivityType.VIEW_CACHE, mGeocache); mDbFrontend.closeDatabase(); } public void onRestoreInstanceState(Bundle savedInstanceState) { CharSequence id = savedInstanceState.getCharSequence(Geocache.ID); if (id == null || id.equals("")) mGeocache = null; else mGeocache = mDbFrontend.loadCacheFromId(id.toString()); if (mGeocache == null) mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "", CacheType.NULL, 0, 0, 0); } public void onResume() { mRadarView.handleUnknownLocation(); mGeoFixProvider.onResume(); mRadarView.setUseImperial(mSharedPreferences.getBoolean("imperial", false)); mGeocache = mIncomingIntentHandler.maybeGetGeocacheFromIntent(mParent.getIntent(), mGeocache, mDbFrontend); // Possible fix for issue 53. if (mGeocache == null) { mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "", CacheType.NULL, 0, 0, 0); } mGeocacheViewer.set(mGeocache); final FavoriteState favoriteState = new FavoriteState(mDbFrontend, mGeocache.getId()); final FavoriteViewDelegate favoriteViewDelegate = new FavoriteViewDelegate( mFavoriteView, favoriteState); mFavoriteView.setGeocache(favoriteViewDelegate); mWebPageButtonEnabler.check(); } public void onSaveInstanceState(Bundle outState) { // apparently there are cases where getGeocache returns null, causing // crashes with 0.7.7/0.7.8. if (mGeocache == null) outState.putCharSequence(Geocache.ID, ""); else outState.putCharSequence(Geocache.ID, mGeocache.getId()); } public void setGeocache(Geocache geocache) { mGeocache = geocache; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.intents; import com.google.code.geobeagle.Geocache; public interface GeocacheToUri { public String convert(Geocache geocache); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.intents; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.content.Context; import java.net.URLEncoder; import java.util.Locale; public class GeocacheToGoogleMap implements GeocacheToUri { private final Context mContext; public GeocacheToGoogleMap(Context context) { mContext = context; } /* * (non-Javadoc) * @see * com.google.code.geobeagle.activity.main.intents.GeocacheToUri#convert * (com.google.code.geobeagle.Geocache) */ public String convert(Geocache geocache) { // "geo:%1$.5f,%2$.5f?name=cachename" String idAndName = geocache.getIdAndName().toString(); idAndName = idAndName.replace("(", "["); idAndName = idAndName.replace(")", "]"); idAndName = URLEncoder.encode(idAndName); final String format = String.format(Locale.US, mContext .getString(R.string.map_intent), geocache.getLatitude(), geocache.getLongitude(), idAndName); return format; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.intents; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.content.res.Resources; /* * Convert a Geocache to the cache page url. */ public class GeocacheToCachePage implements GeocacheToUri { private final Resources mResources; public GeocacheToCachePage(Resources resources) { mResources = resources; } // TODO: move strings into Provider enum. public String convert(Geocache geocache) { return String.format(mResources.getStringArray(R.array.cache_page_url)[geocache .getContentProvider().toInt()], geocache.getShortId()); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.intents; import com.google.code.geobeagle.activity.main.UriParser; import android.content.Intent; public class IntentFactory { private final UriParser mUriParser; public IntentFactory(UriParser uriParser) { mUriParser = uriParser; } public Intent createIntent(String action, String uri) { return new Intent(action, mUriParser.parse(uri)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import android.content.res.Resources; public class FieldnoteStringsFVsDnf { private final Resources mResources; public FieldnoteStringsFVsDnf(Resources resources) { mResources = resources; } String getString(int id, boolean dnf) { return mResources.getStringArray(id)[dnf ? 0 : 1]; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Toaster; import com.google.code.geobeagle.activity.main.DateFormatter; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.util.Date; /** * Writes lines formatted like: * * <pre> * GC1FX1A,2008-09-27T21:04Z, Found it,&quot;log text&quot; * </pre> */ public class FileLogger implements ICacheLogger { private final Toaster mErrorToaster; private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; private final DateFormatter mSimpleDateFormat; public FileLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, DateFormatter simpleDateFormat, Toaster errorToaster) { mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; mSimpleDateFormat = simpleDateFormat; mErrorToaster = errorToaster; } public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { try { OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream( FieldnoteLogger.FIELDNOTES_FILE, true), "UTF-16"); final Date date = new Date(); final String formattedDate = mSimpleDateFormat.format(date); final String logLine = String.format("%1$s,%2$s,%3$s,\"%4$s\"\n", geocacheId, formattedDate, mFieldnoteStringsFVsDnf.getString(R.array.fieldnote_file_code, dnf), logText.toString()); writer.write(logLine); writer.close(); } catch (IOException e) { mErrorToaster.showToast(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.R; import android.content.Context; import android.content.Intent; public class SmsLogger implements ICacheLogger { private final Context mContext; private final FieldnoteStringsFVsDnf mFieldNoteStringsFoundVsDnf; public SmsLogger(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, Context context) { mFieldNoteStringsFoundVsDnf = fieldnoteStringsFVsDnf; mContext = context; } @Override public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { Intent sendIntent = new Intent(Intent.ACTION_VIEW); sendIntent.putExtra("address", "41411"); sendIntent.putExtra("sms_body", mFieldNoteStringsFoundVsDnf.getString( R.array.fieldnote_code, dnf) + geocacheId + " " + logText); sendIntent.setType("vnd.android-dir/mms-sms"); mContext.startActivity(sendIntent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import android.app.Dialog; public interface DialogHelper { public abstract void configureEditor(); public abstract void configureDialogText(Dialog dialog); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.R; import android.text.util.Linkify; import android.widget.EditText; import android.widget.TextView; public class DialogHelperCommon { private final boolean mDnf; private final EditText mEditText; private final TextView mFieldnoteCaveat; private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; public DialogHelperCommon(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, EditText editText, boolean dnf, TextView fieldnoteCaveat) { mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; mDnf = dnf; mEditText = editText; mFieldnoteCaveat = fieldnoteCaveat; } public void configureDialogText() { Linkify.addLinks(mFieldnoteCaveat, Linkify.WEB_URLS); } public void configureEditor(String localDate) { final String defaultMessage = mFieldnoteStringsFVsDnf.getString(R.array.default_msg, mDnf); final String msg = String.format("(%1$s/%2$s) %3$s", localDate, mFieldnoteStringsFVsDnf .getString(R.array.geobeagle_sig, mDnf), defaultMessage); mEditText.setText(msg); final int len = msg.length(); mEditText.setSelection(len - defaultMessage.length(), len); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.R; import android.app.Dialog; import android.text.InputFilter; import android.text.InputFilter.LengthFilter; import android.widget.EditText; import android.widget.TextView; public class DialogHelperSms implements DialogHelper { private final EditText mEditText; private final boolean mFDnf; private final TextView mFieldnoteCaveat; private final FieldnoteStringsFVsDnf mFieldnoteStringsFVsDnf; private final int mGeocacheIdLength; public DialogHelperSms(int geocacheIdLength, FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf, EditText editText, boolean dnf, TextView fieldnoteCaveat) { mGeocacheIdLength = geocacheIdLength; mFieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf; mEditText = editText; mFDnf = dnf; mFieldnoteCaveat = fieldnoteCaveat; } @Override public void configureEditor() { final LengthFilter lengthFilter = new LengthFilter( 160 - (mGeocacheIdLength + 1 + mFieldnoteStringsFVsDnf.getString( R.array.fieldnote_code, mFDnf).length())); mEditText.setFilters(new InputFilter[] { lengthFilter }); } @Override public void configureDialogText(Dialog dialog) { mFieldnoteCaveat.setText(R.string.sms_caveat); dialog.setTitle(R.string.log_cache_with_sms); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.database.DbFrontend; import android.app.Dialog; import android.content.DialogInterface; import android.content.SharedPreferences; import android.content.DialogInterface.OnClickListener; import android.widget.EditText; public class FieldnoteLogger { // TODO: share one onClickCancel across app. public static class OnClickCancel implements OnClickListener { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } } public static class OnClickOk implements OnClickListener { private final CacheLogger mCacheLogger; private final boolean mDnf; private final EditText mEditText; private final DbFrontend mDbFrontend; private final CharSequence mGeocacheId; public OnClickOk(CharSequence geocacheId, EditText editText, CacheLogger cacheLogger, DbFrontend dbFrontend, boolean dnf) { mGeocacheId = geocacheId; mEditText = editText; mCacheLogger = cacheLogger; mDbFrontend = dbFrontend; mDnf = dnf; } @Override public void onClick(DialogInterface arg0, int arg1) { mCacheLogger.log(mGeocacheId, mEditText.getText(), mDnf); mDbFrontend.setGeocacheTag(mGeocacheId, Tags.DNF, mDnf); mDbFrontend.setGeocacheTag(mGeocacheId, Tags.FOUND, !mDnf); } } static final String FIELDNOTES_FILE = "/sdcard/GeoBeagleFieldNotes.txt"; private final DialogHelperCommon mDialogHelperCommon; private final DialogHelperFile mDialogHelperFile; private final DialogHelperSms mDialogHelperSms; public FieldnoteLogger(DialogHelperCommon dialogHelperCommon, DialogHelperFile dialogHelperFile, DialogHelperSms dialogHelperSms) { mDialogHelperSms = dialogHelperSms; mDialogHelperFile = dialogHelperFile; mDialogHelperCommon = dialogHelperCommon; } public void onPrepareDialog(Dialog dialog, SharedPreferences defaultSharedPreferences, String localDate) { final boolean fieldNoteTextFile = defaultSharedPreferences.getBoolean( "field-note-text-file", false); DialogHelper dialogHelper = fieldNoteTextFile ? mDialogHelperFile : mDialogHelperSms; dialogHelper.configureDialogText(dialog); mDialogHelperCommon.configureDialogText(); dialogHelper.configureEditor(); mDialogHelperCommon.configureEditor(localDate); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; interface ICacheLogger { public void log(CharSequence geocacheId, CharSequence logText, boolean dnf); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import android.content.SharedPreferences; public class CacheLogger implements ICacheLogger { private final FileLogger mFileLogger; private final SharedPreferences mSharedPreferences; private final SmsLogger mSmsLogger; public CacheLogger(SharedPreferences sharedPreferences, FileLogger fileLogger, SmsLogger smsLogger) { mSharedPreferences = sharedPreferences; mFileLogger = fileLogger; mSmsLogger = smsLogger; } @Override public void log(CharSequence geocacheId, CharSequence logText, boolean dnf) { final boolean fFieldNoteTextFile = mSharedPreferences.getBoolean( "field-note-text-file", false); if (fFieldNoteTextFile) mFileLogger.log(geocacheId, logText, dnf); else mSmsLogger.log(geocacheId, logText, dnf); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.main.fieldnotes; import com.google.code.geobeagle.R; import android.app.Dialog; import android.content.Context; import android.widget.TextView; public class DialogHelperFile implements DialogHelper { private Context mContext; private final TextView mFieldnoteCaveat; public DialogHelperFile(TextView fieldNoteCaveat, Context context) { mFieldnoteCaveat = fieldNoteCaveat; mContext = context; } @Override public void configureEditor() { } @Override public void configureDialogText(Dialog dialog) { mFieldnoteCaveat.setText(String.format(mContext.getString(R.string.field_note_file_caveat), FieldnoteLogger.FIELDNOTES_FILE)); dialog.setTitle(R.string.log_cache_to_file); } }
Java
package com.google.code.geobeagle.activity.cachelist.presenter; public class AbsoluteBearingFormatter implements BearingFormatter { private static final String[] LETTERS = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; public String formatBearing(float absBearing, float myHeading) { return LETTERS[((((int)(absBearing) + 22 + 720) % 360) / 45)]; } }
Java
package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.database.CachesProviderToggler; import com.google.code.geobeagle.database.DistanceAndBearing; import com.google.code.geobeagle.database.DistanceAndBearing.IDistanceAndBearingProvider; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.BaseAdapter; import android.widget.AbsListView.OnScrollListener; import java.util.AbstractList; /** Feeds the caches in a CachesProvider to the GUI list view */ public class CacheListAdapter extends BaseAdapter implements Refresher { private final CachesProviderToggler mProvider; private final IDistanceAndBearingProvider mDistances; private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater; private final TitleUpdater mTitleUpdater; private AbstractList<Geocache> mListData; private float mAzimuth; private boolean mUpdatesEnabled = true; public static class ScrollListener implements OnScrollListener { private final CacheListAdapter mCacheListAdapter; public ScrollListener(CacheListAdapter updateFlag) { mCacheListAdapter = updateFlag; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mCacheListAdapter.enableUpdates(scrollState == SCROLL_STATE_IDLE); } } public CacheListAdapter(CachesProviderToggler provider, IDistanceAndBearingProvider distances, GeocacheSummaryRowInflater inflater, TitleUpdater titleUpdater, AbstractList<Geocache> listData) { mProvider = provider; mGeocacheSummaryRowInflater = inflater; mTitleUpdater = titleUpdater; mDistances = distances; mListData = listData; } public void enableUpdates(boolean enable) { mUpdatesEnabled = enable; if (enable) refresh(); } public void setAzimuth (float azimuth) { mAzimuth = azimuth; } /** Updates the GUI from the Provider if necessary */ @Override public void refresh() { if (!mUpdatesEnabled || !mProvider.hasChanged()) { return; } forceRefresh(); } public void forceRefresh() { mListData = mProvider.getCaches(); mProvider.resetChanged(); mTitleUpdater.refresh(); notifyDataSetChanged(); } public int getCount() { if (mListData == null) return 0; return mListData.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } /** Get the geocache for a certain row in the displayed list, starting with zero */ public Geocache getGeocacheAt(int position) { if (mListData == null) return null; Geocache cache = mListData.get(position); return cache; } public View getView(int position, View convertView, ViewGroup parent) { if (mListData == null) return null; //What happens in this case? View view = mGeocacheSummaryRowInflater.inflate(convertView); Geocache cache = mListData.get(position); DistanceAndBearing geocacheVector = mDistances.getDistanceAndBearing(cache); mGeocacheSummaryRowInflater.setData(view, geocacheVector, mAzimuth); return view; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.database.CachesProviderToggler; import com.google.code.geobeagle.database.DbFrontend; import android.app.ListActivity; import android.widget.TextView; public class TitleUpdater implements RefreshAction { private final CachesProviderToggler mCachesProviderToggler; private final ListActivity mListActivity; private final DbFrontend mDbFrontend; private final TextSelector mTextSelector; public static class TextSelector { int getTitle(boolean isShowingNearest) { return isShowingNearest ? R.string.cache_list_title : R.string.cache_list_title_all; } int getNoNearbyCachesText(int allCachesCount) { return allCachesCount > 0 ? R.string.no_nearby_caches : R.string.no_caches; } } public TitleUpdater(ListActivity listActivity, CachesProviderToggler cachesProviderToggler, DbFrontend dbFrontend, TextSelector textSelector) { mListActivity = listActivity; mCachesProviderToggler = cachesProviderToggler; mDbFrontend = dbFrontend; mTextSelector = textSelector; } public void refresh() { int sqlCount = mDbFrontend.count(null); // count all caches int nearestCachesCount = mCachesProviderToggler.getCount(); int title = mTextSelector.getTitle(mCachesProviderToggler.isShowingNearest()); mListActivity.setTitle(mListActivity.getString(title, nearestCachesCount, sqlCount)); if (0 == nearestCachesCount) { final int noNearbyCachesText = mTextSelector .getNoNearbyCachesText(sqlCount); final TextView emptyTextView = (TextView)mListActivity .findViewById(android.R.id.empty); emptyTextView.setText(noNearbyCachesText); } } }
Java