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.activity.cachelist.presenter;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GraphicsGenerator;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater.RowViews.CacheNameAttributes;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.DistanceAndBearing;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheSummaryRowInflater implements HasDistanceFormatter {
public static class RowViews {
private final TextView mAttributes;
private final TextView mCacheName;
private final TextView mDistance;
private final ImageView mIcon;
private final TextView mId;
private final Resources mResources;
private final CacheNameAttributes mCacheNameAttributes;
RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon,
TextView id, Resources resources, CacheNameAttributes cacheNameAttributes) {
mAttributes = attributes;
mCacheName = cacheName;
mDistance = distance;
mIcon = icon;
mId = id;
mResources = resources;
mCacheNameAttributes = cacheNameAttributes;
}
public static class CacheNameAttributes {
void setTextColor(boolean fArchived, boolean fUnavailable,
TextView cacheName) {
if (fArchived)
cacheName.setTextColor(Color.DKGRAY);
else if (fUnavailable)
cacheName.setTextColor(Color.LTGRAY);
else
cacheName.setTextColor(Color.WHITE);
}
void setStrikethrough(boolean fArchived, boolean fUnavailable,
TextView cacheName) {
if (fArchived || fUnavailable)
cacheName.setPaintFlags(cacheName.getPaintFlags()
| Paint.STRIKE_THRU_TEXT_FLAG);
else
cacheName.setPaintFlags(cacheName.getPaintFlags()
& ~Paint.STRIKE_THRU_TEXT_FLAG);
}
}
private CharSequence getFormattedDistance(
DistanceAndBearing distanceAndBearing, float azimuth,
DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter) {
// Use the slower, more accurate distance for display.
double distance = distanceAndBearing.getDistance();
if (distance == -1) {
return "";
}
final CharSequence formattedDistance = distanceFormatter
.formatDistance((float)distance);
float bearing = distanceAndBearing.getBearing();
final String formattedBearing = relativeBearingFormatter.formatBearing(bearing,
azimuth);
return formattedDistance + " " + formattedBearing;
}
void set(DistanceAndBearing distanceAndBearing, float azimuth,
DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter,
GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) {
//CacheType type = geocacheVector.getGeocache().getCacheType();
//mIcon.setImageResource(type.icon());
Geocache geocache = distanceAndBearing.getGeocache();
mIcon.setImageDrawable(geocache.getIcon(mResources, graphicsGenerator, dbFrontend));
CharSequence geocacheId = geocache.getId();
mId.setText(geocacheId);
mAttributes.setText(geocache.getFormattedAttributes());
mCacheName.setText(geocache.getName());
boolean fArchived = dbFrontend.geocacheHasTag(geocacheId,
Tags.ARCHIVED);
boolean fUnavailable = dbFrontend.geocacheHasTag(geocacheId,
Tags.UNAVAILABLE);
mCacheNameAttributes.setTextColor(fArchived, fUnavailable,
mCacheName);
mCacheNameAttributes.setStrikethrough(fArchived, fUnavailable,
mCacheName);
mDistance.setText(getFormattedDistance(distanceAndBearing, azimuth, distanceFormatter,
relativeBearingFormatter));
}
}
private BearingFormatter mBearingFormatter;
private DistanceFormatter mDistanceFormatter;
private final LayoutInflater mLayoutInflater;
private final Resources mResources;
private final GraphicsGenerator mGraphicsGenerator;
private final DbFrontend mDbFrontend;
private final CacheNameAttributes mCacheNameAttributes;
public GeocacheSummaryRowInflater(DistanceFormatter distanceFormatter,
LayoutInflater layoutInflater,
BearingFormatter relativeBearingFormatter, Resources resources,
GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend,
CacheNameAttributes cacheNameAttributes) {
mLayoutInflater = layoutInflater;
mDistanceFormatter = distanceFormatter;
mBearingFormatter = relativeBearingFormatter;
mResources = resources;
mGraphicsGenerator = graphicsGenerator;
mDbFrontend = dbFrontend;
mCacheNameAttributes = cacheNameAttributes;
}
BearingFormatter getBearingFormatter() {
return mBearingFormatter;
}
public View inflate(View convertView) {
if (convertView != null)
return convertView;
// Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")");
View view = mLayoutInflater.inflate(R.layout.cache_row, null);
RowViews rowViews = new RowViews((TextView)view
.findViewById(R.id.txt_gcattributes), ((TextView)view
.findViewById(R.id.txt_cache)), ((TextView)view
.findViewById(R.id.distance)), ((ImageView)view
.findViewById(R.id.gc_row_icon)), ((TextView)view
.findViewById(R.id.txt_gcid)), mResources, mCacheNameAttributes);
view.setTag(rowViews);
return view;
}
public void setBearingFormatter(boolean absoluteBearing) {
mBearingFormatter = absoluteBearing ? new AbsoluteBearingFormatter()
: new RelativeBearingFormatter();
}
public void setData(View view, DistanceAndBearing geocacheVector, float azimuth) {
((RowViews)view.getTag()).set(geocacheVector, azimuth, mDistanceFormatter,
mBearingFormatter, mGraphicsGenerator, mDbFrontend);
}
public void setDistanceFormatter(DistanceFormatter distanceFormatter) {
mDistanceFormatter = distanceFormatter;
}
}
| 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.formatting.DistanceFormatter;
public interface HasDistanceFormatter {
public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter);
}
| 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;
public class RelativeBearingFormatter implements BearingFormatter {
private static final String[] ARROWS = {
"^", ">", "v", "<",
};
public String formatBearing(float absBearing, float myHeading) {
return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)];
}
}
| 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.formatting.DistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.SharedPreferences;
import java.util.ArrayList;
public class DistanceFormatterManager {
private ArrayList<HasDistanceFormatter> mHasDistanceFormatters;
private final DistanceFormatterMetric mDistanceFormatterMetric;
private final DistanceFormatterImperial mDistanceFormatterImperial;
private final SharedPreferences mDefaultSharedPreferences;
DistanceFormatterManager(SharedPreferences defaultSharedPreferences,
DistanceFormatterImperial distanceFormatterImperial,
DistanceFormatterMetric distanceFormatterMetric) {
mDistanceFormatterImperial = distanceFormatterImperial;
mDistanceFormatterMetric = distanceFormatterMetric;
mDefaultSharedPreferences = defaultSharedPreferences;
mHasDistanceFormatters = new ArrayList<HasDistanceFormatter>(2);
}
public void addHasDistanceFormatter(HasDistanceFormatter hasDistanceFormatter) {
mHasDistanceFormatters.add(hasDistanceFormatter);
}
public DistanceFormatter getFormatter() {
final boolean imperial = mDefaultSharedPreferences.getBoolean("imperial", false);
return imperial ? mDistanceFormatterImperial : mDistanceFormatterMetric;
}
public void setFormatter() {
final DistanceFormatter formatter = getFormatter();
for (HasDistanceFormatter hasDistanceFormatter : mHasDistanceFormatters) {
hasDistanceFormatter.setDistanceFormatter(formatter);
}
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.database.CachesProviderCenterThread;
import com.google.code.geobeagle.database.ICachesProviderCenter;
/** Sends location and azimuth updates to CacheList
* when the user position changes. */
public class CacheListPositionUpdater implements Refresher {
private final CacheListAdapter mCacheList;
private final GeoFixProvider mGeoFixProvider;
private final ICachesProviderCenter mSearchCenter;
private final CachesProviderCenterThread mSortCenterThread;
public CacheListPositionUpdater(GeoFixProvider geoFixProvider,
CacheListAdapter cacheList, ICachesProviderCenter searchCenter,
CachesProviderCenterThread sortCenter) {
mGeoFixProvider = geoFixProvider;
mCacheList = cacheList;
mSearchCenter = searchCenter;
mSortCenterThread = sortCenter;
}
public void refresh() {
final GeoFix location = mGeoFixProvider.getLocation();
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
mSearchCenter.setCenter(latitude, longitude);
mSortCenterThread.setCenter(latitude, longitude, mCacheList);
}
}
@Override
public void forceRefresh() {
refresh();
}
}
| 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;
public interface RefreshAction {
public void refresh();
} | Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
public interface BearingFormatter {
public abstract String formatBearing(float absBearing, float myHeading);
}
| 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;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.actions.CacheFilterUpdater;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.cachelist.actions.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class GeocacheListController {
public static final String SELECT_CACHE = "SELECT_CACHE";
private final CacheListAdapter mCacheListAdapter;
private final MenuActions mMenuActions;
private final MenuActionSyncGpx mMenuActionSyncGpx;
private final CacheAction mDefaultCacheAction;
private final CacheFilterUpdater mCacheFilterUpdater;
public GeocacheListController(CacheListAdapter cacheListAdapter,
MenuActionSyncGpx menuActionSyncGpx,
MenuActions menuActions,
CacheAction defaultCacheAction,
CacheFilterUpdater cacheFilterUpdater) {
mCacheListAdapter = cacheListAdapter;
mMenuActionSyncGpx = menuActionSyncGpx;
mMenuActions = menuActions;
mDefaultCacheAction = defaultCacheAction;
mCacheFilterUpdater = cacheFilterUpdater;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public void onListItemClick(ListView l, View v, int position, long id) {
if (position > 0) {
mDefaultCacheAction.act(mCacheListAdapter.getGeocacheAt(position - 1));
} else {
mCacheListAdapter.forceRefresh();
}
}
public boolean onMenuOpened(int featureId, Menu menu) {
return mMenuActions.onMenuOpened(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
public void onPause() {
mMenuActionSyncGpx.abort();
}
public void onResume(boolean fImport) {
mCacheFilterUpdater.loadActiveFilter();
mCacheListAdapter.forceRefresh();
if (fImport)
mMenuActionSyncGpx.act();
}
}
| 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.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.database.CachesProviderToggler;
import android.content.res.Resources;
public class MenuActionToggleFilter implements MenuAction {
private final CachesProviderToggler mCachesProviderToggler;
private final CacheListAdapter mListRefresher;
private final Resources mResources;
public MenuActionToggleFilter(CachesProviderToggler cachesProviderToggler,
CacheListAdapter cacheListRefresh, Resources resources) {
mCachesProviderToggler = cachesProviderToggler;
mListRefresher = cacheListRefresh;
mResources = resources;
}
public void act() {
mCachesProviderToggler.toggle();
mListRefresher.forceRefresh();
}
@Override
public String getLabel() {
if (mCachesProviderToggler.isShowingNearest())
return mResources.getString(R.string.menu_show_all_caches);
else
return mResources.getString(R.string.menu_show_nearest_caches);
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.actions;
public interface Abortable {
public void abort();
}
| 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.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Tags;
import com.google.code.geobeagle.actions.ActionStaticLabel;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.activity.cachelist.GpxImporterFactory;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.xmlimport.GpxImporter;
import android.content.res.Resources;
public class MenuActionSyncGpx extends ActionStaticLabel implements MenuAction {
private Abortable mAbortable;
private final CacheListAdapter mCacheList;
private final GpxImporterFactory mGpxImporterFactory;
private final DbFrontend mDbFrontend;
public MenuActionSyncGpx(Abortable abortable, CacheListAdapter cacheList,
GpxImporterFactory gpxImporterFactory, DbFrontend dbFrontend,
Resources resources) {
super(resources, R.string.menu_sync);
mAbortable = abortable;
mCacheList = cacheList;
mGpxImporterFactory = gpxImporterFactory;
mDbFrontend = dbFrontend;
}
public void abort() {
mAbortable.abort();
}
@Override
public void act() {
//Only the most recent batch of caches is shown as 'new'
mDbFrontend.clearTagForAllCaches(Tags.NEW);
final GpxImporter gpxImporter = mGpxImporterFactory.create(mDbFrontend.getCacheWriter());
mAbortable = gpxImporter;
gpxImporter.importGpxs(mCacheList);
}
}
| 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.actions;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeoFix;
import com.google.code.geobeagle.GeoFixProvider;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.actions.ActionStaticLabel;
import com.google.code.geobeagle.actions.CacheAction;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.database.DbFrontend;
import android.content.res.Resources;
public class MenuActionMyLocation extends ActionStaticLabel implements MenuAction {
private final ErrorDisplayer mErrorDisplayer;
private final DbFrontend mDbFrontend;
private final GeocacheFactory mGeocacheFactory;
private final GeoFixProvider mLocationControl;
private final CacheAction mCacheActionEdit;
public MenuActionMyLocation(ErrorDisplayer errorDisplayer,
GeocacheFactory geocacheFactory,
GeoFixProvider locationControl, DbFrontend dbFrontend,
Resources resources, CacheAction cacheActionEdit) {
super(resources, R.string.menu_add_my_location);
mErrorDisplayer = errorDisplayer;
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
mDbFrontend = dbFrontend;
mCacheActionEdit = cacheActionEdit;
}
@Override
public void act() {
GeoFix location = mLocationControl.getLocation();
if (location == null)
return;
long time = location.getTime();
final Geocache newCache = mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format(
"[%1$tk:%1$tM] My Location", time), location.getLatitude(),
location.getLongitude(), Source.MY_LOCATION, "mylocation", CacheType.MY_LOCATION, 0, 0, 0);
if (newCache == null) {
mErrorDisplayer.displayError(R.string.current_location_null);
return;
}
newCache.saveToDb(mDbFrontend);
mCacheActionEdit.act(newCache);
//Since the Edit activity will refresh the list, we don't need to do it
//mListRefresher.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.cachelist;
import com.google.code.geobeagle.IPausable;
import com.google.code.geobeagle.actions.CacheContextMenu;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.database.CachesProviderDb;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheListDelegate {
static class ImportIntentManager {
static final String INTENT_EXTRA_IMPORT_TRIGGERED = "com.google.code.geabeagle.import_triggered";
private final Activity mActivity;
ImportIntentManager(Activity activity) {
mActivity = activity;
}
boolean isImport() {
final Intent intent = mActivity.getIntent();
if (intent == null)
return false;
String action = intent.getAction();
if (action == null)
return false;
if (!action.equals("android.intent.action.VIEW"))
return false;
if (intent.getBooleanExtra(INTENT_EXTRA_IMPORT_TRIGGERED, false))
return false;
// Need to alter the intent so that the import isn't retriggered if
// pause/resume is a result of the phone going to sleep and then
// waking up again.
intent.putExtra(INTENT_EXTRA_IMPORT_TRIGGERED, true);
return true;
}
}
private final ActivitySaver mActivitySaver;
private final GeocacheListController mController;
private final DbFrontend mDbFrontend;
private final ImportIntentManager mImportIntentManager;
private final CacheContextMenu mContextMenu;
private final CacheListAdapter mCacheList;
private final ListActivity mListActivity;
private final DistanceFormatterManager mDistanceFormatterManager;
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final CachesProviderDb mCachesToFlush;
private final IPausable[] mPausables;
public CacheListDelegate(ImportIntentManager importIntentManager, ActivitySaver activitySaver,
GeocacheListController geocacheListController,
DbFrontend dbFrontend,
CacheContextMenu menuCreator,
CacheListAdapter cacheList,
GeocacheSummaryRowInflater geocacheSummaryRowInflater,
ListActivity listActivity,
DistanceFormatterManager distanceFormatterManager,
CachesProviderDb cachesToFlush,
IPausable[] pausables) {
mActivitySaver = activitySaver;
mController = geocacheListController;
mImportIntentManager = importIntentManager;
mDbFrontend = dbFrontend;
mContextMenu = menuCreator;
mCacheList = cacheList;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
mListActivity = listActivity;
mDistanceFormatterManager = distanceFormatterManager;
mCachesToFlush = cachesToFlush;
mPausables = pausables;
}
public boolean onContextItemSelected(MenuItem menuItem) {
return mContextMenu.onContextItemSelected(menuItem);
}
public boolean onCreateOptionsMenu(Menu menu) {
return mController.onCreateOptionsMenu(menu);
}
public void onListItemClick(ListView l, View v, int position, long id) {
mController.onListItemClick(l, v, position, id);
}
public boolean onMenuOpened(int featureId, Menu menu) {
return mController.onMenuOpened(featureId, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
return mController.onOptionsItemSelected(item);
}
public void onPause() {
for (IPausable pausable : mPausables)
pausable.onPause();
mController.onPause();
mActivitySaver.save(ActivityType.CACHE_LIST);
mDbFrontend.closeDatabase();
}
public void onResume() {
Log.d("GeoBeagle", "CacheListDelegate.onResume()");
mDistanceFormatterManager.setFormatter();
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(mListActivity);
final boolean absoluteBearing = sharedPreferences.getBoolean("absolute-bearing", false);
mGeocacheSummaryRowInflater.setBearingFormatter(absoluteBearing);
mController.onResume(mImportIntentManager.isImport());
for (IPausable pausable : mPausables)
pausable.onResume();
}
public void onActivityResult() {
Log.d("GeoBeagle", "CacheListDelegate.onActivityResult()");
mCachesToFlush.notifyOfDbChange();
mCacheList.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;
import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
/** Invoked from SearchOnlineActivity to restore the last GeoBeagle activity */
public class ActivityRestorer {
public static class CacheListRestorer implements Restorer {
private final Activity mActivity;
public CacheListRestorer(Activity activity) {
mActivity = activity;
}
@Override
public void restore() {
mActivity.startActivity(new Intent(mActivity, CacheListActivity.class));
mActivity.finish();
}
}
public static class NullRestorer implements Restorer {
@Override
public void restore() {
}
}
public interface Restorer {
void restore();
}
public static class ViewCacheRestorer implements Restorer {
private final Activity mActivity;
private final SharedPreferences mSharedPreferences;
public ViewCacheRestorer(SharedPreferences sharedPreferences, Activity activity) {
mSharedPreferences = sharedPreferences;
mActivity = activity;
}
@Override
public void restore() {
String id = mSharedPreferences.getString("geocacheId", "");
final Intent intent = new Intent(mActivity, GeoBeagle.class);
intent.putExtra("geocacheId", id).setAction(GeocacheListController.SELECT_CACHE);
mActivity.startActivity(intent);
mActivity.finish();
}
}
private final ActivityTypeFactory mActivityTypeFactory;
private final Restorer[] mRestorers;
private final SharedPreferences mSharedPreferences;
public ActivityRestorer(ActivityTypeFactory activityTypeFactory,
SharedPreferences sharedPreferences, Restorer[] restorers) {
mActivityTypeFactory = activityTypeFactory;
mSharedPreferences = sharedPreferences;
mRestorers = restorers;
}
public void restore(int flags) {
if ((flags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0)
return;
final int iLastActivity = mSharedPreferences.getInt(ActivitySaver.LAST_ACTIVITY,
ActivityType.NONE.toInt());
final ActivityType activityType = mActivityTypeFactory.fromInt(iLastActivity);
mRestorers[activityType.toInt()].restore();
}
}
| Java |
/**
*
*/
package com.google.code.geobeagle.activity.prox;
class ScalarParameter extends Parameter {
public ScalarParameter(double accelConst, double attenuation, double init) {
super(accelConst, attenuation, init);
}
public ScalarParameter(double accelConst, double attenuation) {
super(accelConst, attenuation);
}
public ScalarParameter(double init) {
super(init);
}
public ScalarParameter() {
super();
}
@Override
public void update(double deltaSec) {
if (!mIsInited || (mTargetValue == mValue && mChangePerSec == 0))
return;
//First update mChangePerSec, then update mValue
//There is an ideal mChangePerSec for every distance. Move towards it.
double distance = mTargetValue - mValue;
double accel = distance * mAccelConst;
mValue += mChangePerSec * deltaSec + accel*deltaSec*deltaSec/2.0;
mChangePerSec += accel * deltaSec;
mChangePerSec *= Math.pow(mAttenuation, deltaSec);
}
} | Java |
package com.google.code.geobeagle.activity.prox;
/** Contains the value of a single parameter. This abstraction allows for
* animating arbitrary parameters smoothly to their current value. */
public class Parameter {
/** If an initial value has been set */
protected boolean mIsInited = false;
/** Max change in movement towards target value, in delta / (sec^2) */
protected double mValue;
protected double mTargetValue;
/** Delta per second for mValue. Updated to move mValue towards mTargetValue */
protected double mChangePerSec = 0;
/** How quickly the movement towards the correct value accelerates */
protected final double mAccelConst;
/** Part of the speed that is preserved after one second if otherwise unchanged. */
protected final double mAttenuation;
public Parameter(double accelConst, double attenuation, double init) {
mAccelConst = accelConst;
mAttenuation = attenuation;
mTargetValue = init;
mValue = init;
mIsInited = true;
}
public Parameter(double accelConst, double attenuation) {
mAccelConst = accelConst;
mAttenuation = attenuation;
mTargetValue = 0;
mValue = 0;
mIsInited = false;
}
public Parameter(double init) {
mAccelConst = 0.8;
mAttenuation = 0.3;
mTargetValue = init;
mValue = init;
mIsInited = true;
}
public Parameter() {
mAccelConst = 0.8;
mAttenuation = 0.3;
mTargetValue = 0;
mValue = 0;
mIsInited = false;
}
public double get() {
return mValue;
}
public void set(double value) {
if (mIsInited) {
mTargetValue = value;
} else {
mTargetValue = value;
mValue = value;
mIsInited = true;
}
}
//Override this!
/** Animate the value towards its goal given that deltaSec time
* elapsed since last update */
public void update(double deltaSec) { };
} | Java |
package com.google.code.geobeagle.activity.prox;
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.database.CachesProviderCount;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.RadialGradient;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Paint.Style;
import android.graphics.Shader.TileMode;
import android.util.Log;
import java.util.AbstractList;
public class ProximityPainter {
//private int mUserX;
/** Where on the display to show the user's location */
private int mUserY;
/* X center of display */
private int mCenterX;
/** Higher value means that big distances are compressed relatively more */
private double mLogScale = 1.25;
private final int mUserScreenRadius = 25;
private Paint mTextPaint;
private Paint mDistancePaint;
private Paint mMainDistancePaint;
private Paint mCachePaint;
private Paint mUserPaint;
private Paint mSpeedPaint;
private Paint mAccuracyPaint;
private Paint mCompassNorthPaint;
private Paint mCompassSouthPaint;
private Paint mGlowPaint;
private final CachesProviderCount mCachesProvider;
private Geocache mSelectedGeocache;
/** Which direction the device is pointed, in degrees */
private Parameter mDeviceDirection = new AngularParameter(0.03, 0.3);
/** Location reading accuracy in meters */
private Parameter mGpsAccuracy = new ScalarParameter(4.0);
private Parameter mScaleFactor = new ScalarParameter(12.0);
/** The speed of the user, measured using GPS */
private Parameter mUserSpeed = new ScalarParameter(0);
/** Which way the user is moving */
private Parameter mUserDirection = new AngularParameter(0.03, 0.3);
private Parameter mLatitude = new ScalarParameter();
private Parameter mLongitude = new ScalarParameter();
private Rect mTempBounds = new Rect();
private Parameter[] allParameters = { mDeviceDirection, mGpsAccuracy,
mScaleFactor, mUserSpeed, mUserDirection, mLatitude, mLongitude };
public ProximityPainter(CachesProviderCount cachesProvider) {
mCachesProvider = cachesProvider;
mUserY = 350;
//mUseImerial = mSharedPreferences.getBoolean("imperial", false);
mTextPaint = new Paint();
mTextPaint.setColor(Color.GREEN);
mDistancePaint = new Paint();
mDistancePaint.setARGB(255, 0, 96, 0);
mDistancePaint.setStyle(Style.STROKE);
mDistancePaint.setStrokeWidth(2);
mDistancePaint.setAntiAlias(true);
mMainDistancePaint = new Paint(mDistancePaint);
mMainDistancePaint.setARGB(255, 0, 200, 0);
mMainDistancePaint.setStrokeWidth(4);
mCachePaint = new Paint();
mCachePaint.setARGB(255, 200, 200, 248);
mCachePaint.setStyle(Style.STROKE);
mCachePaint.setStrokeWidth(2);
mCachePaint.setAntiAlias(true);
int userColor = Color.argb(255, 216, 176, 128);
//mGlowShader = new RadialGradient(0, 0,
// (int)mGpsAccuracy.get(), 0x2000ff00, 0xc000ff00, TileMode.CLAMP);
mAccuracyPaint = new Paint();
//mAccuracyPaint.setShader(mGlowShader);
mAccuracyPaint.setStrokeWidth(6);
mAccuracyPaint.setStyle(Style.STROKE);
mAccuracyPaint.setColor(userColor);
float[] intervals = { 20, 10};
mAccuracyPaint.setPathEffect(new DashPathEffect(intervals, 5));
mAccuracyPaint.setAntiAlias(true);
mUserPaint = new Paint();
mUserPaint.setColor(userColor);
mUserPaint.setStyle(Style.STROKE);
mUserPaint.setStrokeWidth(6);
mUserPaint.setAntiAlias(true);
mSpeedPaint = new Paint();
mSpeedPaint.setColor(userColor);
mSpeedPaint.setStrokeWidth(6);
mSpeedPaint.setStyle(Style.STROKE);
mSpeedPaint.setAntiAlias(true);
mCompassNorthPaint = new Paint();
mCompassNorthPaint.setARGB(255, 255, 0, 0);
mCompassNorthPaint.setStrokeWidth(3);
mCompassNorthPaint.setAntiAlias(true);
mCompassSouthPaint = new Paint();
mCompassSouthPaint.setARGB(255, 230, 230, 230);
mCompassSouthPaint.setStrokeWidth(3);
mCompassSouthPaint.setAntiAlias(true);
mGlowPaint = new Paint();
mGlowPaint.setStyle(Style.STROKE);
}
public void setUserLocation(double latitude, double longitude, float accuracy) {
mLatitude.set(latitude);
mLongitude.set(longitude);
mGpsAccuracy.set(accuracy);
mCachesProvider.setCenter(latitude, longitude);
}
public void setSelectedGeocache(Geocache geocache) {
mSelectedGeocache = geocache;
}
public void draw(Canvas canvas) {
canvas.drawColor(Color.BLACK); //Clear screen
mCenterX = canvas.getWidth() / 2;
//The maximum pixel distance from user point that's visible on screen
int maxScreenRadius = (int)Math.ceil(Math.sqrt(mCenterX*mCenterX + mUserY*mUserY));
int accuracyScreenRadius = transformDistanceToScreen(mGpsAccuracy.get());
double direction = mDeviceDirection.get();
//Draw accuracy blur field
if (accuracyScreenRadius > 0) {
//TODO: Wasting objects!
/*
mGlowShader = new RadialGradient(mCenterX, mUserY,
accuracyScreenRadius, 0x80ffff00, 0x20ffff00, TileMode.CLAMP);
mAccuracyPaint.setShader(mGlowShader);
*/
canvas.drawCircle(mCenterX, mUserY, accuracyScreenRadius, mAccuracyPaint);
}
//North
int x1 = xRelativeUser(maxScreenRadius, Math.toRadians(270-direction));
int y1 = yRelativeUser(maxScreenRadius, Math.toRadians(270-direction));
canvas.drawLine(mCenterX, mUserY, x1, y1, mCompassNorthPaint);
//South
int x2 = xRelativeUser(maxScreenRadius, Math.toRadians(90-direction));
int y2 = yRelativeUser(maxScreenRadius, Math.toRadians(90-direction));
canvas.drawLine(mCenterX, mUserY, x2, y2, mCompassSouthPaint);
//West-east
int x3 = xRelativeUser(maxScreenRadius, Math.toRadians(180-direction));
int y3 = yRelativeUser(maxScreenRadius, Math.toRadians(180-direction));
int x4 = xRelativeUser(maxScreenRadius, Math.toRadians(-direction));
int y4 = yRelativeUser(maxScreenRadius, Math.toRadians(-direction));
canvas.drawLine(x3, y3, x4, y4, mDistancePaint);
//Draw user speed vector
if (mUserSpeed.get() > 0) {
int speedRadius = transformDistanceToScreen(mUserSpeed.get()*3.6);
int x7 = xRelativeUser(speedRadius, Math.toRadians(mUserDirection.get()-direction-90));
int y7 = yRelativeUser(speedRadius, Math.toRadians(mUserDirection.get()-direction-90));
canvas.drawLine(mCenterX, mUserY, x7, y7, mSpeedPaint);
}
int[] distanceMarks = { 10, 20, 50, 100, 500, 1000, 5000, 10000, 50000, 100000, 1000000 };
String[] distanceTexts = { "10m", "20m", "50m", "100m", "500m", "1km", "5km", "10km", "50km", "100km", "1000km" };
int lastLeft = mCenterX;
for (int ix = 0; ix < distanceMarks.length; ix++) {
int distance = distanceMarks[ix];
String text = distanceTexts[ix];
int radius = transformDistanceToScreen(distance);
if (radius > maxScreenRadius)
//Not visible anywhere on screen
break;
if (distance == 100 || distance == 1000)
canvas.drawCircle(mCenterX, mUserY, radius, mMainDistancePaint);
else
canvas.drawCircle(mCenterX, mUserY, radius, mDistancePaint);
if (radius > mCenterX) {
int height = (int)Math.sqrt(radius*radius - mCenterX*mCenterX);
canvas.drawText(text, 5, mUserY-height-5, mTextPaint);
} else {
mTextPaint.getTextBounds(text, 0, text.length(), mTempBounds);
int left = mCenterX-radius-10;
if (left + mTempBounds.right > lastLeft)
continue; //Don't draw text that would overlap
lastLeft = left;
canvas.drawText(text, left, mUserY, mTextPaint);
}
}
AbstractList<Geocache> caches = mCachesProvider.getCaches();
//Draw all geocaches and lines to them
if (mCachesProvider.hasChanged()) {
Log.d("GeoBeagle", "ProximityPainter drawing " + caches.size() + " caches");
mCachesProvider.resetChanged();
}
if (mSelectedGeocache != null && !caches.contains(mSelectedGeocache)) {
caches = new GeocacheListPrecomputed(caches, mSelectedGeocache);
}
double maxDistanceM = 0;
for (Geocache geocache : caches) {
double angle = Math.toRadians(GeoUtils.bearing(mLatitude.get(), mLongitude.get(),
geocache.getLatitude(), geocache.getLongitude()) - direction - 90);
double distanceM = GeoUtils.distanceKm(mLatitude.get(), mLongitude.get(),
geocache.getLatitude(), geocache.getLongitude()) * 1000;
if (distanceM > maxDistanceM)
maxDistanceM = distanceM;
double screenDist = transformDistanceToScreen(distanceM);
int cacheScreenRadius = (int)(2*scaleFactorAtDistance(distanceM*2));
mCachePaint.setStrokeWidth((int)Math.ceil(0.5*scaleFactorAtDistance(distanceM)));
mCachePaint.setAlpha(255);
int x = mCenterX + (int)(screenDist * Math.cos(angle));
int y = mUserY + (int)(screenDist * Math.sin(angle));
if (geocache == mSelectedGeocache) {
int glowTh = (int)(mCachePaint.getStrokeWidth() * 2); //(1.0 + Math.abs(Math.sin(mTime))));
drawGlow(canvas, x, y, (int)(cacheScreenRadius+mCachePaint.getStrokeWidth()/2), glowTh);
}
canvas.drawCircle(x, y, cacheScreenRadius, mCachePaint);
//Lines to geocaches
if (screenDist > mUserScreenRadius + cacheScreenRadius) {
//Cache is outside accuracy circle
int x5 = xRelativeUser(mUserScreenRadius, angle);
int y5 = yRelativeUser(mUserScreenRadius, angle);
int x6 = xRelativeUser(screenDist-cacheScreenRadius, angle);
int y6 = yRelativeUser(screenDist-cacheScreenRadius, angle);
mCachePaint.setStrokeWidth(Math.min(8, cacheScreenRadius));
double closeness = 1 - (0.7*screenDist)/maxScreenRadius;
mCachePaint.setAlpha((int)Math.min(255, 256 * 1.5 * closeness));
canvas.drawLine(x5, y5, x6, y6, mCachePaint);
}
}
mScaleFactor.set(mUserY * Math.log(mLogScale) / Math.log(maxDistanceM/2f));
canvas.drawCircle(mCenterX, mUserY, mUserScreenRadius, mUserPaint);
}
/**
* @param radius The smallest radius that will glow
* @param thickness Thickness of glow
*/
private void drawGlow(Canvas c, int x, int y, int radius, int thickness) {
int color = Color.argb(255, 200, 200, 248);
int[] colors = { color, color, 0x00000000};
float[] positions = { 0, ((float)radius)/(radius+thickness), 1f };
//float[] positions = { 0, (radius + 0.5f*thickness)/(radius+thickness), 1f };
//float[] positions = { 0.5f, 0.9f, 1f };
//TODO: Wastes objects
Shader glowShader;
glowShader = new RadialGradient(x, y, radius+thickness*1.5f, colors, positions, TileMode.MIRROR);
mGlowPaint.setShader(glowShader);
mGlowPaint.setStrokeWidth(radius);
c.drawCircle(x, y, radius+thickness/2, mGlowPaint);
}
/** angle is in radians */
private int xRelativeUser(double distance, double angle) {
return mCenterX + (int)(distance * Math.cos(angle));
}
/** angle is in radians */
private int yRelativeUser(double distance, double angle) {
return mUserY + (int)(distance * Math.sin(angle));
}
/** Return the distance in pixels for a real-world distance in meters
* Argument must be positive */
private int transformDistanceToScreen(double meters) {
int distance = (int)(mScaleFactor.get() * myLog(meters));
return Math.max(20, distance - 40);
}
/** At distance 'meters', draw a meter as these many pixels */
private double scaleFactorAtDistance(double meters) {
if (meters < 6)
meters = 1;
else
meters -= 5;
return (int)(2000.0/(mScaleFactor.get() * myLog(meters)));
}
/** Returns logarithm of x in base mLogScale */
private double myLog(double x) {
return Math.log(x) / Math.log(mLogScale);
}
/** bearing 0 is north, bearing 90 is east */
public void setUserDirection(double degrees) {
mDeviceDirection.set(degrees);
}
/** bearing 0 is north, bearing 90 is east */
public void setUserMovement(double bearing, double speed) {
mUserSpeed.set(speed);
mUserDirection.set(bearing);
}
/** Seconds */
private double mTime;
/** Update animations timeDelta seconds (preferably much less than a sec) */
public void advanceTime(double timeDelta) {
mTime += timeDelta;
for (Parameter param : allParameters) {
param.update(timeDelta);
}
}
}
| Java |
package com.google.code.geobeagle.activity.prox;
/** Represents an angle in degrees, knowing values 360 and 0 are the same */
class AngularParameter extends Parameter {
public AngularParameter(double accelConst, double attenuation, double init) {
super(accelConst, attenuation, init);
}
public AngularParameter(double accelConst, double attenuation) {
super(accelConst, attenuation);
}
public AngularParameter(double init) {
super(init);
}
public AngularParameter() {
super();
}
@Override
public void update(double deltaSec) {
double distance = mTargetValue - mValue;
if (distance > 180)
distance -= 360;
else if (distance < -180)
distance += 360;
double accel = distance * Math.abs(distance) * mAccelConst;
mValue += mChangePerSec * deltaSec + accel*deltaSec*deltaSec/2.0;
mChangePerSec += accel * deltaSec;
mChangePerSec *= Math.pow(mAttenuation, deltaSec);
}
} | Java |
package com.google.code.geobeagle.activity.filterlist;
import com.google.code.geobeagle.CacheFilter;
import com.google.code.geobeagle.Tags;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import java.util.ArrayList;
public class FilterTypeCollection {
private static final String FILTER_PREFS = "Filter";
private final Activity mActivity;
private ArrayList<CacheFilter> mFilterTypes = new ArrayList<CacheFilter>();
public FilterTypeCollection(Activity activity) {
mActivity = activity;
load();
}
/** Loads/reloads the list of filters from the Preferences */
private void load() {
mFilterTypes.clear();
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
String ids = prefs.getString("FilterList", "");
String[] idArray = ids.split(", ");
if (idArray.length == 1 && idArray[0].equals("")) {
//No filters were registered. Setup the default ones
firstSetup();
} else {
for (String id : idArray) {
mFilterTypes.add(new CacheFilter(id, mActivity));
}
}
}
private void firstSetup() {
Log.i("GeoBeagle", "FilterTypeCollection first setup");
{ FilterPreferences pref = new FilterPreferences("All caches");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("All", mActivity, pref));
}
{ FilterPreferences favoritesPref = new FilterPreferences("Favorites");
favoritesPref.setString("FilterTags",
Integer.toString(Tags.FAVORITES));
add(new CacheFilter("Favorites", mActivity, favoritesPref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 1");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter1", mActivity, pref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 2");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter2", mActivity, pref));
}
{ FilterPreferences pref = new FilterPreferences("Custom 3");
pref.setBoolean("Waypoints", false);
add(new CacheFilter("Filter3", mActivity, pref));
}
/*
{ FilterPreferences foundPref = new FilterPreferences("Found");
foundPref.setInteger("FilterTag", Tags.FOUND);
add(new CacheFilter("Found", mActivity, foundPref));
}
{ FilterPreferences dnfPref = new FilterPreferences("Did Not Find");
dnfPref.setInteger("FilterTag", Tags.DNF);
add(new CacheFilter("DNF", mActivity, dnfPref));
}
*/
String filterList = null;
for (CacheFilter cacheFilter : mFilterTypes) {
cacheFilter.saveToPreferences();
if (filterList == null)
filterList = cacheFilter.mId;
else
filterList = filterList + ", " + cacheFilter.mId;
}
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
Editor editor = prefs.edit();
editor.putString("FilterList", filterList);
editor.commit();
}
private void add(CacheFilter cacheFilter) {
mFilterTypes.add(cacheFilter);
}
private CacheFilter getFromId(String id) {
for (CacheFilter cacheFilter : mFilterTypes)
if (cacheFilter.mId.equals(id))
return cacheFilter;
return null;
}
public CacheFilter getActiveFilter() {
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
String id = prefs.getString("ActiveFilter", "All");
return getFromId(id);
}
public void setActiveFilter(CacheFilter cacheFilter) {
SharedPreferences prefs = mActivity.getSharedPreferences(FILTER_PREFS, 0);
Editor editor = prefs.edit();
editor.putString("ActiveFilter", cacheFilter.mId);
editor.commit();
}
public int getCount() {
return mFilterTypes.size();
}
public CacheFilter get(int position) {
return mFilterTypes.get(position);
}
public int getIndexOf(CacheFilter cacheFilter) {
return mFilterTypes.indexOf(cacheFilter);
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import com.google.code.geobeagle.CacheFilter;
import com.google.code.geobeagle.R;
//import com.google.code.geobeagle.R;
import android.app.ListActivity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class FilterListActivityDelegate {
private static class FilterListAdapter extends BaseAdapter {
private final FilterTypeCollection mFilterTypeCollection;
private LayoutInflater mInflater;
private Bitmap mIconSelected;
private Bitmap mIconUnselected;
/** -1 means no row is selected */
private int mSelectionIndex = -1;
public FilterListAdapter(Context context, FilterTypeCollection filterTypeCollection) {
mFilterTypeCollection = filterTypeCollection;
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
Resources resources = context.getResources();
mIconSelected = BitmapFactory.decodeResource(resources,
R.drawable.btn_radio_on);
//android.R.drawable.radiobutton_on_background);
mIconUnselected = BitmapFactory.decodeResource(resources,
R.drawable.btn_radio_off);
//android.R.drawable.radiobutton_off_background);
}
@Override
public int getCount() {
return mFilterTypeCollection.getCount();
}
@Override
public Object getItem(int position) {
return mFilterTypeCollection.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = mInflater.inflate(R.layout.filterlist_row, null);
ImageView image = (ImageView) view.findViewById(R.id.icon);
if (position == mSelectionIndex)
image.setImageBitmap(mIconSelected);
else
image.setImageBitmap(mIconUnselected);
TextView text = (TextView) view.findViewById(R.id.txt_filter);
text.setText(mFilterTypeCollection.get(position).getName());
return view;
}
public void setSelection(int index) {
mSelectionIndex = index;
notifyDataSetChanged();
}
}
private FilterTypeCollection mFilterTypeCollection;
private FilterListAdapter mAdapter;
public void onCreate(ListActivity activity) {
mFilterTypeCollection = new FilterTypeCollection(activity);
mAdapter = new FilterListAdapter(activity, mFilterTypeCollection);
int ix = mFilterTypeCollection.getIndexOf(mFilterTypeCollection.getActiveFilter());
mAdapter.setSelection(ix);
activity.setListAdapter(mAdapter);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
CacheFilter cacheFilter = mFilterTypeCollection.get(position);
mFilterTypeCollection.setActiveFilter(cacheFilter);
mAdapter.setSelection(position);
}
}
| Java |
package com.google.code.geobeagle.activity.filterlist;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
/** Used to simulate a SharedPreferences when initializing
* a FilterType for the first time. */
class FilterPreferences implements SharedPreferences {
private HashMap<String, Object> mValues;
public FilterPreferences(String filterName) {
mValues = new HashMap<String, Object>();
setString("FilterName", filterName);
};
public void setBoolean(String key, boolean value) {
mValues.put(key, new Boolean(value));
}
public void setString(String key, String value) {
mValues.put(key, value);
}
public void setInteger(String key, int value) {
mValues.put(key, new Integer(value));
}
@Override
public boolean contains(String key) {
return mValues.containsKey(key);
}
@Override
public Editor edit() {
return null;
}
@Override
public Map<String, ?> getAll() {
return mValues;
}
@Override
public boolean getBoolean(String key, boolean defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Boolean)value;
}
@Override
public float getFloat(String key, float defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Float)value;
}
@Override
public int getInt(String key, int defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Integer)value;
}
@Override
public long getLong(String key, long defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (Long)value;
}
@Override
public String getString(String key, String defValue) {
Object value = mValues.get(key);
if (value == null) return defValue;
return (String)value;
}
@Override
public void registerOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
}
@Override
public void unregisterOnSharedPreferenceChangeListener(
OnSharedPreferenceChangeListener listener) {
}
}
| Java |
package com.google.code.geobeagle;
import android.app.Activity;
import android.content.SharedPreferences;
import java.util.HashSet;
import java.util.Set;
//TODO: Allow filtering on Source
/**
* A CacheFilter determines which of all geocaches that should be
* visible in the list and map views.
* It can be translated into a SQL constraint for accessing the database.
*/
public class CacheFilter {
private final Activity mActivity;
/** The name of this filter as visible to the user */
private String mName;
/** The string used in Preferences to identify this filter */
public final String mId;
/** The name of this filter as visible to the user */
public String getName() {
return mName;
}
public static interface FilterGui {
public boolean getBoolean(int id);
public String getString(int id);
public void setBoolean(int id, boolean value);
public void setString(int id, String value);
}
private static class BooleanOption {
public final String PrefsName;
public final String SqlClause;
public boolean Selected;
public int ViewResource;
public BooleanOption(String prefsName, String sqlClause,
int viewResource) {
PrefsName = prefsName;
SqlClause = sqlClause;
Selected = true;
ViewResource = viewResource;
}
}
private final BooleanOption[] mTypeOptions = {
new BooleanOption("Traditional", "CacheType = 1", R.id.ToggleButtonTrad),
new BooleanOption("Multi", "CacheType = 2", R.id.ToggleButtonMulti),
new BooleanOption("Unknown", "CacheType = 3", R.id.ToggleButtonMystery),
new BooleanOption("MyLocation", "CacheType = 4", R.id.ToggleButtonMyLocation),
new BooleanOption("Others", "CacheType = 0 OR (CacheType >= 5 AND CacheType <= 14)", R.id.ToggleButtonOthers),
new BooleanOption("Waypoints", "(CacheType >= 20 AND CacheType <= 25)", R.id.ToggleButtonWaypoints),
};
//These SQL are to be applied when the option is deselected!
private final BooleanOption[] mSizeOptions = {
new BooleanOption("Micro", "Container != 1", R.id.ToggleButtonMicro),
new BooleanOption("Small", "Container != 2", R.id.ToggleButtonSmall),
new BooleanOption("UnknownSize", "Container != 0", R.id.ToggleButtonUnknownSize),
};
private String mFilterString;
private static final Set<Integer> EMPTY_SET = new HashSet<Integer>();
/** Limits the filter to only include geocaches with this tag.
* Zero means no limit. */
private Set<Integer> mRequiredTags = EMPTY_SET;
/** Caches with this tag are not included in the results no matter what.
* Zero means no restriction. */
private Set<Integer> mForbiddenTags = EMPTY_SET;
public CacheFilter(String id, Activity activity) {
mId = id;
mActivity = activity;
SharedPreferences preferences = mActivity.getSharedPreferences(mId, 0);
loadFromPreferences(preferences);
}
public CacheFilter(String id, Activity activity,
SharedPreferences sharedPreferences) {
mId = id;
mActivity = activity;
loadFromPreferences(sharedPreferences);
}
/**
* Load the values from SharedPreferences.
* @return true if any value in the filter was changed
*/
private void loadFromPreferences(SharedPreferences preferences) {
for (BooleanOption option : mTypeOptions) {
option.Selected = preferences.getBoolean(option.PrefsName, true);
}
for (BooleanOption option : mSizeOptions) {
option.Selected = preferences.getBoolean(option.PrefsName, true);
}
mFilterString = preferences.getString("FilterString", null);
String required = preferences.getString("FilterTags", "");
mRequiredTags = StringToIntegerSet(required);
String forbidden = preferences.getString("FilterForbiddenTags", "");
mForbiddenTags = StringToIntegerSet(forbidden);
mName = preferences.getString("FilterName", "Unnamed");
}
public void saveToPreferences() {
SharedPreferences preferences = mActivity.getSharedPreferences(mId, 0);
SharedPreferences.Editor editor = preferences.edit();
for (BooleanOption option : mTypeOptions) {
editor.putBoolean(option.PrefsName, option.Selected);
}
for (BooleanOption option : mSizeOptions) {
editor.putBoolean(option.PrefsName, option.Selected);
}
editor.putString("FilterString", mFilterString);
editor.putString("FilterTags", SetToString(mRequiredTags));
editor.putString("FilterForbiddenTags", SetToString(mForbiddenTags));
editor.putString("FilterName", mName);
editor.commit();
}
private static String SetToString(Set<Integer> set) {
StringBuffer buffer = new StringBuffer();
boolean first = true;
for (int i : set) {
if (first)
first = false;
else
buffer.append(' ');
buffer.append(i);
}
return buffer.toString();
}
private static Set<Integer> StringToIntegerSet(String string) {
if (string.equals(""))
return EMPTY_SET;
Set<Integer> set = new HashSet<Integer>();
String[] parts = string.split(" ");
for (String part : parts) {
set.add(Integer.decode(part));
}
return set;
}
/** @return A number of conditions separated by AND,
* or an empty string if there isn't any limit */
public String getSqlWhereClause() {
int count = 0;
for (BooleanOption option : mTypeOptions) {
if (option.Selected)
count++;
}
StringBuilder result = new StringBuilder();
boolean isFirst = true;
if (count != mTypeOptions.length && count != 0) {
for (BooleanOption option : mTypeOptions) {
if (!option.Selected)
continue;
if (isFirst) {
result.append("(");
isFirst = false;
} else {
result.append(" OR ");
}
result.append(option.SqlClause);
}
result.append(")");
}
if (mFilterString != null && !mFilterString.equals("")) {
if (isFirst) {
isFirst = false;
} else {
result.append(" AND ");
}
if (containsUppercase(mFilterString)) {
//Do case-sensitive query
result.append("(Id LIKE '%" + mFilterString
+ "%' OR Description LIKE '%" + mFilterString + "%')");
} else {
//Do case-insensitive search
result.append("(lower(Id) LIKE '%" + mFilterString
+ "%' OR lower(Description) LIKE '%" + mFilterString + "%')");
}
}
for (BooleanOption option : mSizeOptions) {
if (!option.Selected) {
if (isFirst) {
isFirst = false;
} else {
result.append(" AND ");
}
result.append(option.SqlClause);
}
}
return result.toString();
}
public Set<Integer> getRequiredTags() {
return mRequiredTags;
}
private static boolean containsUppercase(String string) {
return !string.equals(string.toLowerCase());
}
public void loadFromGui(FilterGui provider) {
String newName = provider.getString(R.id.NameOfFilter);
if (!newName.trim().equals("")) {
mName = newName;
}
for (BooleanOption option : mTypeOptions) {
option.Selected = provider.getBoolean(option.ViewResource);
}
for (BooleanOption option : mSizeOptions) {
option.Selected = provider.getBoolean(option.ViewResource);
}
mFilterString = provider.getString(R.id.FilterString);
mRequiredTags = new HashSet<Integer>();
mForbiddenTags = new HashSet<Integer>();
if (provider.getBoolean(R.id.CheckBoxRequireFavorites))
mRequiredTags.add(Tags.FAVORITES);
else if (provider.getBoolean(R.id.CheckBoxForbidFavorites))
mForbiddenTags.add(Tags.FAVORITES);
if (provider.getBoolean(R.id.CheckBoxRequireFound))
mRequiredTags.add(Tags.FOUND);
else if (provider.getBoolean(R.id.CheckBoxForbidFound))
mForbiddenTags.add(Tags.FOUND);
if (provider.getBoolean(R.id.CheckBoxRequireDNF))
mRequiredTags.add(Tags.DNF);
else if (provider.getBoolean(R.id.CheckBoxForbidDNF))
mForbiddenTags.add(Tags.DNF);
}
/** Set up the view from the values in this CacheFilter. */
public void pushToGui(FilterGui provider) {
provider.setString(R.id.NameOfFilter, mName);
for (BooleanOption option : mTypeOptions) {
provider.setBoolean(option.ViewResource, option.Selected);
}
for (BooleanOption option : mSizeOptions) {
provider.setBoolean(option.ViewResource, option.Selected);
}
String filter = mFilterString == null ? "" : mFilterString;
provider.setString(R.id.FilterString, filter);
provider.setBoolean(R.id.CheckBoxRequireFavorites,
mRequiredTags.contains(Tags.FAVORITES));
provider.setBoolean(R.id.CheckBoxForbidFavorites,
mForbiddenTags.contains(Tags.FAVORITES));
provider.setBoolean(R.id.CheckBoxRequireFound,
mRequiredTags.contains(Tags.FOUND));
provider.setBoolean(R.id.CheckBoxForbidFound,
mForbiddenTags.contains(Tags.FOUND));
provider.setBoolean(R.id.CheckBoxRequireDNF,
mRequiredTags.contains(Tags.DNF));
provider.setBoolean(R.id.CheckBoxForbidDNF,
mForbiddenTags.contains(Tags.DNF));
}
public Set<Integer> getForbiddenTags() {
return mForbiddenTags;
}
}
| 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.ui;
import android.text.Editable;
import android.text.InputFilter;
class StubEditable implements Editable {
private String mString;
public StubEditable(String s) {
mString = s;
}
public Editable append(char arg0) {
return null;
}
public Editable append(CharSequence arg0) {
return null;
}
public Editable append(CharSequence arg0, int arg1, int arg2) {
return null;
}
public char charAt(int index) {
return mString.charAt(index);
}
public void clear() {
}
public void clearSpans() {
}
public Editable delete(int arg0, int arg1) {
return null;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
mString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
public InputFilter[] getFilters() {
return null;
}
public int getSpanEnd(Object arg0) {
return 0;
}
public int getSpanFlags(Object arg0) {
return 0;
}
public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) {
return null;
}
public int getSpanStart(Object arg0) {
return 0;
}
public Editable insert(int arg0, CharSequence arg1) {
return null;
}
public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) {
return null;
}
public int length() {
return mString.length();
}
@SuppressWarnings("unchecked")
public int nextSpanTransition(int arg0, int arg1, Class arg2) {
return 0;
}
public void removeSpan(Object arg0) {
}
public Editable replace(int arg0, int arg1, CharSequence arg2) {
return null;
}
public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) {
return null;
}
public void setFilters(InputFilter[] arg0) {
}
public void setSpan(Object arg0, int arg1, int arg2, int arg3) {
}
public CharSequence subSequence(int start, int end) {
return mString.subSequence(start, end);
}
public String toString() {
return mString;
}
}
| 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.data;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFromParcelFactory;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.data.Geocache.Source.SourceFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
private static SourceFactory mSourceFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
}
public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> {
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory(
new GeocacheFactory());
public Geocache createFromParcel(Parcel in) {
return mGeocacheFromParcelFactory.create(in);
}
public Geocache[] newArray(int size) {
return new Geocache[size];
}
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
return new Geocache(id, name, latitude, longitude, sourceType, sourceName);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| 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.data;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.DistanceFormatter;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.data.GeocacheVector;
import com.google.code.geobeagle.data.IGeocacheVector;
import com.google.code.geobeagle.io.LocationSaver;
import android.location.Location;
public class GeocacheVectorFactory {
private final DistanceFormatter mDistanceFormatter;
private final ResourceProvider mResourceProvider;
private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory;
private final LocationSaver mLocationSaver;
public GeocacheVectorFactory(GeocacheFromMyLocationFactory geocacheFromMyLocationFactory,
LocationSaver locationSaver, DistanceFormatter distanceFormatter,
ResourceProvider resourceProvider) {
mDistanceFormatter = distanceFormatter;
mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory;
mResourceProvider = resourceProvider;
mLocationSaver = locationSaver;
}
private float calculateDistance(Location here, Geocache geocache) {
if (here != null) {
float[] results = new float[1];
Location.distanceBetween(here.getLatitude(), here.getLongitude(), geocache
.getLatitude(), geocache.getLongitude(), results);
return results[0];
}
return -1;
}
public GeocacheVector create(Geocache location, Location here) {
return new GeocacheVector(location, calculateDistance(here, location), mDistanceFormatter);
}
public IGeocacheVector createMyLocation() {
return new GeocacheVector.MyLocation(mResourceProvider, mGeocacheFromMyLocationFactory,
mLocationSaver);
}
}
| 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.gpx.zip;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipInputStream;
public class ZipInputStreamFactory {
public GpxZipInputStream create(String filename) throws IOException {
return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream(
new FileInputStream(filename))));
}
}
| 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.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.CacheListData;
import com.google.code.geobeagle.data.DistanceFormatter;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.data.GeocacheVectorFactory;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.data.GeocacheVector.LocationComparator;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.GpxImporter;
import com.google.code.geobeagle.io.GpxImporterDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheListAdapter;
import com.google.code.geobeagle.ui.GeocacheRowInflater;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.view.LayoutInflater;
public class CacheListDelegateDI {
public static CacheListDelegate create(ListActivity parent, LayoutInflater layoutInflater) {
final ErrorDisplayer errorDisplayer = new ErrorDisplayer(parent);
final Database database = DatabaseDI.create(parent);
final ResourceProvider resourceProvider = new ResourceProvider(parent);
final LocationManager locationManager = (LocationManager)parent
.getSystemService(Context.LOCATION_SERVICE);
final LocationControl locationControl = LocationControlDi.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromMyLocationFactory geocacheFromMyLocationFactory = new GeocacheFromMyLocationFactory(
geocacheFactory, locationControl, errorDisplayer);
final GeocachesSql locationBookmarks = DatabaseDI.create(locationControl, database);
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final DistanceFormatter distanceFormatter = new DistanceFormatter();
final LocationSaver locationSaver = new LocationSaver(database, sqliteWrapper, cacheWriter);
final GeocacheVectorFactory geocacheVectorFactory = new GeocacheVectorFactory(
geocacheFromMyLocationFactory, locationSaver, distanceFormatter, resourceProvider);
final LocationComparator locationComparator = new LocationComparator();
final GeocacheVectors geocacheVectors = new GeocacheVectors(locationComparator,
geocacheVectorFactory);
final CacheListData cacheListData = new CacheListData(geocacheVectors,
geocacheVectorFactory);
final Action actions[] = CacheListDelegateDI.create(parent, database, sqliteWrapper,
cacheListData, cacheWriter, geocacheVectors, errorDisplayer);
final CacheListDelegate.CacheListOnCreateContextMenuListener.Factory factory = new CacheListDelegate.CacheListOnCreateContextMenuListener.Factory();
final GpxImporter gpxImporter = GpxImporterDI.create(database, sqliteWrapper,
errorDisplayer, parent);
final GeocacheRowInflater geocacheRowInflater = new GeocacheRowInflater(layoutInflater);
final GeocacheListAdapter geocacheListAdapter = new GeocacheListAdapter(geocacheVectors,
geocacheRowInflater);
return new CacheListDelegate(parent, locationBookmarks, locationControl, cacheListData,
geocacheVectors, geocacheListAdapter, errorDisplayer, actions, factory, gpxImporter);
}
public static Action[] create(ListActivity parent, Database database,
SQLiteWrapper sqliteWrapper, CacheListData cacheListData, CacheWriter cacheWriter,
GeocacheVectors geocacheVectors, ErrorDisplayer errorDisplayer) {
final Intent intent = new Intent(parent, GeoBeagle.class);
final ViewAction viewAction = new ViewAction(geocacheVectors, parent, intent);
final DeleteAction deleteAction = new DeleteAction(database, sqliteWrapper, cacheWriter,
geocacheVectors, errorDisplayer);
return new Action[] {
deleteAction, viewAction
};
}
}
| 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.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.ui.WebPageAndDetailsButtonEnabler;
import android.view.View;
public class Misc {
public static class Time {
public long getCurrentTime() {
return System.currentTimeMillis();
}
}
public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View cachePageButton,
View detailsButton) {
return new WebPageAndDetailsButtonEnabler(geoBeagle, cachePageButton, detailsButton);
}
}
| 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.ui;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.EditCacheActivityDelegate;
import com.google.code.geobeagle.ui.EditCacheActivityDelegate.CancelButtonOnClickListener;
import android.app.Activity;
import android.os.Bundle;
public class EditCacheActivity extends Activity {
private final EditCacheActivityDelegate mEditCacheActivityDelegate;
public EditCacheActivity() {
super();
final Database database = DatabaseDI.create(this);
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final LocationSaver locationSaver = new LocationSaver(database, sqliteWrapper, cacheWriter);
final CancelButtonOnClickListener cancelButtonOnClickListener = new CancelButtonOnClickListener(
this);
mEditCacheActivityDelegate = new EditCacheActivityDelegate(this,
cancelButtonOnClickListener, locationSaver);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEditCacheActivityDelegate.onCreate(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
mEditCacheActivityDelegate.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;
import com.google.code.geobeagle.LocationControl.LocationChooser;
import android.location.LocationManager;
public class LocationControlDi {
public static LocationControl create(LocationManager locationManager) {
final LocationChooser locationChooser = new LocationChooser();
return new LocationControl(locationManager, locationChooser);
}
}
| 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.io;
import com.google.code.geobeagle.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilesIterFactory;
import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.ImportThreadDelegate.ImportThreadHelper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import java.io.FilenameFilter;
public class GpxImporterDI {
// Can't test this due to final methods in base.
public static class ImportThread extends Thread {
static ImportThread create(MessageHandler messageHandler, GpxLoader gpxLoader,
ErrorDisplayer errorDisplayer) {
final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter();
final GpxAndZipFilesIterFactory gpxAndZipFilesIterFactory = new GpxAndZipFilesIterFactory();
final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter,
gpxAndZipFilesIterFactory);
final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader,
messageHandler, errorDisplayer);
return new ImportThread(gpxAndZipFiles, importThreadHelper, errorDisplayer);
}
private final ImportThreadDelegate mImportThreadDelegate;
public ImportThread(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper,
ErrorDisplayer errorDisplayer) {
mImportThreadDelegate = new ImportThreadDelegate(gpxAndZipFiles, importThreadHelper,
errorDisplayer);
}
@Override
public void run() {
mImportThreadDelegate.run();
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ImportThreadWrapper {
private ImportThread mImportThread;
private final MessageHandler mMessageHandler;
public ImportThreadWrapper(MessageHandler messageHandler) {
mMessageHandler = messageHandler;
}
public boolean isAlive() {
if (mImportThread != null)
return mImportThread.isAlive();
return false;
}
public void join() throws InterruptedException {
if (mImportThread != null)
mImportThread.join();
}
public void open(CacheListDelegate cacheListDelegate, GpxLoader gpxLoader,
ErrorDisplayer mErrorDisplayer) {
mMessageHandler.start(cacheListDelegate);
mImportThread = ImportThread.create(mMessageHandler, gpxLoader, mErrorDisplayer);
}
public void start() {
if (mImportThread != null)
mImportThread.start();
}
}
// Too hard to test this class due to final methods in base.
public static class MessageHandler extends Handler {
static final int MSG_DONE = 1;
static final int MSG_PROGRESS = 0;
public static MessageHandler create(ListActivity listActivity) {
final ProgressDialogWrapper progressDialogWrapper = new ProgressDialogWrapper(
listActivity);
return new MessageHandler(progressDialogWrapper);
}
private int mCacheCount;
private CacheListDelegate mCacheListDelegate;
private boolean mLoadAborted;
private final ProgressDialogWrapper mProgressDialogWrapper;
private String mSource;
private String mStatus;
private String mWaypointId;
public MessageHandler(ProgressDialogWrapper progressDialogWrapper) {
mProgressDialogWrapper = progressDialogWrapper;
}
public void abortLoad() {
mLoadAborted = true;
mProgressDialogWrapper.dismiss();
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MessageHandler.MSG_PROGRESS:
mProgressDialogWrapper.setMessage(mStatus);
break;
case MessageHandler.MSG_DONE:
if (!mLoadAborted) {
mProgressDialogWrapper.dismiss();
mCacheListDelegate.onResume();
}
break;
default:
break;
}
}
public void loadComplete() {
sendEmptyMessage(MessageHandler.MSG_DONE);
}
public void start(CacheListDelegate cacheListDelegate) {
mCacheCount = 0;
mLoadAborted = false;
mCacheListDelegate = cacheListDelegate;
mProgressDialogWrapper.show("Importing caches", "Please wait...");
}
public void updateName(String name) {
mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name;
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateSource(String text) {
mSource = text;
}
public void updateWaypointId(String wpt) {
mWaypointId = wpt;
}
}
// Wrapper so that containers can follow the "constructors do no work" rule.
public static class ProgressDialogWrapper {
private final Context mContext;
private ProgressDialog mProgressDialog;
public ProgressDialogWrapper(Context context) {
mContext = context;
}
public void dismiss() {
if (mProgressDialog != null)
mProgressDialog.dismiss();
}
public void setMessage(CharSequence message) {
mProgressDialog.setMessage(message);
}
public void show(String title, String msg) {
mProgressDialog = ProgressDialog.show(mContext, title, msg);
}
}
public static class ToastFactory {
public void showToast(Context context, int resId, int duration) {
Toast.makeText(context, resId, duration).show();
}
}
public static GpxImporter create(Database database, SQLiteWrapper sqliteWrapper,
ErrorDisplayer errorDisplayer, ListActivity listActivity) {
final MessageHandler messageHandler = MessageHandler.create(listActivity);
final GpxLoader gpxLoader = GpxLoaderDI.create(listActivity, database, sqliteWrapper,
messageHandler, errorDisplayer);
final ToastFactory toastFactory = new ToastFactory();
final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler);
return new GpxImporter(gpxLoader, database, sqliteWrapper, listActivity,
importThreadWrapper, messageHandler, errorDisplayer, toastFactory);
}
}
| Java |
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import android.app.Activity;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock; /*
** 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.
*//*
** 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.
*/
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class CachePersisterFacadeDI {
public static class FileFactory {
public File createFile(String path) {
return new File(path);
}
}
public static class WriterWrapper {
Writer mWriter;
public void close() throws IOException {
mWriter.close();
}
public void open(String path) throws IOException {
mWriter = new BufferedWriter(new FileWriter(path), 4000);
}
public void write(String str) throws IOException {
mWriter.write(str);
}
}
public static CachePersisterFacade create(Activity activity, MessageHandler messageHandler,
Database database, SQLiteWrapper sqliteWrapper) {
final CacheWriter cacheWriter = DatabaseDI.createCacheWriter(sqliteWrapper);
final CacheTagWriter cacheTagWriter = new CacheTagWriter(cacheWriter);
final FileFactory fileFactory = new FileFactory();
final WriterWrapper writerWrapper = new WriterWrapper();
final HtmlWriter htmlWriter = new HtmlWriter(writerWrapper);
final CacheDetailsWriter cacheDetailsWriter = new CacheDetailsWriter(htmlWriter);
final PowerManager powerManager = (PowerManager)activity
.getSystemService(Context.POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"Importing");
return new CachePersisterFacade(cacheTagWriter, fileFactory, cacheDetailsWriter,
messageHandler, wakeLock);
}
}
| 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.io;
public class EventHelperDI {
public static EventHelper create(GpxToCacheDI.XmlPullParserWrapper xmlPullParser,
CachePersisterFacade cachePersisterFacade) {
final GpxEventHandler gpxEventHandler = new GpxEventHandler(cachePersisterFacade);
final EventHelper.XmlPathBuilder xmlPathBuilder = new EventHelper.XmlPathBuilder();
return new EventHelper(xmlPathBuilder, gpxEventHandler, xmlPullParser);
}
}
| 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.io;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.Activity;
public class GpxLoaderDI {
public static GpxLoader create(Activity activity, Database database,
SQLiteWrapper sqliteWrapper, MessageHandler messageHandler,
ErrorDisplayer errorDisplayer) {
final CachePersisterFacade cachePersisterFacade = CachePersisterFacadeDI.create(activity,
messageHandler, database, sqliteWrapper);
final GpxToCache gpxToCache = GpxToCacheDI.create(activity, cachePersisterFacade);
return new GpxLoader(gpxToCache, cachePersisterFacade, errorDisplayer);
}
}
| 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.io;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.Activity;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class GpxToCacheDI {
public static class XmlPullParserWrapper {
private String mSource;
private XmlPullParser mXmlPullParser;
public String getAttributeValue(String namespace, String name) {
return mXmlPullParser.getAttributeValue(namespace, name);
}
public int getEventType() throws XmlPullParserException {
return mXmlPullParser.getEventType();
}
public String getName() {
return mXmlPullParser.getName();
}
public String getSource() {
return mSource;
}
public String getText() {
return mXmlPullParser.getText();
}
public int next() throws XmlPullParserException, IOException {
return mXmlPullParser.next();
}
public void open(String path, Reader reader) throws XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
newPullParser.setInput(reader);
mSource = path;
mXmlPullParser = newPullParser;
}
}
public static GpxToCache create(Activity activity, CachePersisterFacade cachePersisterFacade) {
final GpxToCacheDI.XmlPullParserWrapper xmlPullParserWrapper = new GpxToCacheDI.XmlPullParserWrapper();
final EventHelper eventHelper = EventHelperDI.create(xmlPullParserWrapper,
cachePersisterFacade);
return new GpxToCache(xmlPullParserWrapper, eventHelper);
}
public static XmlPullParser createPullParser(String path) throws FileNotFoundException,
XmlPullParserException {
final XmlPullParser newPullParser = XmlPullParserFactory.newInstance().newPullParser();
final Reader reader = new BufferedReader(new FileReader(path));
newPullParser.setInput(reader);
return newPullParser;
}
}
| 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.io;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.Geocaches;
import com.google.code.geobeagle.io.CacheReader;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DbToGeocacheAdapter;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.CacheReader.CacheReaderCursor;
import com.google.code.geobeagle.io.CacheReader.WhereFactory;
import com.google.code.geobeagle.io.Database.ISQLiteDatabase;
import com.google.code.geobeagle.io.Database.OpenHelperDelegate;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseDI {
public static class CacheReaderCursorFactory {
public CacheReaderCursor create(Cursor cursor) {
GeocacheFactory geocacheFactory = new GeocacheFactory();
DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheReaderCursor(cursor, geocacheFactory, dbToGeocacheAdapter);
}
}
public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final Database.OpenHelperDelegate mOpenHelperDelegate;
public GeoBeagleSqliteOpenHelper(Context context,
Database.OpenHelperDelegate openHelperDelegate) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = openHelperDelegate;
}
@Override
public void onCreate(SQLiteDatabase db) {
mOpenHelperDelegate.onCreate(new SQLiteWrapper(db));
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
mOpenHelperDelegate.onUpgrade(new SQLiteWrapper(db), oldVersion, newVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private SQLiteDatabase mSQLiteDatabase;
public SQLiteWrapper(SQLiteDatabase db) {
mSQLiteDatabase = db;
}
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
public void close() {
mSQLiteDatabase.close();
}
public int countResults(String table, String selection, String... selectionArgs) {
Cursor cursor = mSQLiteDatabase.query(table, null, selection, selectionArgs, null,
null, null, null);
int count = cursor.getCount();
cursor.close();
return count;
}
public void endTransaction() {
mSQLiteDatabase.endTransaction();
}
public void execSQL(String sql) {
mSQLiteDatabase.execSQL(sql);
}
public void execSQL(String sql, Object... bindArgs) {
mSQLiteDatabase.execSQL(sql, bindArgs);
}
public void openReadableDatabase(Database database) {
mSQLiteDatabase = database.getReadableDatabase();
}
public void openWritableDatabase(Database database) {
mSQLiteDatabase = database.getWritableDatabase();
}
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
return mSQLiteDatabase.query(table, columns, selection, selectionArgs, groupBy,
orderBy, having, limit);
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
}
public static Database create(Context context) {
final OpenHelperDelegate openHelperDelegate = new Database.OpenHelperDelegate();
final GeoBeagleSqliteOpenHelper sqliteOpenHelper = new GeoBeagleSqliteOpenHelper(context,
openHelperDelegate);
return new Database(sqliteOpenHelper);
}
public static GeocachesSql create(LocationControl locationControl, Database database) {
final Geocaches geocaches = new Geocaches();
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final CacheReader cacheReader = createCacheReader(sqliteWrapper);
return new GeocachesSql(cacheReader, geocaches, database, sqliteWrapper, locationControl);
}
public static CacheReader createCacheReader(SQLiteWrapper sqliteWrapper) {
final WhereFactory whereFactory = new CacheReader.WhereFactory();
final CacheReaderCursorFactory cacheReaderCursorFactory = new CacheReaderCursorFactory();
return new CacheReader(sqliteWrapper, whereFactory, cacheReaderCursorFactory);
}
public static CacheWriter createCacheWriter(SQLiteWrapper sqliteWrapper) {
DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheWriter(sqliteWrapper, dbToGeocacheAdapter);
}
}
| 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.ui.ContentSelector;
import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.Spinner;
public class GeoBeagleBuilder {
private final Activity mActivity;
public GeoBeagleBuilder(Activity context) {
mActivity = context;
}
public ContentSelector createContentSelector(SharedPreferences preferences) {
return new ContentSelector((Spinner)mActivity.findViewById(R.id.content_provider),
preferences);
}
}
| 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.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.CacheListDelegateDI;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheList extends ListActivity {
private CacheListDelegate delegate;
@Override
public boolean onContextItemSelected(MenuItem item) {
return delegate.onContextItemSelected(item) || super.onContextItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
delegate = CacheListDelegateDI.create(this, this.getLayoutInflater());
delegate.onCreate();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return delegate.onCreateOptionsMenu(menu);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
delegate.onListItemClick(l, v, position, id);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return delegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
super.onPause();
delegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
delegate.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.data;
public interface IGeocacheVector {
public Geocache getGeocache();
public CharSequence getFormattedDistance();
public float getDistance();
public CharSequence getId();
public CharSequence getIdAndName();
}
| 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.data;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Geocache or letterbox description, id, and coordinates.
*/
public class Geocache implements Parcelable {
public static enum Provider {
ATLAS_QUEST(0), GROUNDSPEAK(1), MY_LOCATION(-1);
private final int mIx;
Provider(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
public static enum Source {
GPX(0), MY_LOCATION(1), WEB_URL(2);
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.mIx] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
public static Parcelable.Creator<Geocache> CREATOR = new GeocacheFactory.CreateGeocacheFromParcel();
public static final String ID = "id";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String NAME = "name";
public static final String SOURCE_NAME = "sourceName";
public static final String SOURCE_TYPE = "sourceType";
private final CharSequence mId;
private final double mLatitude;
private final double mLongitude;
private final CharSequence mName;
private final String mSourceName;
private final Source mSourceType;
public Geocache(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
mSourceType = sourceType;
mSourceName = sourceName;
}
public int describeContents() {
return 0;
}
public Provider getContentProvider() {
String prefix = mId.subSequence(0, 2).toString();
if (prefix.equals("GC"))
return Provider.GROUNDSPEAK;
if (prefix.equals("LB"))
return Provider.ATLAS_QUEST;
else
return Provider.MY_LOCATION;
}
public CharSequence getId() {
return mId;
}
public CharSequence getIdAndName() {
if (mId.length() == 0)
return mName;
else if (mName.length() == 0)
return mId;
else
return mId + ": " + mName;
}
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
public CharSequence getName() {
return mName;
}
public CharSequence getShortId() {
if (mId.length() > 2)
return mId.subSequence(2, mId.length());
else
return "";
}
public String getSourceName() {
return mSourceName;
}
public Source getSourceType() {
return mSourceType;
}
public void writeToParcel(Parcel out, int flags) {
Bundle bundle = new Bundle();
bundle.putCharSequence(ID, mId);
bundle.putCharSequence(NAME, mName);
bundle.putDouble(LATITUDE, mLatitude);
bundle.putDouble(LONGITUDE, mLongitude);
bundle.putInt(SOURCE_TYPE, mSourceType.mIx);
bundle.putString(SOURCE_NAME, mSourceName);
out.writeBundle(bundle);
}
public void writeToPrefs(Editor editor) {
editor.putString(ID, mId.toString());
editor.putString(NAME, mName.toString());
editor.putFloat(LATITUDE, (float)mLatitude);
editor.putFloat(LONGITUDE, (float)mLongitude);
editor.putInt(SOURCE_TYPE, mSourceType.mIx);
editor.putString(SOURCE_NAME, mSourceName);
}
}
| Java |
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.location.Location;
public class GeocacheFromMyLocationFactory {
private final LocationControl mLocationControl;
private final ErrorDisplayer mErrorDisplayer;
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory,
LocationControl locationControl, ErrorDisplayer errorDisplayer) {
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
mErrorDisplayer = errorDisplayer;
}
public Geocache create() {
Location location = mLocationControl.getLocation();
if (location == null) {
mErrorDisplayer.displayError(R.string.current_location_null);
return null;
}
long time = location.getTime();
return mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format(
"[%1$tk:%1$tM] My Location", time), location.getLatitude(),
location.getLongitude(), Source.MY_LOCATION, null);
}
}
| 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.
*/
/*
** 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.data;
import com.google.code.geobeagle.data.GeocacheVector.LocationComparator;
import android.location.Location;
import java.util.ArrayList;
public class GeocacheVectors {
private final GeocacheVectorFactory mGeocacheVectorFactory;
private final ArrayList<IGeocacheVector> mGeocacheVectorsList;
private final LocationComparator mLocationComparator;
public GeocacheVectors(LocationComparator locationComparator,
GeocacheVectorFactory geocacheVectorFactory) {
mGeocacheVectorsList = new ArrayList<IGeocacheVector>(0);
mLocationComparator = locationComparator;
mGeocacheVectorFactory = geocacheVectorFactory;
}
public void add(IGeocacheVector destinationVector) {
mGeocacheVectorsList.add(0, destinationVector);
}
public void addLocations(ArrayList<Geocache> geocaches, Location here) {
for (Geocache geocache : geocaches) {
add(mGeocacheVectorFactory.create(geocache, here));
}
}
public IGeocacheVector get(int position) {
return mGeocacheVectorsList.get(position);
}
public void remove(int position) {
mGeocacheVectorsList.remove(position);
}
public void reset(int size) {
mGeocacheVectorsList.clear();
mGeocacheVectorsList.ensureCapacity(size);
}
public int size() {
return mGeocacheVectorsList.size();
}
public void sort() {
mLocationComparator.sort(mGeocacheVectorsList);
}
}
| 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.data;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.io.LocationSaver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class GeocacheVector implements IGeocacheVector {
public static class LocationComparator implements Comparator<IGeocacheVector> {
public int compare(IGeocacheVector destination1, IGeocacheVector destination2) {
final float d1 = destination1.getDistance();
final float d2 = destination2.getDistance();
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
public void sort(ArrayList<IGeocacheVector> arrayList) {
Collections.sort(arrayList, this);
}
}
public static class MyLocation implements IGeocacheVector {
private final ResourceProvider mResourceProvider;
private GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory;
private final LocationSaver mLocationSaver;
public MyLocation(ResourceProvider resourceProvider,
GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) {
mResourceProvider = resourceProvider;
mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory;
mLocationSaver = locationSaver;
}
public CharSequence getCoordinatesIdAndName() {
return null;
}
public Geocache getDestination() {
return null;
}
public float getDistance() {
return -1;
}
public CharSequence getId() {
return mResourceProvider.getString(R.string.my_current_location);
}
public CharSequence getFormattedDistance() {
return "";
}
public CharSequence getIdAndName() {
return mResourceProvider.getString(R.string.my_current_location);
}
public Geocache getGeocache() {
Geocache geocache = mGeocacheFromMyLocationFactory.create();
mLocationSaver.saveLocation(geocache);
return geocache;
}
}
private final Geocache mGeocache;
private final float mDistance;
private final DistanceFormatter mDistanceFormatter;
GeocacheVector(Geocache geocache, float distance, DistanceFormatter distanceFormatter) {
mGeocache = geocache;
mDistance = distance;
mDistanceFormatter = distanceFormatter;
}
public float getDistance() {
return mDistance;
}
public CharSequence getId() {
return mGeocache.getId();
}
public CharSequence getFormattedDistance() {
return mDistanceFormatter.format(mDistance);
}
public CharSequence getIdAndName() {
return mGeocache.getIdAndName();
}
public Geocache getGeocache() {
return mGeocache;
}
}
| Java |
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.data.Geocache.Source;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
Source source = Source.MY_LOCATION;
int iSource = preferences.getInt("sourceType", -1);
if (iSource != -1)
source = mGeocacheFactory.sourceFromInt(iSource);
return mGeocacheFactory.create(preferences.getString("id", "GCMEY7"), preferences
.getString("name", "Google Falls"), preferences.getFloat("latitude", 37.42235f),
preferences.getFloat("longitude", -122.082217f), source, preferences.getString(
"sourceName", null));
}
}
| Java |
package com.google.code.geobeagle.data;
import android.os.Bundle;
import android.os.Parcel;
public class GeocacheFromParcelFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromParcelFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(Parcel in) {
Bundle bundle = in.readBundle();
return mGeocacheFactory.create(bundle.getCharSequence("id"),
bundle.getCharSequence("name"), bundle.getDouble("latitude"), bundle
.getDouble("longitude"), mGeocacheFactory.sourceFromInt(bundle
.getInt("sourceType")), bundle.getString("sourceName"));
}
}
| Java |
package com.google.code.geobeagle.data;
public class DistanceFormatter {
public CharSequence format(float distance) {
if (distance == -1) {
return "";
}
if (distance >= 1000) {
return (int)(distance / 1000) + "km";
}
return (int)distance + "m";
}
}
| 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.data;
import java.util.ArrayList;
public class Geocaches {
private ArrayList<Geocache> mGeocaches;
public Geocaches() {
mGeocaches = new ArrayList<Geocache>();
}
public void add(Geocache geocache) {
mGeocaches.add(geocache);
}
public void clear() {
mGeocaches.clear();
}
public ArrayList<Geocache> getAll() {
return mGeocaches;
}
}
| 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.data;
import android.location.Location;
import java.util.ArrayList;
public class CacheListData {
private final GeocacheVectorFactory mGeocacheVectorFactory;
private final GeocacheVectors mGeocacheVectors;
public CacheListData(GeocacheVectors geocacheVectors, GeocacheVectorFactory geocacheVectorFactory) {
mGeocacheVectors = geocacheVectors;
mGeocacheVectorFactory = geocacheVectorFactory;
}
public void add(ArrayList<Geocache> geocaches, Location here) {
mGeocacheVectors.reset(geocaches.size());
mGeocacheVectors.addLocations(geocaches, here);
mGeocacheVectors.add(mGeocacheVectorFactory.createMyLocation());
mGeocacheVectors.sort();
}
}
| 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.net.UrlQuerySanitizer;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
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_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((fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees,
60.0 * (fAbsDegrees - dAbsDegrees));
}
public static String getStackTrace(Exception e) {
final StackTraceElement stack[] = e.getStackTrace();
final StringBuilder sb = new StringBuilder();
for (final StackTraceElement s : stack) {
sb.append(s.toString() + "\n");
}
return sb.toString();
}
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 matcher = PAT_LATLON.matcher(string);
if (matcher.matches())
return new String[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
return null;
}
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]
};
}
}
| 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.net.Uri;
public class UriParser {
public Uri parse(String uriString) {
return Uri.parse(uriString);
}
}
| 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.ui.CacheDetailsOnClickListener;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheViewer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
public class GeoBeagleDelegate {
static GeoBeagleDelegate buildGeoBeagleDelegate(GeoBeagle parent,
AppLifecycleManager appLifecycleManager, GeocacheViewer geocacheViewer,
ErrorDisplayer errorDisplayer) {
final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(parent);
final DialogInterface.OnClickListener cacheDetailsOkListener = new CacheDetailsOnClickListener.OkListener();
final CacheDetailsOnClickListener.Env env = new CacheDetailsOnClickListener.Env(
LayoutInflater.from(parent));
final CacheDetailsOnClickListener cacheDetailsOnClickListener = CacheDetailsOnClickListener
.create(parent, cacheDetailsBuilder, geocacheViewer, errorDisplayer, env);
return new GeoBeagleDelegate(parent, appLifecycleManager, cacheDetailsBuilder,
cacheDetailsOkListener, cacheDetailsOnClickListener, errorDisplayer);
}
private final AppLifecycleManager mAppLifecycleManager;
private final Builder mCacheDetailsBuilder;
private final OnClickListener mCacheDetailsOkListener;
private final CacheDetailsOnClickListener mCacheDetailsOnClickListener;
private final ErrorDisplayer mErrorDisplayer;
private final Activity mParent;
public GeoBeagleDelegate(Activity parent, AppLifecycleManager appLifecycleManager,
Builder cacheDetailsBuilder, OnClickListener cacheDetailsOkListener,
CacheDetailsOnClickListener cacheDetailsOnClickListener, ErrorDisplayer errorDisplayer) {
mParent = parent;
mAppLifecycleManager = appLifecycleManager;
mCacheDetailsBuilder = cacheDetailsBuilder;
mCacheDetailsOkListener = cacheDetailsOkListener;
mCacheDetailsOnClickListener = cacheDetailsOnClickListener;
mErrorDisplayer = errorDisplayer;
}
public void onCreate() {
mCacheDetailsBuilder.setPositiveButton("Ok", mCacheDetailsOkListener);
mCacheDetailsBuilder.create();
((Button)mParent.findViewById(R.id.cache_details))
.setOnClickListener(mCacheDetailsOnClickListener);
}
public void onPause() {
try {
mAppLifecycleManager.onPause();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
public void onResume() {
try {
mAppLifecycleManager.onResume();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| 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.gpx;
import com.google.code.geobeagle.gpx.gpx.GpxFileOpener;
import com.google.code.geobeagle.gpx.zip.ZipFileOpener;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class GpxAndZipFiles {
public static class GpxAndZipFilesIter {
private final String[] mFileList;
private final GpxAndZipFilesIterFactory mGpxAndZipFileIterFactory;
private int mIxFileList;
private IGpxReaderIter mSubIter;
GpxAndZipFilesIter(String[] fileList, GpxAndZipFilesIterFactory gpxAndZipFilesIterFactory) {
mFileList = fileList;
mGpxAndZipFileIterFactory = gpxAndZipFilesIterFactory;
mIxFileList = 0;
}
public boolean hasNext() throws IOException {
if (mSubIter != null && mSubIter.hasNext())
return true;
return mIxFileList < mFileList.length;
}
public IGpxReader next() throws IOException {
if (mSubIter == null || !mSubIter.hasNext())
mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]);
return mSubIter.next();
}
}
public static class GpxAndZipFilesIterFactory {
public IGpxReaderIter fromFile(String filename) throws IOException {
if (filename.endsWith(".zip")) {
return new ZipFileOpener(GPX_DIR + filename, new ZipInputStreamFactory())
.iterator();
}
return new GpxFileOpener(filename).iterator();
}
}
public static class GpxAndZipFilenameFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".zip"));
}
}
public static final String GPX_DIR = "/sdcard/download/";
private final FilenameFilter mFilenameFilter;
private final GpxAndZipFilesIterFactory mGpxFileIterFactory;
public GpxAndZipFiles(FilenameFilter filenameFilter,
GpxAndZipFilesIterFactory gpxFileIterFactory) {
mFilenameFilter = filenameFilter;
mGpxFileIterFactory = gpxFileIterFactory;
}
public GpxAndZipFilesIter iterator() {
String[] fileList = new File(GPX_DIR).list(mFilenameFilter);
if (fileList == null)
return null;
return new GpxAndZipFilesIter(fileList, mGpxFileIterFactory);
}
}
| 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.gpx.gpx;
import com.google.code.geobeagle.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.gpx.IGpxReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
public GpxReader(String filename) {
mFilename = filename;
}
public String getFilename() {
return mFilename;
}
public Reader open() throws FileNotFoundException {
return new BufferedReader(new FileReader(GpxAndZipFiles.GPX_DIR + mFilename));
}
}
| 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.gpx.gpx;
import com.google.code.geobeagle.gpx.IGpxReader;
import com.google.code.geobeagle.gpx.IGpxReaderIter;
public class GpxFileOpener {
class GpxFileIter implements IGpxReaderIter {
public boolean hasNext() {
return mFilename != null;
}
public IGpxReader next() {
final IGpxReader gpxReader = new GpxReader(mFilename);
mFilename = null;
return gpxReader;
}
}
private String mFilename;
public GpxFileOpener(String filename) {
mFilename = filename;
}
public IGpxReaderIter iterator() {
return new GpxFileIter();
}
}
| 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.gpx;
import java.io.FileNotFoundException;
import java.io.Reader;
public interface IGpxReader {
String getFilename();
Reader open() throws FileNotFoundException;
}
| 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.gpx;
import java.io.IOException;
public interface IGpxReaderIter {
public boolean hasNext() throws IOException;
public IGpxReader next() throws IOException;
} | 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.gpx.zip;
import com.google.code.geobeagle.gpx.IGpxReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
private final Reader mReader;
GpxReader(String filename, Reader reader) {
mFilename = filename;
mReader = reader;
}
public String getFilename() {
return mFilename;
}
public Reader open() {
return mReader;
}
}
| 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.gpx.zip;
import com.google.code.geobeagle.gpx.IGpxReader;
import com.google.code.geobeagle.gpx.IGpxReaderIter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
public class ZipFileOpener {
public static class ZipFileIter implements IGpxReaderIter {
private ZipEntry mNextZipEntry;
private final GpxZipInputStream mZipInputStream;
ZipFileIter(GpxZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
mNextZipEntry = null;
}
public boolean hasNext() throws IOException {
if (mNextZipEntry == null)
mNextZipEntry = mZipInputStream.getNextEntry();
return mNextZipEntry != null;
}
public IGpxReader next() throws IOException {
if (mNextZipEntry == null)
mNextZipEntry = mZipInputStream.getNextEntry();
if (mNextZipEntry == null)
return null;
final String name = mNextZipEntry.getName();
mNextZipEntry = null;
return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream()));
}
}
private final String mFilename;
private final ZipInputStreamFactory mZipInputStreamFactory;
public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory) {
mFilename = filename;
mZipInputStreamFactory = zipInputStreamFactory;
}
public ZipFileIter iterator() throws IOException {
GpxZipInputStream zipInputStream = mZipInputStreamFactory.create(mFilename);
return new ZipFileIter(zipInputStream);
}
}
| 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.gpx.zip;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GpxZipInputStream {
private ZipEntry mNextEntry;
private final ZipInputStream mZipInputStream;
public GpxZipInputStream(ZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
}
ZipEntry getNextEntry() throws IOException {
mNextEntry = null;
mNextEntry = mZipInputStream.getNextEntry();
while (mNextEntry != null && mNextEntry.getName().endsWith("-wpts.gpx")) {
mNextEntry = mZipInputStream.getNextEntry();
}
return mNextEntry;
}
InputStream getStream() throws IOException {
return mZipInputStream;
}
}
| 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.ui.GpsStatusWidget;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/*
* Listener for the Location control.
*/
public class GeoBeagleLocationListener implements LocationListener {
private final LocationControl mLocationControl;
private final GpsStatusWidget mLocationViewer;
public GeoBeagleLocationListener(LocationControl locationControl, GpsStatusWidget gpsStatusWidget) {
mLocationViewer = gpsStatusWidget;
mLocationControl = locationControl;
}
public void onLocationChanged(Location location) {
// Ask the location control to pick the most accurate location (might
// not be this one).
mLocationViewer.setLocation(mLocationControl.getLocation());
}
public void onProviderDisabled(String provider) {
mLocationViewer.setDisabled();
}
public void onProviderEnabled(String provider) {
mLocationViewer.setEnabled();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
mLocationViewer.setStatus(provider, status);
}
}
| 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.intents;
import com.google.code.geobeagle.data.Geocache;
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.intents;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.ui.ContentSelector;
import com.google.code.geobeagle.ui.GetCoordsToast;
import com.google.code.geobeagle.ui.MyLocationProvider;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
public class IntentStarterLocation implements IntentStarter {
private final Activity mActivity;
private final ContentSelector mContentSelector;
private final GetCoordsToast mGetCoordsToast;
private final IntentFactory mIntentFactory;
private final MyLocationProvider mMyLocationProvider;
private final ResourceProvider mResourceProvider;
private final int mUriId;
public IntentStarterLocation(Activity activity, ResourceProvider resourceProvider,
IntentFactory intentFactory, MyLocationProvider myLocationProvider,
ContentSelector contentSelector, int uriId, GetCoordsToast getCoordsToast) {
mActivity = activity;
mGetCoordsToast = getCoordsToast;
mIntentFactory = intentFactory;
mMyLocationProvider = myLocationProvider;
mResourceProvider = resourceProvider;
mContentSelector = contentSelector;
mUriId = uriId;
}
public void startIntent() {
final Location location = mMyLocationProvider.getLocation();
if (location == null)
return;
mGetCoordsToast.show();
mActivity.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, String.format(
mResourceProvider.getStringArray(mUriId)[mContentSelector.getIndex()], location
.getLatitude(), location.getLongitude())));
}
}
| 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.intents;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.ui.GeocacheViewer;
import android.content.Intent;
public class IntentStarterViewUri implements IntentStarter {
private final GeoBeagle mGeoBeagle;
private final GeocacheToUri mGeocacheToUri;
private final IntentFactory mIntentFactory;
public IntentStarterViewUri(GeoBeagle geoBeagle, IntentFactory intentFactory,
GeocacheViewer geocacheViewer, GeocacheToUri geocacheToUri) {
mGeoBeagle = geoBeagle;
mGeocacheToUri = geocacheToUri;
mIntentFactory = intentFactory;
}
public void startIntent() {
mGeoBeagle.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, mGeocacheToUri
.convert(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.intents;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.Geocache;
public class GeocacheToGoogleMap implements GeocacheToUri {
private final ResourceProvider mResourceProvider;
public GeocacheToGoogleMap(ResourceProvider resourceProvider) {
mResourceProvider = resourceProvider;
}
public String convert(Geocache geocache) {
// "geo:%1$.5f,%2$.5f?name=cachename"
return String.format(mResourceProvider.getString(R.string.map_intent), geocache
.getLatitude(), geocache.getLongitude(), geocache.getIdAndName());
}
}
| 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.intents;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.data.Geocache;
import android.content.Intent;
public class IntentStarterRadar implements IntentStarter {
private final IntentFactory mIntentFactory;
private final GeoBeagle mGeoBeagle;
public IntentStarterRadar(GeoBeagle geoBeagle, IntentFactory intentFactory) {
mIntentFactory = intentFactory;
mGeoBeagle = geoBeagle;
}
public void startIntent() {
final Geocache geocache = mGeoBeagle.getGeocache();
final Intent intent = mIntentFactory.createIntent("com.google.android.radar.SHOW_RADAR");
intent.putExtra("latitude", (float)geocache.getLatitude());
intent.putExtra("longitude", (float)geocache.getLongitude());
mGeoBeagle.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.intents;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.Geocache;
/*
* Convert a Geocache to the cache page url.
*/
public class GeocacheToCachePage implements GeocacheToUri {
private final ResourceProvider mResourceProvider;
public GeocacheToCachePage(ResourceProvider resourceProvider) {
mResourceProvider = resourceProvider;
}
// TODO: move strings into Provider enum.
public String convert(Geocache geocache) {
return String.format(mResourceProvider.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.intents;
import com.google.code.geobeagle.UriParser;
import android.content.Intent;
public class IntentFactory {
private final UriParser mUriParser;
public IntentFactory(UriParser uriParser) {
mUriParser = uriParser;
}
public Intent createIntent(String action) {
return new Intent(action);
}
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.intents;
public interface IntentStarter {
public abstract void startIntent();
}
| 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.ui;
import com.google.code.geobeagle.intents.IntentStarter;
import android.app.Activity;
import android.widget.Button;
public class OnCacheButtonClickListenerBuilder {
private final Activity mContext;
private final ErrorDisplayer mErrorDisplayer;
public OnCacheButtonClickListenerBuilder(Activity context, ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mContext = context;
}
public void set(int id, IntentStarter intentStarter, String errorString) {
((Button)mContext.findViewById(id)).setOnClickListener(new CacheButtonOnClickListener(
intentStarter, mErrorDisplayer, errorString));
}
}
| 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.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
public class OnContentProviderSelectedListener implements OnItemSelectedListener {
private final MockableTextView mContentProviderCaption;
private final ResourceProvider mResourceProvider;
public OnContentProviderSelectedListener(ResourceProvider resourceProvider,
MockableTextView contentProviderCaption) {
mResourceProvider = resourceProvider;
mContentProviderCaption = contentProviderCaption;
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String[] objectNames = mResourceProvider.getStringArray(R.array.object_names);
mContentProviderCaption.setText(mResourceProvider.getString(R.string.search_for) + " "
+ objectNames[position] + ":");
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
| 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.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.ui.GeocacheRowInflater.GeocacheRowViews;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class GeocacheListAdapter extends BaseAdapter {
private final GeocacheVectors mGeocacheVectors;
private final GeocacheRowInflater mCacheRow;
public GeocacheListAdapter(GeocacheVectors geocacheVectors, GeocacheRowInflater geocacheRowInflater) {
mGeocacheVectors = geocacheVectors;
mCacheRow = geocacheRowInflater;
}
public int getCount() {
return mGeocacheVectors.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mCacheRow.inflateIfNecessary(convertView);
((GeocacheRowViews)convertView.getTag()).set(mGeocacheVectors.get(position));
return convertView;
}
}
| 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.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.ui.Misc.Time;
import android.location.Location;
import android.location.LocationProvider;
/**
* @author sng Displays the GPS status (accuracy, availability, etc).
*/
public class GpsStatusWidget {
public static class MeterFormatter {
public int accuracyToBarCount(float accuracy) {
return Math.min(METER_LEFT.length(), (int)(Math.log(Math.max(1, accuracy)) / Math
.log(2)));
}
public String barsToMeterText(int bars) {
return METER_LEFT.substring(METER_LEFT.length() - bars) + "×"
+ METER_RIGHT.substring(0, bars);
}
public int lagToAlpha(long milliseconds) {
return Math.max(128, 255 - (int)(milliseconds >> 3));
}
}
public static class MeterView {
private final MeterFormatter mMeterFormatter;
private final MockableTextView mTextView;
public MeterView(MockableTextView textView, MeterFormatter meterFormatter) {
mTextView = textView;
mMeterFormatter = meterFormatter;
}
public void set(long lag, float accuracy) {
mTextView.setText(mMeterFormatter.barsToMeterText(mMeterFormatter
.accuracyToBarCount(accuracy)));
mTextView.setTextColor(mMeterFormatter.lagToAlpha(lag), 147, 190, 38);
}
}
public final static String METER_LEFT = "····«····‹····";
public final static String METER_RIGHT = "····›····»····";
private float mAccuracy;
private final MockableTextView mAccuracyView;
private final MockableTextView mLag;
private long mLastUpdateTime;
private long mLocationTime;
private final MeterView mMeterView;
private final MockableTextView mProvider;
private final ResourceProvider mResourceProvider;
private final MockableTextView mStatus;
private final Time mTime;
public GpsStatusWidget(ResourceProvider resourceProvider, MeterView meterView,
MockableTextView provider, MockableTextView lag, MockableTextView accuracy,
MockableTextView status, Time time, Location initialLocation) {
mResourceProvider = resourceProvider;
mMeterView = meterView;
mLag = lag;
mAccuracyView = accuracy;
mProvider = provider;
mStatus = status;
mTime = time;
}
public void refreshLocation() {
long currentTime = mTime.getCurrentTime();
long lastUpdateLag = currentTime - mLastUpdateTime;
long locationLag = currentTime - mLocationTime;
mLag.setText((locationLag / 1000 + "s").trim());
mAccuracyView.setText((mAccuracy + "m").trim());
mMeterView.set(lastUpdateLag, mAccuracy);
};
public void setDisabled() {
mStatus.setText("DISABLED");
}
public void setEnabled() {
mStatus.setText("ENABLED");
}
public void setLocation(Location location) {
// TODO: use currentTime for alpha channel, but locationTime for text
// lag.
mLastUpdateTime = mTime.getCurrentTime();
mLocationTime = Math.min(location.getTime(), mLastUpdateTime);
mProvider.setText(location.getProvider());
mAccuracy = location.getAccuracy();
}
public void setStatus(String provider, int status) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.out_of_service));
break;
case LocationProvider.AVAILABLE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.available));
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.temporarily_unavailable));
break;
}
}
}
| 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.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.Geocache.Provider;
import com.google.code.geobeagle.data.Geocache.Source;
import android.view.View;
public class WebPageAndDetailsButtonEnabler {
private final View mWebPageButton;
private final View mDetailsButton;
private final GeoBeagle mGeoBeagle;
WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, View cachePageButton, View detailsButton) {
mGeoBeagle = geoBeagle;
mWebPageButton = cachePageButton;
mDetailsButton = detailsButton;
}
public void check() {
Geocache geocache = mGeoBeagle.getGeocache();
mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX);
final Provider contentProvider = geocache.getContentProvider();
mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK
|| contentProvider == Provider.ATLAS_QUEST);
}
}
| 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.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.IGeocacheVector;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class GeocacheRowInflater {
public static class GeocacheRowViews {
private final TextView mCache;
private final TextView mDistance;
public GeocacheRowViews(TextView cache, TextView txtDistance) {
mCache = cache;
mDistance = txtDistance;
}
public void set(IGeocacheVector geocacheVector) {
mCache.setText(geocacheVector.getIdAndName());
mDistance.setText(geocacheVector.getFormattedDistance());
}
}
private final LayoutInflater mLayoutInflater;
public GeocacheRowInflater(LayoutInflater layoutInflater) {
mLayoutInflater = layoutInflater;
}
public View inflateIfNecessary(View convertView) {
if (convertView != null) {
return convertView;
}
convertView = mLayoutInflater.inflate(R.layout.cache_row, null);
GeocacheRowViews geocacheRowViews = new GeocacheRowViews(((TextView)convertView
.findViewById(R.id.txt_cache)), ((TextView)convertView.findViewById(R.id.distance)));
convertView.setTag(geocacheRowViews);
return convertView;
}
}
| 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.ui;
import com.google.code.geobeagle.R;
import android.content.Context;
import android.widget.Toast;
public class GetCoordsToast {
private final Toast mToast;
public GetCoordsToast(Context context) {
mToast = Toast.makeText(context, R.string.get_coords_toast, Toast.LENGTH_LONG);
}
public void show() {
mToast.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.ui;
import com.google.code.geobeagle.LifecycleManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Spinner;
public class ContentSelector implements LifecycleManager {
private static final String CONTENT_PROVIDER = "ContentProvider";
private final SharedPreferences mPreferences;
private final Spinner mSpinner;
public ContentSelector(Spinner spinner, SharedPreferences sharedPreferences) {
mSpinner = spinner;
mPreferences = sharedPreferences;
}
public int getIndex() {
return mSpinner.getSelectedItemPosition();
}
public void onPause(Editor editor) {
editor.putInt(CONTENT_PROVIDER, mSpinner.getSelectedItemPosition());
}
public void onResume(SharedPreferences preferences) {
mSpinner.setSelection(mPreferences.getInt(CONTENT_PROVIDER, 1));
}
}
| Java |
/**
*
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.R;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CacheDetailsOnClickListener implements View.OnClickListener {
public static class CacheDetailsLoader {
public String load(Env env, ErrorDisplayer mErrorDisplayer, CharSequence id) {
final String path = "/sdcard/GeoBeagle/" + id + ".html";
try {
FileInputStream fileInputStream = env.createFileInputStream(path);
byte[] buffer = env.createBuffer(fileInputStream.available());
fileInputStream.read(buffer);
fileInputStream.close();
return new String(buffer);
} catch (FileNotFoundException e) {
return "Error opening cache details file '" + path
+ "'. Please try unmounting your sdcard or re-importing the cache file.";
} catch (IOException e) {
return "Error reading cache details file '" + path
+ "'. Please try unmounting your sdcard or re-importing the cache file.";
}
}
}
public static class Env {
LayoutInflater mLayoutInflater;
public Env(LayoutInflater layoutInflater) {
mLayoutInflater = layoutInflater;
}
public byte[] createBuffer(int size) {
return new byte[size];
}
public FileInputStream createFileInputStream(String path) throws FileNotFoundException {
return new FileInputStream(path);
}
MockableView inflate(int resource, ViewGroup root) {
return new MockableView(mLayoutInflater.inflate(R.layout.cache_details, null));
}
}
public static class MockableView {
private final View mView;
public MockableView(View view) {
mView = view;
}
public View findViewById(int id) {
return mView.findViewById(id);
}
public View getView() {
return mView;
}
}
public static class OkListener implements DialogInterface.OnClickListener {
// @Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
public static CacheDetailsOnClickListener create(GeoBeagle geoBeagle,
Builder alertDialogBuilder, GeocacheViewer geocacheViewer,
ErrorDisplayer errorDisplayer, Env env) {
final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader();
return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, geocacheViewer,
errorDisplayer, env, cacheDetailsLoader);
}
private final Builder mAlertDialogBuilder;
private final CacheDetailsLoader mCacheDetailsLoader;
private final Env mEnv;
private final ErrorDisplayer mErrorDisplayer;
private GeoBeagle mGeoBeagle;
public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder,
GeocacheViewer geocacheViewer, ErrorDisplayer errorDisplayer, Env env,
CacheDetailsLoader cacheDetailsLoader) {
mAlertDialogBuilder = alertDialogBuilder;
mErrorDisplayer = errorDisplayer;
mEnv = env;
mCacheDetailsLoader = cacheDetailsLoader;
mGeoBeagle = geoBeagle;
}
public void onClick(View v) {
try {
MockableView detailsView = mEnv.inflate(R.layout.cache_details, null);
CharSequence id = mGeoBeagle.getGeocache().getId();
mAlertDialogBuilder.setTitle(id);
mAlertDialogBuilder.setView(detailsView.getView());
WebView webView = (WebView)detailsView.findViewById(R.id.webview);
webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(mEnv, mErrorDisplayer, id),
"text/html", "utf-8", "about:blank");
mAlertDialogBuilder.create().show();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| 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.ui;
interface Action {
public void act(int position, GeocacheListAdapter geocacheListAdapter);
}
| 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.ui;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class MockableEditText {
private final EditText mEditText;
public MockableEditText(EditText editText) {
mEditText = editText;
}
public CharSequence getText() {
return mEditText.getText();
}
public void setOnFocusChangeListener(OnFocusChangeListener l) {
mEditText.setOnFocusChangeListener(l);
}
public void setText(CharSequence s) {
mEditText.setText(s);
}
}
| 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.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
public class DeleteAction implements Action {
private final CacheWriter mCacheWriter;
private final Database mDatabase;
private final SQLiteWrapper mSQLiteWrapper;
private final GeocacheVectors mGeocacheVectors;
DeleteAction(Database database, SQLiteWrapper sqliteWrapper, CacheWriter cacheWriter,
GeocacheVectors geocacheVectors, ErrorDisplayer errorDisplayer) {
mGeocacheVectors = geocacheVectors;
mDatabase = database;
mSQLiteWrapper = sqliteWrapper;
mCacheWriter = cacheWriter;
}
public void act(int position, GeocacheListAdapter geocacheListAdapter) {
// TODO: pull sqliteDatabase and then cachewriter up to top level so
// they're shared.
mSQLiteWrapper.openWritableDatabase(mDatabase);
mCacheWriter.deleteCache(mGeocacheVectors.get(position).getId());
mSQLiteWrapper.close();
mGeocacheVectors.remove(position);
geocacheListAdapter.notifyDataSetChanged();
}
}
| 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.ui;
import com.google.code.geobeagle.Util;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
// TODO: this class needs tests.
public class ErrorDisplayer {
private class DisplayErrorRunnable implements Runnable {
private DisplayErrorRunnable() {
}
public void run() {
mAlertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
mAlertDialogBuilder.create().show();
}
}
private final Activity mActivity;
private Builder mAlertDialogBuilder;
public ErrorDisplayer(Activity activity) {
mActivity = activity;
}
public void displayError(int resourceId) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(resourceId);
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
public void displayError(int resId, Object... args) {
displayError(String.format((String)mActivity.getText(resId), args));
}
public void displayError(String string) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(string);
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
public void displayErrorAndStack(Exception e) {
displayErrorAndStack("", e);
}
public void displayErrorAndStack(String msg, Exception e) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(("Error " + msg + ":" + e.toString() + "\n\n" + Util
.getStackTrace(e)));
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
}
| 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.ui;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MockableButton extends MockableTextView {
private final Button mButton;
public MockableButton(Button button) {
super(button);
mButton = button;
}
public void setOnClickListener(OnClickListener onClickListener) {
mButton.setOnClickListener(onClickListener);
}
@Override
public void setTextColor(int red) {
mButton.setTextColor(red);
}
}
| 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.ui;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.CacheListData;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.GpxImporter;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import java.util.ArrayList;
public class CacheListDelegate {
public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener {
public static class Factory {
public OnCreateContextMenuListener create(GeocacheVectors geocacheVectors) {
return new CacheListOnCreateContextMenuListener(geocacheVectors);
}
}
private final GeocacheVectors mGeocacheVectors;
CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors) {
mGeocacheVectors = geocacheVectors;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(mGeocacheVectors.get(acmi.position).getId());
menu.add(0, MENU_VIEW, 0, "View");
if (acmi.position > 0)
menu.add(0, MENU_DELETE, 1, "Delete");
}
}
public static final int MENU_DELETE = 0;
public static final int MENU_VIEW = 1;
public static final String SELECT_CACHE = "SELECT_CACHE";
private final Action mActions[];
private final CacheListData mCacheListData;
private final GeocachesSql mGeocachesSql;
private final CacheListOnCreateContextMenuListener.Factory mCreateContextMenuFactory;
private final ErrorDisplayer mErrorDisplayer;
private final GpxImporter mGpxImporter;
private final LocationControl mLocationControl;
private final ListActivity mParent;
private final GeocacheListAdapter mGeocacheListAdapter;
private final GeocacheVectors mGeocacheVectors;
CacheListDelegate(ListActivity parent, GeocachesSql geocachesSql,
LocationControl locationControl, CacheListData cacheListData,
GeocacheVectors geocacheVectors, GeocacheListAdapter geocacheListAdapter,
ErrorDisplayer errorDisplayer, Action[] actions,
CacheListOnCreateContextMenuListener.Factory factory, GpxImporter gpxImporter) {
mParent = parent;
mGeocachesSql = geocachesSql;
mLocationControl = locationControl;
mCacheListData = cacheListData;
mGeocacheVectors = geocacheVectors;
mErrorDisplayer = errorDisplayer;
mActions = actions;
mCreateContextMenuFactory = factory;
mGpxImporter = gpxImporter;
mGeocacheListAdapter = geocacheListAdapter;
}
public boolean onContextItemSelected(MenuItem menuItem) {
try {
AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem
.getMenuInfo();
mActions[menuItem.getItemId()].act(adapterContextMenuInfo.position,
mGeocacheListAdapter);
return true;
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
return false;
}
public void onCreate() {
mParent.setContentView(R.layout.cache_list);
mParent.getListView().setOnCreateContextMenuListener(
mCreateContextMenuFactory.create(mGeocacheVectors));
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(R.string.menu_import_gpx);
return true;
}
public void onListItemClick(ListView l, View v, int position, long id) {
try {
mActions[MENU_VIEW].act(position, mGeocacheListAdapter);
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
mGpxImporter.importGpxs(this);
return true;
}
public void onPause() {
try {
mGpxImporter.abort();
} catch (InterruptedException e) {
// Nothing we can do here! There is no chance to communicate to the
// user.
}
}
public void onResume() {
try {
mGeocachesSql.loadNearestCaches();
ArrayList<Geocache> geocaches = mGeocachesSql.getGeocaches();
mCacheListData.add(geocaches, mLocationControl.getLocation());
mParent.setListAdapter(mGeocacheListAdapter);
mParent.setTitle("Nearest Unfound Caches (" + geocaches.size() + " / "
+ mGeocachesSql.getCount() + ")");
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| 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.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Util;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.io.LocationSaver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class EditCacheActivityDelegate {
public static class CancelButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
public CancelButtonOnClickListener(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
// TODO: replace magic number.
mActivity.setResult(-1, null);
mActivity.finish();
}
}
public static class EditCache {
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(EditText id, EditText name, EditText latitude, EditText longitude) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return new Geocache(mId.getText(), mName.getText(), Util.parseCoordinate(mLatitude
.getText()), Util.parseCoordinate(mLongitude.getText()), mOriginalGeocache
.getSourceType(), mOriginalGeocache.getSourceName());
}
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.requestFocus();
}
}
public static class SetButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
private final EditCache mGeocacheView;
private final LocationSaver mLocationSaver;
public SetButtonOnClickListener(Activity activity, EditCache editCache,
LocationSaver locationSaver) {
mActivity = activity;
mGeocacheView = editCache;
mLocationSaver = locationSaver;
}
public void onClick(View v) {
Geocache geocache = mGeocacheView.get();
mLocationSaver.saveLocation(geocache);
Intent i = new Intent();
i.setAction(CacheListDelegate.SELECT_CACHE);
i.putExtra("geocache", geocache);
mActivity.setResult(0, i);
mActivity.finish();
}
}
private final CancelButtonOnClickListener mCancelButtonOnClickListener;
private final LocationSaver mLocationSaver;
private final Activity mParent;
public EditCacheActivityDelegate(Activity parent,
CancelButtonOnClickListener cancelButtonOnClickListener, LocationSaver locationSaver) {
mParent = parent;
mCancelButtonOnClickListener = cancelButtonOnClickListener;
mLocationSaver = locationSaver;
}
public void onCreate(Bundle savedInstanceState) {
mParent.setContentView(R.layout.cache_edit);
}
public void onResume() {
Intent intent = mParent.getIntent();
Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
EditCache editCache = new EditCache((EditText)mParent.findViewById(R.id.edit_id),
(EditText)mParent.findViewById(R.id.edit_name), (EditText)mParent
.findViewById(R.id.edit_latitude), (EditText)mParent
.findViewById(R.id.edit_longitude));
editCache.set(geocache);
SetButtonOnClickListener setButtonOnClickListener = new SetButtonOnClickListener(mParent,
editCache, mLocationSaver);
((Button)mParent.findViewById(R.id.edit_set)).setOnClickListener(setButtonOnClickListener);
Button cancel = (Button)mParent.findViewById(R.id.edit_cancel);
cancel.setOnClickListener(mCancelButtonOnClickListener);
}
}
| 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.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import android.content.Context;
import android.content.Intent;
public class ViewAction implements Action {
private final Context mContext;
private final Intent mIntent;
private GeocacheVectors mGeocacheVectors;
ViewAction(GeocacheVectors geocacheVectors, Context context, Intent intent) {
mGeocacheVectors = geocacheVectors;
mContext = context;
mIntent = intent;
}
public void act(int position, GeocacheListAdapter geocacheListAdapter) {
mIntent.putExtra("geocache", mGeocacheVectors.get(position).getGeocache()).setAction(
CacheListDelegate.SELECT_CACHE);
mContext.startActivity(mIntent);
}
}
| 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.ui;
import android.graphics.Color;
import android.widget.TextView;
public class MockableTextView {
private final TextView mTextView;
public MockableTextView(TextView textView) {
mTextView = textView;
}
public CharSequence getText() {
return mTextView.getText();
}
public void setEnabled(boolean enabled) {
mTextView.setEnabled(enabled);
}
public void setText(CharSequence text) {
mTextView.setText(text);
}
public void setText(int id) {
mTextView.setText(id);
}
public void setTextColor(int color) {
mTextView.setTextColor(color);
}
public void setTextColor(int alpha, int r, int g, int b) {
mTextView.setTextColor(Color.argb(alpha, r, g, b));
}
}
| 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.ui;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import android.location.Location;
public class MyLocationProvider {
private final ErrorDisplayer mErrorDisplayer;
private final LocationControl mLocationControl;
public MyLocationProvider(LocationControl locationControl, ErrorDisplayer errorDisplayer) {
mLocationControl = locationControl;
mErrorDisplayer = errorDisplayer;
}
public Location getLocation() {
Location location = mLocationControl.getLocation();
if (null == location) {
mErrorDisplayer.displayError(R.string.error_cant_get_location);
}
return location;
}
}
| 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.ui;
import com.google.code.geobeagle.Util;
import com.google.code.geobeagle.data.Geocache;
import android.widget.TextView;
public class GeocacheViewer {
public static final String FNAME_RECENT_LOCATIONS = "RECENT_LOCATIONS";
public static final String PREFS_LOCATION = "Location";
private final TextView mId;
private final TextView mName;
private final TextView mCoords;
public GeocacheViewer(TextView gcid, TextView gcname, TextView gccoords) {
mId = gcid;
mName = gcname;
mCoords = gccoords;
}
public void set(Geocache geocache) {
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mCoords.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()) + ", "
+ Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
}
}
| 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.ui;
import com.google.code.geobeagle.intents.IntentStarter;
import android.content.ActivityNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
public class CacheButtonOnClickListener implements OnClickListener {
private final IntentStarter mDestinationToIntentFactory;
private final ErrorDisplayer mErrorDisplayer;
private final String mErrorMessage;
public CacheButtonOnClickListener(IntentStarter intentStarter, ErrorDisplayer errorDisplayer,
String errorMessage) {
mDestinationToIntentFactory = intentStarter;
mErrorDisplayer = errorDisplayer;
mErrorMessage = errorMessage;
}
public void onClick(View view) {
try {
mDestinationToIntentFactory.startIntent();
} catch (final ActivityNotFoundException e) {
mErrorDisplayer.displayError("Error: " + e.getMessage() + mErrorMessage);
} catch (final Exception e) {
mErrorDisplayer.displayError("Error: " + 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.ui;
import com.google.code.geobeagle.CacheList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
public class GeocacheListOnClickListener implements OnClickListener {
final private Activity mActivity;
public GeocacheListOnClickListener(Activity activity) {
mActivity = activity;
}
protected Intent createIntent(Context context, Class<?> cls) {
return new Intent(context, cls);
}
public void onClick(View v) {
mActivity.startActivity(createIntent(mActivity, CacheList.class));
}
}
| 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.location.Location;
import android.location.LocationManager;
public class LocationControl {
public static class LocationChooser {
/**
* 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.)
*/
public Location choose(Location location1, Location location2) {
if (location1 == null)
return location2;
if (location2 == null)
return location1;
if (location2.getTime() > location1.getTime()) {
if (location2.getAccuracy() <= location1.getAccuracy())
return location2;
else if (location1.distanceTo(location2) >= location1.getAccuracy()
+ location2.getAccuracy()) {
return location2;
}
}
return location1;
}
}
private final LocationChooser mLocationChooser;
private final LocationManager mLocationManager;
LocationControl(LocationManager locationManager, LocationChooser locationChooser) {
mLocationManager = locationManager;
mLocationChooser = locationChooser;
}
/*
* (non-Javadoc)
* @see
* com.android.geobrowse.GpsControlI#getLocation(android.content.Context)
*/
public Location getLocation() {
return mLocationChooser.choose(mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER), mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
}
}
| 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.LocationControl.LocationChooser;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.GeocacheFromPreferencesFactory;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.intents.GeocacheToCachePage;
import com.google.code.geobeagle.intents.GeocacheToGoogleMap;
import com.google.code.geobeagle.intents.IntentFactory;
import com.google.code.geobeagle.intents.IntentStarterLocation;
import com.google.code.geobeagle.intents.IntentStarterRadar;
import com.google.code.geobeagle.intents.IntentStarterViewUri;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ContentSelector;
import com.google.code.geobeagle.ui.EditCacheActivity;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheListOnClickListener;
import com.google.code.geobeagle.ui.GeocacheViewer;
import com.google.code.geobeagle.ui.GetCoordsToast;
import com.google.code.geobeagle.ui.GpsStatusWidget;
import com.google.code.geobeagle.ui.Misc;
import com.google.code.geobeagle.ui.MockableTextView;
import com.google.code.geobeagle.ui.MyLocationProvider;
import com.google.code.geobeagle.ui.OnCacheButtonClickListenerBuilder;
import com.google.code.geobeagle.ui.OnContentProviderSelectedListener;
import com.google.code.geobeagle.ui.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.ui.GpsStatusWidget.MeterFormatter;
import com.google.code.geobeagle.ui.GpsStatusWidget.MeterView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationManager;
import android.net.UrlQuerySanitizer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
/*
* Main Activity for GeoBeagle.
*/
public class GeoBeagle extends Activity implements LifecycleManager {
private WebPageAndDetailsButtonEnabler mWebPageButtonEnabler;
private ContentSelector mContentSelector;
private final ErrorDisplayer mErrorDisplayer;
private GeoBeagleDelegate mGeoBeagleDelegate;
private Geocache mGeocache;
private GeocacheFromPreferencesFactory mGeocacheFromPreferencesFactory;
private GeocacheViewer mGeocacheViewer;
private LocationControl mGpsControl;
private final Handler mHandler;
private GeoBeagleLocationListener mLocationListener;
private GpsStatusWidget mLocationViewer;
private final ResourceProvider mResourceProvider;
private final Runnable mUpdateTimeTask = new Runnable() {
public void run() {
mLocationViewer.refreshLocation();
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
private LocationSaver mLocationSaver;
public GeoBeagle() {
super();
mErrorDisplayer = new ErrorDisplayer(this);
mResourceProvider = new ResourceProvider(this);
mHandler = new Handler();
}
private MockableTextView createTextView(int id) {
return new MockableTextView((TextView)findViewById(id));
}
private void getCoordinatesFromIntent(GeocacheViewer geocacheViewer, Intent intent,
ErrorDisplayer errorDisplayer) {
try {
if (intent.getType() == null) {
final String query = intent.getData().getQuery();
final CharSequence sanitizedQuery = Util.parseHttpUri(query,
new UrlQuerySanitizer(), UrlQuerySanitizer
.getAllButNulAndAngleBracketsLegal());
final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery);
mGeocache = new Geocache(latlon[2], latlon[3], Util.parseCoordinate(latlon[0]),
Util.parseCoordinate(latlon[1]), Source.WEB_URL, null);
mLocationSaver.saveLocation(mGeocache);
geocacheViewer.set(mGeocache);
}
} catch (final Exception e) {
errorDisplayer.displayError("Error: " + e.getMessage());
}
}
public Geocache getGeocache() {
return mGeocache;
}
private boolean maybeGetCoordinatesFromIntent() {
final Intent intent = getIntent();
if (intent != null) {
final String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_VIEW)) {
getCoordinatesFromIntent(mGeocacheViewer, intent, mErrorDisplayer);
return true;
} else if (action.equals(CacheListDelegate.SELECT_CACHE)) {
mGeocache = intent.<Geocache> getParcelableExtra("geocache");
mGeocacheViewer.set(mGeocache);
mWebPageButtonEnabler.check();
return true;
}
}
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 0)
setIntent(data);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GeoBeagleBuilder builder = new GeoBeagleBuilder(this);
mContentSelector = builder.createContentSelector(getPreferences(Activity.MODE_PRIVATE));
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final Database Database = DatabaseDI.create(this);
mLocationSaver = new LocationSaver(Database, sqliteWrapper, DatabaseDI
.createCacheWriter(sqliteWrapper));
mWebPageButtonEnabler = Misc.create(this,
findViewById(R.id.cache_page), findViewById(R.id.cache_details));
mLocationViewer = new GpsStatusWidget(mResourceProvider, new MeterView(
createTextView(R.id.location_viewer), new MeterFormatter()),
createTextView(R.id.provider), createTextView(R.id.lag),
createTextView(R.id.accuracy), createTextView(R.id.status),
new Misc.Time(), new Location(""));
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mGpsControl = new LocationControl(locationManager, new LocationChooser());
mLocationListener = new GeoBeagleLocationListener(mGpsControl, mLocationViewer);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
mGeocacheFromPreferencesFactory = new GeocacheFromPreferencesFactory(geocacheFactory);
final TextView gcid = (TextView)findViewById(R.id.gcid);
final TextView gcname = (TextView)findViewById(R.id.gcname);
final TextView gccoords = (TextView)findViewById(R.id.gccoords);
mGeocacheViewer = new GeocacheViewer(gcid, gcname, gccoords);
setCacheClickListeners();
((Button)findViewById(R.id.go_to_list))
.setOnClickListener(new GeocacheListOnClickListener(this));
AppLifecycleManager appLifecycleManager = new AppLifecycleManager(
getPreferences(MODE_PRIVATE), new LifecycleManager[] {
this, new LocationLifecycleManager(mLocationListener, locationManager),
mContentSelector
});
mGeoBeagleDelegate = GeoBeagleDelegate.buildGeoBeagleDelegate(this,
appLifecycleManager, mGeocacheViewer, mErrorDisplayer);
mGeoBeagleDelegate.onCreate();
((Spinner)findViewById(R.id.content_provider))
.setOnItemSelectedListener(new OnContentProviderSelectedListener(
mResourceProvider, new MockableTextView(
(TextView)findViewById(R.id.select_cache_prompt))));
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 1000);
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(R.string.menu_edit_geocache);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, EditCacheActivity.class);
intent.putExtra("geocache", mGeocache);
startActivityForResult(intent, 0);
return true;
}
@Override
public void onPause() {
super.onPause();
mGeoBeagleDelegate.onPause();
}
public void onPause(Editor editor) {
getGeocache().writeToPrefs(editor);
}
@Override
protected void onResume() {
super.onResume();
mGeoBeagleDelegate.onResume();
maybeGetCoordinatesFromIntent();
mWebPageButtonEnabler.check();
final Location location = mGpsControl.getLocation();
if (location != null)
mLocationListener.onLocationChanged(location);
}
public void onResume(SharedPreferences preferences) {
setGeocache(mGeocacheFromPreferencesFactory.create(preferences));
}
private void setCacheClickListeners() {
IntentFactory intentFactory = new IntentFactory(new UriParser());
GetCoordsToast getCoordsToast = new GetCoordsToast(this);
MyLocationProvider myLocationProvider = new MyLocationProvider(mGpsControl, mErrorDisplayer);
OnCacheButtonClickListenerBuilder cacheClickListenerSetter = new OnCacheButtonClickListenerBuilder(
this, mErrorDisplayer);
cacheClickListenerSetter.set(R.id.object_map, new IntentStarterLocation(this,
mResourceProvider, intentFactory, myLocationProvider, mContentSelector,
R.array.map_objects, getCoordsToast), "");
cacheClickListenerSetter.set(R.id.nearest_objects, new IntentStarterLocation(this,
mResourceProvider, intentFactory, myLocationProvider, mContentSelector,
R.array.nearest_objects, getCoordsToast), "");
cacheClickListenerSetter.set(R.id.maps, new IntentStarterViewUri(this, intentFactory,
mGeocacheViewer, new GeocacheToGoogleMap(mResourceProvider)), "");
cacheClickListenerSetter.set(R.id.cache_page, new IntentStarterViewUri(this, intentFactory,
mGeocacheViewer, new GeocacheToCachePage(mResourceProvider)), "");
cacheClickListenerSetter.set(R.id.radar, new IntentStarterRadar(this, intentFactory),
"\nPlease install the Radar application to use Radar.");
}
void setGeocache(Geocache geocache) {
mGeocache = geocache;
mGeocacheViewer.set(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;
import android.content.SharedPreferences;
public class AppLifecycleManager {
private final LifecycleManager[] mLifecycleManagers;
private final SharedPreferences mPreferences;
public AppLifecycleManager(SharedPreferences preferences, LifecycleManager[] lifecycleManagers) {
mLifecycleManagers = lifecycleManagers;
mPreferences = preferences;
}
public void onPause() {
final SharedPreferences.Editor editor = mPreferences.edit();
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onPause(editor);
}
editor.commit();
}
public void onResume() {
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onResume(mPreferences);
}
}
}
| 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.content.Context;
public class ResourceProvider {
private final Context mContext;
public ResourceProvider(Context context) {
mContext = context;
}
public String getString(int resourceId) {
return mContext.getString(resourceId);
}
public String[] getStringArray(int resourceId) {
return mContext.getResources().getStringArray(resourceId);
}
}
| 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.content.Intent;
public interface ActivityStarter {
void startActivity(Intent 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;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public interface LifecycleManager {
public abstract void onPause(Editor editor);
public abstract void onResume(SharedPreferences preferences);
}
| 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.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.LocationListener;
import android.location.LocationManager;
/*
* Handle onPause and onResume for the LocationManager.
*/
public class LocationLifecycleManager implements LifecycleManager {
private final LocationListener mLocationListener;
private final LocationManager mLocationManager;
public LocationLifecycleManager(LocationListener locationListener,
LocationManager locationManager) {
mLocationListener = locationListener;
mLocationManager = locationManager;
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onPause()
*/
public void onPause(Editor editor) {
mLocationManager.removeUpdates(mLocationListener);
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onResume()
*/
public void onResume(SharedPreferences preferences) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mLocationListener);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListener);
}
}
| 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.io;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.ImportThreadWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.io.GpxImporterDI.ToastFactory;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.ListActivity;
import android.widget.Toast;
public class GpxImporter {
private final Database mDatabase;
private final ErrorDisplayer mErrorDisplayer;
private final GpxLoader mGpxLoader;
private final ImportThreadWrapper mImportThreadWrapper;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final SQLiteWrapper mSqliteWrapper;
private final ToastFactory mToastFactory;
GpxImporter(GpxLoader gpxLoader, Database database, SQLiteWrapper sqliteWrapper,
ListActivity listActivity, ImportThreadWrapper importThreadWrapper,
MessageHandler messageHandler, ErrorDisplayer errorDisplayer, ToastFactory toastFactory) {
mSqliteWrapper = sqliteWrapper;
mDatabase = database;
mListActivity = listActivity;
mGpxLoader = gpxLoader;
mImportThreadWrapper = importThreadWrapper;
mMessageHandler = messageHandler;
mErrorDisplayer = errorDisplayer;
mToastFactory = toastFactory;
}
public void abort() throws InterruptedException {
mMessageHandler.abortLoad();
mGpxLoader.abort();
if (mImportThreadWrapper.isAlive()) {
mImportThreadWrapper.join();
mSqliteWrapper.close();
mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT);
}
}
public void importGpxs(CacheListDelegate cacheListDelegate) {
mSqliteWrapper.openReadableDatabase(mDatabase);
mImportThreadWrapper.open(cacheListDelegate, mGpxLoader, mErrorDisplayer);
mImportThreadWrapper.start();
}
}
| 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.io;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import android.database.Cursor;
import android.location.Location;
public class CacheReader {
public static class CacheReaderCursor {
private final Cursor mCursor;
private final GeocacheFactory mGeocacheFactory;
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
public CacheReaderCursor(Cursor cursor, GeocacheFactory geocacheFactory,
DbToGeocacheAdapter dbToGeocacheAdapter) {
mCursor = cursor;
mGeocacheFactory = geocacheFactory;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
void close() {
mCursor.close();
}
public Geocache getCache() {
String sourceName = mCursor.getString(4);
return mGeocacheFactory.create(mCursor.getString(2), mCursor.getString(3), mCursor
.getDouble(0), mCursor.getDouble(1), mDbToGeocacheAdapter
.sourceNameToSourceType(sourceName), sourceName);
}
boolean moveToNext() {
return mCursor.moveToNext();
}
}
public static class WhereFactory {
// 1 degree ~= 111km
public static final double DEGREES_DELTA = 0.08;
public String getWhere(Location location) {
if (location == null)
return null;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
double latLow = latitude - WhereFactory.DEGREES_DELTA;
double latHigh = latitude + WhereFactory.DEGREES_DELTA;
double lat_radians = Math.toRadians(latitude);
double cos_lat = Math.cos(lat_radians);
double lonLow = Math.max(-180, longitude - WhereFactory.DEGREES_DELTA / cos_lat);
double lonHigh = Math.min(180, longitude + WhereFactory.DEGREES_DELTA / cos_lat);
return "Latitude > " + latLow + " AND Latitude < " + latHigh + " AND Longitude > "
+ lonLow + " AND Longitude < " + lonHigh;
}
}
public static final String SQL_QUERY_LIMIT = "1000";
private final DatabaseDI.CacheReaderCursorFactory mCacheReaderCursorFactory;
private final SQLiteWrapper mSqliteWrapper;
private final WhereFactory mWhereFactory;
// TODO: rename to CacheSqlReader / CacheSqlWriter
CacheReader(DatabaseDI.SQLiteWrapper sqliteWrapper, WhereFactory whereFactory,
DatabaseDI.CacheReaderCursorFactory cacheReaderCursorFactory) {
mSqliteWrapper = sqliteWrapper;
mWhereFactory = whereFactory;
mCacheReaderCursorFactory = cacheReaderCursorFactory;
}
public int getTotalCount() {
return mSqliteWrapper.countResults(Database.TBL_CACHES, null);
}
public CacheReaderCursor open(Location location) {
String where = mWhereFactory.getWhere(location);
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, Database.READER_COLUMNS, where,
null, null, null, SQL_QUERY_LIMIT);
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return mCacheReaderCursorFactory.create(cursor);
}
}
| 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.io;
import com.google.code.geobeagle.data.Geocache.Source;
// TODO: Rename to CacheTagSqlWriter.
/**
* @author sng
*/
public class CacheTagWriter {
public final CacheWriter mCacheWriter;
private boolean mFound;
private String mGpxName;
private CharSequence mId;
private double mLatitude;
private double mLongitude;
private CharSequence mName;
private String mSqlDate;
public CacheTagWriter(CacheWriter cacheWriter) {
mCacheWriter = cacheWriter;
}
public void cacheName(String name) {
mName = name;
}
public void clear() { // TODO: ensure source is not reset
mId = mName = null;
mLatitude = mLongitude = 0;
mFound = false;
}
public void end() {
mCacheWriter.clearEarlierLoads();
}
public void gpxName(String gpxName) {
mGpxName = gpxName;
}
/**
* @param gpxTime
* @return true if we should load this gpx; false if the gpx is already
* loaded.
*/
public boolean gpxTime(String gpxTime) {
mSqlDate = isoTimeToSql(gpxTime);
if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) {
return false;
}
mCacheWriter.clearCaches(mGpxName);
return true;
}
public void id(CharSequence id) {
mId = id;
}
public String isoTimeToSql(String gpxTime) {
return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19);
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = Double.parseDouble(latitude);
mLongitude = Double.parseDouble(longitude);
}
public void startWriting() {
mCacheWriter.startWriting();
}
public void stopWriting(boolean successfulGpxImport) {
mCacheWriter.stopWriting();
if (successfulGpxImport)
mCacheWriter.writeGpx(mGpxName, mSqlDate);
}
public void symbol(String symbol) {
mFound = symbol.equals("Geocache Found");
}
public void write() {
if (!mFound)
mCacheWriter.insertAndUpdateCache(mId, mName, mLatitude, mLongitude, Source.GPX,
mGpxName);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.