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.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
import com.google.code.geobeagle.Geocache;
class CacheItem extends OverlayItem {
private final Geocache mGeocache;
CacheItem(GeoPoint geoPoint, String id, Geocache geocache) {
super(geoPoint, id, "");
mGeocache = geocache;
}
Geocache getGeocache() {
return mGeocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.MapView;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
public class GeoMapView extends MapView {
private OverlayManager mOverlayManager;
public GeoMapView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
Log.d("GeoBeagle", "~~~~~~~~~~onLayout " + changed + ", " + left + ", " + top + ", "
+ right + ", " + bottom);
if (mOverlayManager != null) {
mOverlayManager.selectOverlay();
}
}
public void setScrollListener(OverlayManager overlayManager) {
mOverlayManager = overlayManager;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import com.google.code.geobeagle.activity.map.QueryManager.CachedNeedsLoading;
import com.google.code.geobeagle.activity.map.QueryManager.PeggedLoader;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.Toaster;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class GeoMapActivity extends MapActivity {
private static class NullOverlay extends Overlay {
}
private static final int DEFAULT_ZOOM_LEVEL = 14;
private static boolean fZoomed = false;
private DbFrontend mDbFrontend;
private GeoMapActivityDelegate mGeoMapActivityDelegate;
private GeoMapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
@Override
protected boolean isRouteDisplayed() {
// This application doesn't use routes
return false;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
// Set member variables first, in case anyone after this needs them.
mMapView = (GeoMapView)findViewById(R.id.mapview);
mDbFrontend = new DbFrontend(this);
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMapView.setBuiltInZoomControls(true);
mMapView.setSatellite(false);
final Resources resources = getResources();
final Drawable defaultMarker = resources.getDrawable(R.drawable.map_pin2_others);
final CacheDrawables cacheDrawables = new CacheDrawables(resources);
final CacheItemFactory cacheItemFactory = new CacheItemFactory(cacheDrawables);
final List<Overlay> mapOverlays = mMapView.getOverlays();
final MenuActions menuActions = new MenuActions(getResources());
menuActions.add(new GeoMapActivityDelegate.MenuActionToggleSatellite(mMapView));
menuActions.add(new MenuActionCacheList(this));
final Intent intent = getIntent();
final MapController mapController = mMapView.getController();
final double latitude = intent.getFloatExtra("latitude", 0);
final double longitude = intent.getFloatExtra("longitude", 0);
final Overlay nullOverlay = new GeoMapActivity.NullOverlay();
final GeoPoint nullGeoPoint = new GeoPoint(0, 0);
mapOverlays.add(nullOverlay);
mapOverlays.add(mMyLocationOverlay);
final ArrayList<Geocache> nullList = new ArrayList<Geocache>();
final List<DensityPatch> densityPatches = new ArrayList<DensityPatch>();
final Toaster toaster = new Toaster(this, R.string.too_many_caches, Toast.LENGTH_SHORT);
final PeggedLoader peggedLoader = new QueryManager.PeggedLoader(mDbFrontend, nullList,
toaster);
final int[] initialLatLonMinMax = {
0, 0, 0, 0
};
CachedNeedsLoading cachedNeedsLoading = new CachedNeedsLoading(nullGeoPoint, nullGeoPoint);
final QueryManager queryManager = new QueryManager(peggedLoader, cachedNeedsLoading,
initialLatLonMinMax);
final DensityOverlayDelegate densityOverlayDelegate = DensityOverlay.createDelegate(
densityPatches, nullGeoPoint, queryManager);
final DensityOverlay densityOverlay = new DensityOverlay(densityOverlayDelegate);
final ArrayList<Geocache> geocacheList = new ArrayList<Geocache>();
final CachePinsOverlay cachePinsOverlay = new CachePinsOverlay(cacheItemFactory, this,
defaultMarker, geocacheList);
final CachePinsOverlayFactory cachePinsOverlayFactory = new CachePinsOverlayFactory(
mMapView, this, defaultMarker, cacheItemFactory, cachePinsOverlay, queryManager);
mGeoMapActivityDelegate = new GeoMapActivityDelegate(mMapView, menuActions);
final GeoPoint center = new GeoPoint((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mapController.setCenter(center);
final OverlayManager overlayManager = new OverlayManager(mMapView, mapOverlays,
densityOverlay, cachePinsOverlayFactory, false);
mMapView.setScrollListener(overlayManager);
if (!fZoomed) {
mapController.setZoom(DEFAULT_ZOOM_LEVEL);
fZoomed = true;
}
overlayManager.selectOverlay();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mGeoMapActivityDelegate.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
return mGeoMapActivityDelegate.onMenuOpened(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mGeoMapActivityDelegate.onOptionsItemSelected(item);
}
@Override
public void onPause() {
mMyLocationOverlay.disableMyLocation();
mMyLocationOverlay.disableCompass();
mDbFrontend.closeDatabase();
super.onPause();
}
@Override
public void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.enableCompass();
mDbFrontend.openDatabase();
}
}
| 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;
public enum ActivityType {
// These constants are persisted to the database. They are also used as
// indices in ActivityRestorer.
CACHE_LIST(1), NONE(0), SEARCH_ONLINE(2), VIEW_CACHE(3);
private final int mIx;
ActivityType(int i) {
mIx = i;
}
int toInt() {
return mIx;
}
}
| 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 android.content.Context;
public class ActivityDI {
public static class ActivityTypeFactory {
private final ActivityType mActivityTypes[] = new ActivityType[ActivityType.values().length];
public ActivityTypeFactory() {
for (ActivityType activityType : ActivityType.values())
mActivityTypes[activityType.toInt()] = activityType;
}
public ActivityType fromInt(int i) {
return mActivityTypes[i];
}
}
public static ActivitySaver createActivitySaver(Context context) {
return new ActivitySaver(context.getSharedPreferences("GeoBeagle", Context.MODE_PRIVATE)
.edit());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.app.AlertDialog;
import android.view.LayoutInflater;
public class FieldNoteSenderDI {
public static FieldNoteSender build(GeoBeagle parent, LayoutInflater layoutInflater) {
final AlertDialog.Builder builder = new AlertDialog.Builder(parent);
final FieldNoteSender.DialogHelper dialogHelper = new FieldNoteSender.DialogHelper();
return new FieldNoteSender(layoutInflater, builder, dialogHelper);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckButtons;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckDetailsButton;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler.CheckWebPageButton;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader.DetailsOpener;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
public class Misc {
public static CacheDetailsOnClickListener createCacheDetailsOnClickListener(
GeoBeagle geoBeagle, Builder alertDialogBuilder, LayoutInflater layoutInflater) {
final DetailsOpener detailsOpener = new DetailsOpener(geoBeagle);
final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader(detailsOpener);
return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, layoutInflater,
cacheDetailsLoader);
}
public static WebPageAndDetailsButtonEnabler create(GeoBeagle geoBeagle, View webPageButton,
View detailsButton) {
final CheckWebPageButton checkWebPageButton = new CheckWebPageButton(webPageButton);
final CheckDetailsButton checkDetailsButton = new CheckDetailsButton(detailsButton);
final CheckButtons checkButtons = new CheckButtons(new CheckButton[] {
checkWebPageButton, checkDetailsButton
});
return new WebPageAndDetailsButtonEnabler(geoBeagle, checkButtons);
}
}
| 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.GeocacheFactory;
import com.google.code.geobeagle.activity.main.view.EditCacheActivityDelegate;
import com.google.code.geobeagle.activity.main.view.EditCacheActivityDelegate.CancelButtonOnClickListener;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Activity;
import android.os.Bundle;
public class EditCacheActivity extends Activity {
private EditCacheActivityDelegate mEditCacheActivityDelegate;
private DbFrontend mDbFrontend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final CancelButtonOnClickListener cancelButtonOnClickListener = new CancelButtonOnClickListener(
this);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
mDbFrontend = new DbFrontend(this);
LocationSaver locationSaver = new LocationSaver(mDbFrontend);
mEditCacheActivityDelegate = new EditCacheActivityDelegate(this,
cancelButtonOnClickListener, geocacheFactory, locationSaver);
mEditCacheActivityDelegate.onCreate();
}
@Override
protected void onPause() {
super.onPause();
mDbFrontend.closeDatabase();
}
@Override
protected void onResume() {
super.onResume();
mEditCacheActivityDelegate.onResume();
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
public class DistanceFormatterManagerDi {
public static DistanceFormatterManager create(Context context) {
final SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
final DistanceFormatterMetric distanceFormatterMetric = new DistanceFormatterMetric();
final DistanceFormatterImperial distanceFormatterImperial = new DistanceFormatterImperial();
return new DistanceFormatterManager(sharedPreferences, distanceFormatterImperial,
distanceFormatterMetric);
}
}
| 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 android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
public class CacheListActivity extends ListActivity {
private CacheListDelegate mCacheListDelegate;
// This is the ctor that Android will use.
public CacheListActivity() {
}
// This is the ctor for testing.
public CacheListActivity(CacheListDelegate cacheListDelegate) {
mCacheListDelegate = cacheListDelegate;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return mCacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "CacheListActivity onCreate");
mCacheListDelegate = CacheListDelegateDI.create(this, getLayoutInflater());
mCacheListDelegate.onCreate();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
return mCacheListDelegate.onCreateOptionsMenu(menu);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
mCacheListDelegate.onListItemClick(l, v, position, id);
}
/*
* (non-Javadoc)
* @see android.app.Activity#onMenuOpened(int, android.view.Menu)
*/
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
super.onMenuOpened(featureId, menu);
return mCacheListDelegate.onMenuOpened(featureId, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mCacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
@Override
protected void onPause() {
Log.d("GeoBeagle", "CacheListActivity onPause");
super.onPause();
mCacheListDelegate.onPause();
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "CacheListActivity onResume");
mCacheListDelegate.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.activity.cachelist;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
public class CompassListenerFactory {
private final LocationControlBuffered mLocationControlBuffered;
public CompassListenerFactory(LocationControlBuffered locationControlBuffered) {
mLocationControlBuffered = locationControlBuffered;
}
public CompassListener create(CacheListRefresh cacheListRefresh) {
return new CompassListener(cacheListRefresh, mLocationControlBuffered, 720);
}
}
| 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.activity.cachelist.presenter.CacheListRefresh.UpdateFlag;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
public class CacheListView extends ListView {
public static class ScrollListener implements OnScrollListener {
private final UpdateFlag mUpdateFlag;
public ScrollListener(UpdateFlag updateFlag) {
mUpdateFlag = updateFlag;
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mUpdateFlag.setUpdatesEnabled(scrollState == SCROLL_STATE_IDLE);
}
}
// If these constructors aren't here, Android throws
// java.lang.NoSuchMethodException: CacheListView(Context,AttributeSet)
public CacheListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CacheListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CacheListView(Context context) {
super(context);
}
/*
* (non-Javadoc)
* @see android.widget.ListView#setAdapter(android.widget.ListAdapter)
*/
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
}
| 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.activity.cachelist.presenter.ActionAndTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader;
import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
public class ActionManagerFactory {
private final ActionAndTolerance[] mActionAndTolerances;
private final ToleranceStrategy mSqlCacheLoaderTolerance;
public ActionManagerFactory(ActionAndTolerance[] actionAndTolerances,
ToleranceStrategy sqlCacheLoaderTolerance) {
mActionAndTolerances = actionAndTolerances;
mSqlCacheLoaderTolerance = sqlCacheLoaderTolerance;
}
public ActionManager create(SqlCacheLoader sqlCacheLoader) {
mActionAndTolerances[0] = new ActionAndTolerance(
sqlCacheLoader, mSqlCacheLoaderTolerance);
return new ActionManager(mActionAndTolerances);
}
}
| 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.CacheTypeFactory;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.LocationControlBuffered.GpsDisabledLocation;
import com.google.code.geobeagle.actions.MenuActionSearchOnline;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegate.ImportIntentManager;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextAction;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionEdit;
import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionView;
import com.google.code.geobeagle.activity.cachelist.actions.menu.Abortable;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionMyLocation;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx;
import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionToggleFilter;
import com.google.code.geobeagle.activity.cachelist.model.CacheListData;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.presenter.ActionAndTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.AdapterCachesSorter;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListAdapter;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.activity.cachelist.presenter.ListTitleFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationAndAzimuthTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.SensorManagerWrapper;
import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader;
import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.FilterNearestCaches;
import com.google.code.geobeagle.database.LocationSaver;
import com.google.code.geobeagle.database.WhereFactoryAllCaches;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches;
import com.google.code.geobeagle.database.DatabaseDI.SearchFactory;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.WhereStringFactory;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget.InflatedGpsStatusWidget;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.hardware.SensorManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout.LayoutParams;
import java.util.ArrayList;
import java.util.Calendar;
public class CacheListDelegateDI {
public static class Timing {
private long mStartTime;
public void lap(CharSequence msg) {
long finishTime = Calendar.getInstance().getTimeInMillis();
Log.d("GeoBeagle", "****** " + msg + ": " + (finishTime - mStartTime));
mStartTime = finishTime;
}
public void start() {
mStartTime = Calendar.getInstance().getTimeInMillis();
}
public long getTime() {
return Calendar.getInstance().getTimeInMillis();
}
}
public static CacheListDelegate create(ListActivity listActivity, LayoutInflater layoutInflater) {
final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
final ErrorDisplayer errorDisplayer = new ErrorDisplayer(listActivity, mOnClickListener);
final LocationManager locationManager = (LocationManager)listActivity
.getSystemService(Context.LOCATION_SERVICE);
ArrayList<LocationListener> locationListeners = new ArrayList<LocationListener>(3);
final CombinedLocationManager combinedLocationManager = new CombinedLocationManager(
locationManager, locationListeners);
final LocationControlBuffered locationControlBuffered = LocationControlDi
.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromMyLocationFactory geocacheFromMyLocationFactory = new GeocacheFromMyLocationFactory(
geocacheFactory, locationControlBuffered);
final BearingFormatter relativeBearingFormatter = new RelativeBearingFormatter();
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(listActivity);
final ArrayList<GeocacheVector> geocacheVectorsList = new ArrayList<GeocacheVector>(10);
final GeocacheVectors geocacheVectors = new GeocacheVectors(geocacheVectorsList);
final CacheListData cacheListData = new CacheListData(geocacheVectors);
final XmlPullParserWrapper xmlPullParserWrapper = new XmlPullParserWrapper();
final GeocacheSummaryRowInflater geocacheSummaryRowInflater = new GeocacheSummaryRowInflater(
distanceFormatterManager.getFormatter(), geocacheVectors, layoutInflater,
relativeBearingFormatter);
final UpdateFlag updateFlag = new UpdateFlag();
final GeocacheListAdapter geocacheListAdapter = new GeocacheListAdapter(geocacheVectors,
geocacheSummaryRowInflater);
final InflatedGpsStatusWidget inflatedGpsStatusWidget = new InflatedGpsStatusWidget(
listActivity);
final GpsStatusWidget gpsStatusWidget = new GpsStatusWidget(listActivity);
gpsStatusWidget.addView(inflatedGpsStatusWidget, LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(listActivity,
gpsStatusWidget, locationControlBuffered, combinedLocationManager,
distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
inflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
final CombinedLocationListener combinedLocationListener = new CombinedLocationListener(
locationControlBuffered, gpsStatusWidgetDelegate);
final UpdateGpsWidgetRunnable updateGpsWidgetRunnable = gpsWidgetAndUpdater
.getUpdateGpsWidgetRunnable();
updateGpsWidgetRunnable.run();
final WhereFactoryAllCaches whereFactoryAllCaches = new WhereFactoryAllCaches();
final SearchFactory searchFactory = new SearchFactory();
final WhereStringFactory whereStringFactory = new WhereStringFactory();
final WhereFactoryNearestCaches whereFactoryNearestCaches = new WhereFactoryNearestCaches(
searchFactory, whereStringFactory);
final FilterNearestCaches filterNearestCaches = new FilterNearestCaches(
whereFactoryAllCaches, whereFactoryNearestCaches);
final ListTitleFormatter listTitleFormatter = new ListTitleFormatter();
final CacheListDelegateDI.Timing timing = new CacheListDelegateDI.Timing();
final AdapterCachesSorter adapterCachesSorter = new AdapterCachesSorter(cacheListData,
timing, locationControlBuffered);
final GpsDisabledLocation gpsDisabledLocation = new GpsDisabledLocation();
final DistanceUpdater distanceUpdater = new DistanceUpdater(geocacheListAdapter);
final ToleranceStrategy sqlCacheLoaderTolerance = new LocationTolerance(500,
gpsDisabledLocation, 1000);
final ToleranceStrategy adapterCachesSorterTolerance = new LocationTolerance(6,
gpsDisabledLocation, 1000);
final LocationTolerance distanceUpdaterLocationTolerance = new LocationTolerance(1,
gpsDisabledLocation, 1000);
final ToleranceStrategy distanceUpdaterTolerance = new LocationAndAzimuthTolerance(
distanceUpdaterLocationTolerance, 720);
final ActionAndTolerance[] actionAndTolerances = new ActionAndTolerance[] {
null, new ActionAndTolerance(adapterCachesSorter, adapterCachesSorterTolerance),
new ActionAndTolerance(distanceUpdater, distanceUpdaterTolerance)
};
final ActionManagerFactory actionManagerFactory = new ActionManagerFactory(
actionAndTolerances, sqlCacheLoaderTolerance);
final DbFrontend dbFrontend = new DbFrontend(listActivity);
final TitleUpdater titleUpdater = new TitleUpdater(listActivity, filterNearestCaches,
listTitleFormatter, timing);
final SqlCacheLoader sqlCacheLoader = new SqlCacheLoader(dbFrontend, filterNearestCaches,
cacheListData, locationControlBuffered, titleUpdater, timing);
final ActionManager actionManager = actionManagerFactory.create(sqlCacheLoader);
final CacheListRefresh cacheListRefresh = new CacheListRefresh(actionManager, timing,
locationControlBuffered, updateFlag);
final SensorManager sensorManager = (SensorManager)listActivity
.getSystemService(Context.SENSOR_SERVICE);
final CompassListenerFactory compassListenerFactory = new CompassListenerFactory(
locationControlBuffered);
distanceFormatterManager.addHasDistanceFormatter(geocacheSummaryRowInflater);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final CacheListView.ScrollListener scrollListener = new CacheListView.ScrollListener(
updateFlag);
final SensorManagerWrapper sensorManagerWrapper = new SensorManagerWrapper(sensorManager);
final GeocacheListPresenter geocacheListPresenter = new GeocacheListPresenter(
combinedLocationListener, combinedLocationManager, compassListenerFactory,
distanceFormatterManager, geocacheListAdapter, geocacheSummaryRowInflater,
geocacheVectors, gpsStatusWidget, listActivity, locationControlBuffered,
sensorManagerWrapper, updateGpsWidgetRunnable, scrollListener);
final CacheTypeFactory cacheTypeFactory = new CacheTypeFactory();
final Aborter aborter = new Aborter();
final MessageHandler messageHandler = MessageHandler.create(listActivity);
final CachePersisterFacadeFactory cachePersisterFacadeFactory = new CachePersisterFacadeFactory(
messageHandler, cacheTypeFactory);
final GpxImporterFactory gpxImporterFactory = new GpxImporterFactory(aborter,
cachePersisterFacadeFactory, errorDisplayer, geocacheListPresenter, listActivity,
messageHandler, xmlPullParserWrapper);
final Abortable nullAbortable = new Abortable() {
public void abort() {
}
};
final MenuActionSyncGpx menuActionSyncGpx = new MenuActionSyncGpx(nullAbortable,
cacheListRefresh, gpxImporterFactory, dbFrontend);
final MenuActions menuActions = new MenuActions(listActivity.getResources());
menuActions.add(menuActionSyncGpx);
menuActions.add(new MenuActionToggleFilter(filterNearestCaches, cacheListRefresh));
menuActions.add(new MenuActionMyLocation(cacheListRefresh, errorDisplayer,
geocacheFromMyLocationFactory, new LocationSaver(dbFrontend)));
menuActions.add(new MenuActionSearchOnline(listActivity));
// menuActions.add(new MenuActionChooseFilter(listActivity));
final Intent geoBeagleMainIntent = new Intent(listActivity, GeoBeagle.class);
final ContextActionView contextActionView = new ContextActionView(geocacheVectors,
listActivity, geoBeagleMainIntent);
final ContextActionEdit contextActionEdit = new ContextActionEdit(geocacheVectors,
listActivity);
final ContextActionDelete contextActionDelete = new ContextActionDelete(
geocacheListAdapter, geocacheVectors, titleUpdater, dbFrontend);
final ContextAction[] contextActions = new ContextAction[] {
contextActionDelete, contextActionView, contextActionEdit
};
final GeocacheListController geocacheListController = new GeocacheListController(
cacheListRefresh, contextActions, filterNearestCaches, menuActionSyncGpx,
menuActions);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(listActivity);
final ImportIntentManager importIntentManager = new ImportIntentManager(listActivity);
return new CacheListDelegate(importIntentManager, activitySaver, cacheListRefresh,
geocacheListController, geocacheListPresenter, dbFrontend);
}
}
| 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.ErrorDisplayer;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.GpxImporter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.app.ListActivity;
public class GpxImporterFactory {
private final Aborter mAborter;
private final CachePersisterFacadeFactory mCachePersisterFacadeFactory;
private final ErrorDisplayer mErrorDisplayer;
private final GeocacheListPresenter mGeocacheListPresenter;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
public GpxImporterFactory(Aborter aborter,
CachePersisterFacadeFactory cachePersisterFacadeFactory, ErrorDisplayer errorDisplayer,
GeocacheListPresenter geocacheListPresenter, ListActivity listActivity,
MessageHandler messageHandler, XmlPullParserWrapper xmlPullParserWrapper) {
mAborter = aborter;
mCachePersisterFacadeFactory = cachePersisterFacadeFactory;
mErrorDisplayer = errorDisplayer;
mGeocacheListPresenter = geocacheListPresenter;
mListActivity = listActivity;
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
}
public GpxImporter create(CacheWriter cacheWriter) {
return GpxImporterDI.create(mListActivity, mXmlPullParserWrapper, mErrorDisplayer,
mGeocacheListPresenter, mAborter, mMessageHandler, mCachePersisterFacadeFactory,
cacheWriter);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivityRestorer;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityDI.ActivityTypeFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManagerDi;
import com.google.code.geobeagle.activity.main.GeocacheFromPreferencesFactory;
import com.google.code.geobeagle.activity.searchonline.JsInterface.JsInterfaceHelper;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate;
import com.google.code.geobeagle.gpsstatuswidget.GpsWidgetAndUpdater;
import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidget.InflatedGpsStatusWidget;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.hardware.SensorManager;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
import java.util.ArrayList;
public class SearchOnlineActivity extends Activity {
private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "SearchOnlineActivity onCreate");
setContentView(R.layout.search);
final LocationManager locationManager = (LocationManager)this
.getSystemService(Context.LOCATION_SERVICE);
final LocationControlBuffered mLocationControlBuffered = LocationControlDi
.create(locationManager);
final ArrayList<LocationListener> locationListeners = new ArrayList<LocationListener>(3);
final CombinedLocationManager mCombinedLocationManager = new CombinedLocationManager(
locationManager, locationListeners);
final InflatedGpsStatusWidget mGpsStatusWidget = (InflatedGpsStatusWidget)this
.findViewById(R.id.gps_widget_view);
final DistanceFormatterManager distanceFormatterManager = DistanceFormatterManagerDi
.create(this);
final GpsWidgetAndUpdater gpsWidgetAndUpdater = new GpsWidgetAndUpdater(this,
mGpsStatusWidget, mLocationControlBuffered, mCombinedLocationManager,
distanceFormatterManager.getFormatter());
final GpsStatusWidgetDelegate gpsStatusWidgetDelegate = gpsWidgetAndUpdater
.getGpsStatusWidgetDelegate();
gpsWidgetAndUpdater.getUpdateGpsWidgetRunnable().run();
mGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate);
mGpsStatusWidget.setBackgroundColor(Color.BLACK);
final Refresher refresher = new NullRefresher();
final CompassListener mCompassListener = new CompassListener(refresher,
mLocationControlBuffered, 720);
final SensorManager mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
final CombinedLocationListener mCombinedLocationListener = new CombinedLocationListener(
mLocationControlBuffered, gpsStatusWidgetDelegate);
distanceFormatterManager.addHasDistanceFormatter(gpsStatusWidgetDelegate);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final GeocacheFromPreferencesFactory geocacheFromPreferencesFactory = new GeocacheFromPreferencesFactory(
geocacheFactory);
final ActivityTypeFactory activityTypeFactory = new ActivityTypeFactory();
final ActivityRestorer activityRestorer = new ActivityRestorer(this,
geocacheFromPreferencesFactory, activityTypeFactory, getSharedPreferences(
"GeoBeagle", Context.MODE_PRIVATE));
mSearchOnlineActivityDelegate = new SearchOnlineActivityDelegate(
((WebView)findViewById(R.id.help_contents)), mSensorManager, mCompassListener,
mCombinedLocationManager, mCombinedLocationListener, mLocationControlBuffered,
distanceFormatterManager, activitySaver);
final JsInterfaceHelper jsInterfaceHelper = new JsInterfaceHelper(this);
final JsInterface jsInterface = new JsInterface(mLocationControlBuffered, jsInterfaceHelper);
mSearchOnlineActivityDelegate.configureWebView(jsInterface);
activityRestorer.restore(getIntent().getFlags());
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_online_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
startActivity(new Intent(this, CacheListActivity.class));
return true;
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "SearchOnlineActivity onResume");
mSearchOnlineActivityDelegate.onResume();
}
@Override
protected void onPause() {
super.onPause();
Log.d("GeoBeagle", "SearchOnlineActivity onPause");
mSearchOnlineActivityDelegate.onPause();
}
}
| 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.preferences;
import com.google.code.geobeagle.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class EditPreferences extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.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.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream;
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.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.xmlimport.CachePersisterFacade;
import com.google.code.geobeagle.xmlimport.GpxLoader;
import com.google.code.geobeagle.xmlimport.GpxToCache;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import android.os.PowerManager.WakeLock;
public class GpxLoaderDI {
public static GpxLoader create(CachePersisterFacade cachePersisterFacade,
XmlPullParserWrapper xmlPullParserFactory, Aborter aborter, ErrorDisplayer errorDisplayer, WakeLock wakeLock) {
final GpxToCache gpxToCache = new GpxToCache(xmlPullParserFactory, aborter);
return new GpxLoader(cachePersisterFacade, errorDisplayer, gpxToCache, 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.xmlimport;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.cachedetails.CacheDetailsWriter;
import com.google.code.geobeagle.cachedetails.HtmlWriter;
import com.google.code.geobeagle.cachedetails.WriterWrapper;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler;
import android.os.PowerManager.WakeLock;
import java.io.File;
public class CachePersisterFacadeDI {
//TODO: Remove class CachePersisterFacadeFactory
public static class CachePersisterFacadeFactory {
private final CacheDetailsWriter mCacheDetailsWriter;
private final CacheTypeFactory mCacheTypeFactory;
private final FileFactory mFileFactory;
private final HtmlWriter mHtmlWriter;
private final MessageHandler mMessageHandler;
private final WriterWrapper mWriterWrapper;
public CachePersisterFacadeFactory(MessageHandler messageHandler,
CacheTypeFactory cacheTypeFactory) {
mMessageHandler = messageHandler;
mFileFactory = new FileFactory();
mWriterWrapper = new WriterWrapper();
mHtmlWriter = new HtmlWriter(mWriterWrapper);
mCacheDetailsWriter = new CacheDetailsWriter(mHtmlWriter);
mCacheTypeFactory = cacheTypeFactory;
}
public CachePersisterFacade create(CacheWriter cacheWriter, WakeLock wakeLock) {
final CacheTagSqlWriter cacheTagSqlWriter = new CacheTagSqlWriter(cacheWriter, mCacheTypeFactory);
return new CachePersisterFacade(cacheTagSqlWriter, mFileFactory, mCacheDetailsWriter,
mMessageHandler, wakeLock);
}
}
public static class FileFactory {
public File createFile(String path) {
return new File(path);
}
}
}
| 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.xmlimport;
import com.google.code.geobeagle.xmlimport.EventHandler;
import com.google.code.geobeagle.xmlimport.EventHelper;
import com.google.code.geobeagle.xmlimport.EventHelper.XmlPathBuilder;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
public class EventHelperDI {
public static class EventHelperFactory {
private final XmlPullParserWrapper mXmlPullParser;
public EventHelperFactory(XmlPullParserWrapper xmlPullParser) {
mXmlPullParser = xmlPullParser;
}
public EventHelper create(EventHandler eventHandler) {
final XmlPathBuilder xmlPathBuilder = new XmlPathBuilder();
return new EventHelper(xmlPathBuilder, eventHandler, mXmlPullParser);
}
}
}
| 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.xmlimport;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
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 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.xmlimport;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.database.CacheWriter;
import com.google.code.geobeagle.xmlimport.CachePersisterFacadeDI.CachePersisterFacadeFactory;
import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory;
import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter;
import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper;
import com.google.code.geobeagle.xmlimport.ImportThreadDelegate.ImportThreadHelper;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.xmlimport.gpx.GpxFileIterAndZipFileIterFactory;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxAndZipFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter;
import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
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,
EventHandlers eventHandlers, XmlPullParserWrapper xmlPullParserWrapper,
ErrorDisplayer errorDisplayer, Aborter aborter) {
final GpxFilenameFilter gpxFilenameFilter = new GpxFilenameFilter();
final FilenameFilter filenameFilter = new GpxAndZipFilenameFilter(gpxFilenameFilter);
final ZipInputFileTester zipInputFileTester = new ZipInputFileTester(gpxFilenameFilter);
final GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory = new GpxFileIterAndZipFileIterFactory(
zipInputFileTester, aborter);
final GpxAndZipFiles gpxAndZipFiles = new GpxAndZipFiles(filenameFilter,
gpxFileIterAndZipFileIterFactory);
final EventHelperFactory eventHelperFactory = new EventHelperFactory(
xmlPullParserWrapper);
final ImportThreadHelper importThreadHelper = new ImportThreadHelper(gpxLoader,
messageHandler, eventHelperFactory, eventHandlers, 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 final Aborter mAborter;
private ImportThread mImportThread;
private final MessageHandler mMessageHandler;
private final XmlPullParserWrapper mXmlPullParserWrapper;
public ImportThreadWrapper(MessageHandler messageHandler,
XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) {
mMessageHandler = messageHandler;
mXmlPullParserWrapper = xmlPullParserWrapper;
mAborter = aborter;
}
public boolean isAlive() {
if (mImportThread != null)
return mImportThread.isAlive();
return false;
}
public void join() {
if (mImportThread != null)
try {
mImportThread.join();
} catch (InterruptedException e) {
// Ignore; we are aborting anyway.
}
}
public void open(CacheListRefresh cacheListRefresh, GpxLoader gpxLoader,
EventHandlers eventHandlers, ErrorDisplayer mErrorDisplayer) {
mMessageHandler.start(cacheListRefresh);
mImportThread = ImportThread.create(mMessageHandler, gpxLoader, eventHandlers,
mXmlPullParserWrapper, mErrorDisplayer, mAborter);
}
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 {
public static final String GEOBEAGLE = "GeoBeagle";
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 boolean mLoadAborted;
private CacheListRefresh mMenuActionRefresh;
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) {
// Log.d(GEOBEAGLE, "received msg: " + msg.what);
switch (msg.what) {
case MessageHandler.MSG_PROGRESS:
mProgressDialogWrapper.setMessage(mStatus);
break;
case MessageHandler.MSG_DONE:
if (!mLoadAborted) {
mProgressDialogWrapper.dismiss();
mMenuActionRefresh.forceRefresh();
}
break;
default:
break;
}
}
public void loadComplete() {
sendEmptyMessage(MessageHandler.MSG_DONE);
}
public void start(CacheListRefresh cacheListRefresh) {
mCacheCount = 0;
mLoadAborted = false;
mMenuActionRefresh = cacheListRefresh;
// TODO: move text into resource.
mProgressDialogWrapper.show("Syncing caches", "Please wait...");
}
public void updateName(String name) {
mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name;
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
public void updateSource(String text) {
mSource = text;
mStatus = "Opening: " + mSource + "...";
sendEmptyMessage(MessageHandler.MSG_PROGRESS);
}
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 class Toaster {
private final Context mContext;
private final int mResId;
private final int mDuration;
public Toaster(Context context, int resId, int duration) {
mContext = context;
mResId = resId;
mDuration = duration;
}
public void showToast() {
Toast.makeText(mContext, mResId, mDuration).show();
}
}
public static GpxImporter create(ListActivity listActivity,
XmlPullParserWrapper xmlPullParserWrapper, ErrorDisplayer errorDisplayer,
GeocacheListPresenter geocacheListPresenter, Aborter aborter,
MessageHandler messageHandler, CachePersisterFacadeFactory cachePersisterFacadeFactory,
CacheWriter cacheWriter) {
final PowerManager powerManager = (PowerManager)listActivity
.getSystemService(Context.POWER_SERVICE);
final WakeLock wakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
"Importing");
final CachePersisterFacade cachePersisterFacade = cachePersisterFacadeFactory.create(
cacheWriter, wakeLock);
final GpxLoader gpxLoader = GpxLoaderDI.create(cachePersisterFacade, xmlPullParserWrapper,
aborter, errorDisplayer, wakeLock);
final ToastFactory toastFactory = new ToastFactory();
final ImportThreadWrapper importThreadWrapper = new ImportThreadWrapper(messageHandler,
xmlPullParserWrapper, aborter);
final EventHandlerGpx eventHandlerGpx = new EventHandlerGpx(cachePersisterFacade);
final EventHandlerLoc eventHandlerLoc = new EventHandlerLoc(cachePersisterFacade);
final EventHandlers eventHandlers = new EventHandlers();
eventHandlers.add(".gpx", eventHandlerGpx);
eventHandlers.add(".loc", eventHandlerLoc);
return new GpxImporter(geocacheListPresenter, gpxLoader, listActivity, importThreadWrapper,
messageHandler, toastFactory, eventHandlers, 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;
public enum CacheType {
NULL(0, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "null"),
MULTI(2, R.drawable.cache_multi, R.drawable.cache_multi_big,
R.drawable.map_pin2_multi, "Multi"),
TRADITIONAL(1, R.drawable.cache_tradi, R.drawable.cache_tradi_big,
R.drawable.map_pin2_tradi, "Traditional"),
UNKNOWN(3, R.drawable.cache_mystery, R.drawable.cache_mystery_big,
R.drawable.map_pin2_mystery, "Unknown Cache"),
MY_LOCATION(4, R.drawable.blue_dot, R.drawable.blue_dot,
R.drawable.map_pin2_empty, "My location"),
//Caches without unique icons
EARTHCACHE(5, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Earthcache"),
VIRTUAL(6, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Virtual Cache"),
LETTERBOX_HYBRID(7, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Letterbox Hybrid"),
EVENT(8, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Event Cache"),
WEBCAM(9, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Webcam Cache"),
CITO(10, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Cache In Trash Out Event"),
LOCATIONLESS(11, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Locationless (Reverse) Cache"),
APE(12, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Project APE Cache"),
MEGA(13, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Mega-Event Cache"),
//Waypoint types
WAYPOINT(20, R.drawable.cache_default, R.drawable.cache_default_big,
R.drawable.map_pin2_default, "Waypoint"), //Not actually seen in GPX...
WAYPOINT_PARKING(21, R.drawable.cache_waypoint_p, R.drawable.cache_waypoint_p_big,
R.drawable.map_pin2_wp_p, "Waypoint|Parking Area"),
WAYPOINT_REFERENCE(22, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "Waypoint|Reference Point"),
WAYPOINT_STAGES(23, R.drawable.cache_waypoint_s, R.drawable.cache_waypoint_s_big,
R.drawable.map_pin2_wp_s, "Waypoint|Stages of a Multicache"),
WAYPOINT_TRAILHEAD(24, R.drawable.cache_waypoint_t, R.drawable.cache_waypoint_t_big,
R.drawable.map_pin2_wp_t, "Waypoint|Trailhead"),
WAYPOINT_FINAL(25, R.drawable.cache_waypoint_r, R.drawable.cache_waypoint_r_big,
R.drawable.map_pin2_wp_r, "Waypoint|Final Location"); //TODO: Doesn't have unique graphics yet
private final int mIconId;
private final int mIconIdBig;
private final int mIx;
private final int mIconIdMap;
private final String mTag;
CacheType(int ix, int drawableId, int drawableIdBig, int drawableIdMap,
String tag) {
mIx = ix;
mIconId = drawableId;
mIconIdBig = drawableIdBig;
mIconIdMap = drawableIdMap;
mTag = tag;
}
public int icon() {
return mIconId;
}
public int iconBig() {
return mIconIdBig;
}
public int toInt() {
return mIx;
}
public int iconMap() {
return mIconIdMap;
}
public String getTag() {
return mTag;
}
}
| Java |
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.content.Context;
import android.os.Handler;
import android.view.View;
public class GpsWidgetAndUpdater {
private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
private final UpdateGpsWidgetRunnable mUpdateGpsRunnable;
public GpsWidgetAndUpdater(Context context, View gpsWidgetView,
LocationControlBuffered mLocationControlBuffered,
CombinedLocationManager combinedLocationManager,
DistanceFormatter distanceFormatterMetric) {
final Time time = new Time();
final Handler handler = new Handler();
final MeterBars meterBars = GpsStatusWidget.create(context, gpsWidgetView);
final Meter meter = GpsStatusWidget.createMeterWrapper(gpsWidgetView, meterBars);
final TextLagUpdater textLagUpdater = GpsStatusWidget.createTextLagUpdater(gpsWidgetView,
combinedLocationManager, time);
mUpdateGpsRunnable = new UpdateGpsWidgetRunnable(handler, mLocationControlBuffered, meter,
textLagUpdater);
mGpsStatusWidgetDelegate = GpsStatusWidget.createGpsStatusWidgetDelegate(gpsWidgetView,
time, combinedLocationManager, meter, distanceFormatterMetric, meterBars,
textLagUpdater, context);
}
public GpsStatusWidgetDelegate getGpsStatusWidgetDelegate() {
return mGpsStatusWidgetDelegate;
}
public UpdateGpsWidgetRunnable getUpdateGpsWidgetRunnable() {
return mUpdateGpsRunnable;
}
}
| 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.gpsstatuswidget;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LagNull;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LastKnownLocationUnavailable;
import com.google.code.geobeagle.gpsstatuswidget.TextLagUpdater.LastLocationUnknown;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
/**
* @author sng Displays the GPS status (mAccuracy, availability, etc).
*/
public class GpsStatusWidget extends LinearLayout {
static GpsStatusWidgetDelegate createGpsStatusWidgetDelegate(View gpsStatusWidget, Time time,
CombinedLocationManager combinedLocationManager, Meter meter,
DistanceFormatter distanceFormatter, MeterBars meterBars,
TextLagUpdater textLagUpdater, Context parent) {
final TextView status = (TextView)gpsStatusWidget.findViewById(R.id.status);
final TextView provider = (TextView)gpsStatusWidget.findViewById(R.id.provider);
final MeterFader meterFader = new MeterFader(gpsStatusWidget, meterBars, time);
return new GpsStatusWidgetDelegate(combinedLocationManager, distanceFormatter, meter,
meterFader, provider, parent, status, textLagUpdater);
}
public static class InflatedGpsStatusWidget extends LinearLayout {
private GpsStatusWidgetDelegate mGpsStatusWidgetDelegate;
public InflatedGpsStatusWidget(Context context) {
super(context);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
public InflatedGpsStatusWidget(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.gps_widget, this, true);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
mGpsStatusWidgetDelegate.paint();
}
public void setDelegate(GpsStatusWidgetDelegate gpsStatusWidgetDelegate) {
mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate;
}
}
public GpsStatusWidget(Context context) {
super(context);
}
public static MeterBars create(Context context, View gpsWidget) {
final MeterFormatter meterFormatter = new MeterFormatter(context);
final TextView locationViewer = (TextView)gpsWidget.findViewById(R.id.location_viewer);
return new MeterBars(locationViewer, meterFormatter);
}
public static Meter createMeterWrapper(View gpsStatusWidget, MeterBars meterBars) {
final TextView accuracyView = (TextView)gpsStatusWidget.findViewById(R.id.accuracy);
return new Meter(meterBars, accuracyView);
}
public static TextLagUpdater createTextLagUpdater(View gpsStatusWidget,
CombinedLocationManager combinedLocationManager, Time time) {
final TextView lag = (TextView)gpsStatusWidget.findViewById(R.id.lag);
final LagNull lagNull = new LagNull();
final LastKnownLocationUnavailable lastKnownLocationUnavailable = new LastKnownLocationUnavailable(
lagNull);
final LastLocationUnknown lastLocationUnknown = new LastLocationUnknown(
combinedLocationManager, lastKnownLocationUnavailable);
return new TextLagUpdater(lastLocationUnknown, lag, time);
}
}
| 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.CacheTypeFactory;
import com.google.code.geobeagle.Geocache.AttributeFormatter;
import com.google.code.geobeagle.Geocache.AttributeFormatterImpl;
import com.google.code.geobeagle.Geocache.AttributeFormatterNull;
import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory;
import com.google.code.geobeagle.activity.main.GeocacheFromParcelFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
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 static enum Provider {
ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC");
private final int mIx;
private final String mPrefix;
Provider(int ix, String prefix) {
mIx = ix;
mPrefix = prefix;
}
public int toInt() {
return mIx;
}
public String getPrefix() {
return mPrefix;
}
}
public static Provider ALL_PROVIDERS[] = {
Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING
};
public static enum Source {
GPX(0), LOC(3), 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;
}
}
static class AttributeFormatterFactory {
private AttributeFormatterImpl mAttributeFormatterImpl;
private AttributeFormatterNull mAttributeFormatterNull;
public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl,
AttributeFormatterNull attributeFormatterNull) {
mAttributeFormatterImpl = attributeFormatterImpl;
mAttributeFormatterNull = attributeFormatterNull;
}
AttributeFormatter getAttributeFormatter(Source sourceType) {
if (sourceType == Source.GPX)
return mAttributeFormatterImpl;
return mAttributeFormatterNull;
}
}
private static CacheTypeFactory mCacheTypeFactory;
private static SourceFactory mSourceFactory;
private AttributeFormatterFactory mAttributeFormatterFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
mCacheTypeFactory = new CacheTypeFactory();
mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(),
new AttributeFormatterNull());
}
public CacheType cacheTypeFromInt(int cacheTypeIx) {
return mCacheTypeFactory.fromInt(cacheTypeIx);
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
if (name == null)
name = "";
final AttributeFormatter attributeFormatter = mAttributeFormatterFactory
.getAttributeFormatter(sourceType);
return new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType,
difficulty, terrain, container, attributeFormatter);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| Java |
package com.google.code.geobeagle;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
public class ErrorDisplayerDi {
static public ErrorDisplayer createErrorDisplayer(Activity activity) {
final OnClickListener mOnClickListener = new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
return new ErrorDisplayer(activity, mOnClickListener);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public class CacheWriterFactory {
public CacheWriter create(ISQLiteDatabase writableDatabase) {
return DatabaseDI.createCacheWriter(writableDatabase);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public class Database {
public static final String DATABASE_NAME = "GeoBeagle.db";
public static final int DATABASE_VERSION = 11;
public static final String S0_COLUMN_CACHE_TYPE = "CacheType INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_CONTAINER = "Container INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1";
public static final String S0_COLUMN_DIFFICULTY = "Difficulty INTEGER NOT NULL Default 0";
public static final String S0_COLUMN_TERRAIN = "Terrain INTEGER NOT NULL Default 0";
public static final String S0_INTENT = "intent";
public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?";
public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?";
public static final String SQL_CREATE_CACHE_TABLE_V08 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR);";
public static final String SQL_CREATE_CACHE_TABLE_V10 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ");";
public static final String SQL_CREATE_CACHE_TABLE_V11 = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ", "
+ S0_COLUMN_CACHE_TYPE + ", " + S0_COLUMN_CONTAINER + ", " + S0_COLUMN_DIFFICULTY
+ ", " + S0_COLUMN_TERRAIN + ");";
public static final String SQL_CREATE_GPX_TABLE_V10 = "CREATE TABLE GPX ("
+ "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL);";
public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude);";
public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude);";
public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source);";
public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?";
public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1";
public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1";
public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES";
public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?";
public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?";
public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES "
+ "(Id, Description, Latitude, Longitude, Source, DeleteMe, CacheType, Difficulty, Terrain, Container) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?, ?)";
public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)";
public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '"
+ S0_INTENT + "'";
public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1";
public static final String TBL_CACHES = "CACHES";
public static final String TBL_GPX = "GPX";
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.BoundingBox;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.Search;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchDown;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.SearchUp;
import com.google.code.geobeagle.database.WhereFactoryNearestCaches.WhereStringFactory;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.Arrays;
public class DatabaseDI {
public static class CacheReaderCursorFactory {
public CacheReaderCursor create(Cursor cursor) {
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheReaderCursor(cursor, geocacheFactory, dbToGeocacheAdapter);
}
}
public static class GeoBeagleSqliteOpenHelper extends SQLiteOpenHelper {
private final OpenHelperDelegate mOpenHelperDelegate;
public GeoBeagleSqliteOpenHelper(Context context) {
super(context, Database.DATABASE_NAME, null, Database.DATABASE_VERSION);
mOpenHelperDelegate = new OpenHelperDelegate();
}
public SQLiteWrapper getWritableSqliteWrapper() {
return new SQLiteWrapper(this.getWritableDatabase());
}
@Override
public void onCreate(SQLiteDatabase db) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onCreate(sqliteWrapper);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(db);
mOpenHelperDelegate.onUpgrade(sqliteWrapper, oldVersion);
}
}
public static class SQLiteWrapper implements ISQLiteDatabase {
private final SQLiteDatabase mSQLiteDatabase;
public SQLiteWrapper(SQLiteDatabase writableDatabase) {
mSQLiteDatabase = writableDatabase;
}
public void beginTransaction() {
mSQLiteDatabase.beginTransaction();
}
public int countResults(String table, String selection, String... selectionArgs) {
Log.d("GeoBeagle", "SQL count results: " + selection + ", "
+ Arrays.toString(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) {
Log.d("GeoBeagle", "SQL: " + sql);
mSQLiteDatabase.execSQL(sql);
}
public void execSQL(String sql, Object... bindArgs) {
Log.d("GeoBeagle", "SQL: " + sql + ", " + Arrays.toString(bindArgs));
mSQLiteDatabase.execSQL(sql, bindArgs);
}
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs) {
final Cursor query = mSQLiteDatabase.query(table, columns, selection, selectionArgs,
groupBy, orderBy, having, limit);
// Log.d("GeoBeagle", "limit: " + limit + ", count: " +
// query.getCount() + ", query: "
// + selection);
Log.d("GeoBeagle", "limit: " + limit + ", query: " + selection);
return query;
}
public Cursor rawQuery(String sql, String[] selectionArgs) {
return mSQLiteDatabase.rawQuery(sql, selectionArgs);
}
public void setTransactionSuccessful() {
mSQLiteDatabase.setTransactionSuccessful();
}
public void close() {
Log.d("GeoBeagle", "----------closing sqlite------");
mSQLiteDatabase.close();
}
public boolean isOpen() {
return mSQLiteDatabase.isOpen();
}
}
static public class SearchFactory {
public Search createSearch(double latitude, double longitude, float min, float max,
ISQLiteDatabase sqliteWrapper) {
WhereStringFactory whereStringFactory = new WhereStringFactory();
BoundingBox boundingBox = new BoundingBox(latitude, longitude, sqliteWrapper,
whereStringFactory);
SearchDown searchDown = new SearchDown(boundingBox, min);
SearchUp searchUp = new SearchUp(boundingBox, max);
return new WhereFactoryNearestCaches.Search(boundingBox, searchDown, searchUp);
}
}
public static CacheReader createCacheReader(ISQLiteDatabase sqliteWrapper) {
final CacheReaderCursorFactory cacheReaderCursorFactory = new CacheReaderCursorFactory();
return new CacheReader(sqliteWrapper, cacheReaderCursorFactory);
}
public static CacheWriter createCacheWriter(ISQLiteDatabase writableDatabase) {
// final SQLiteWrapper sqliteWrapper = new
// DatabaseDI.SQLiteWrapper(sqliteDatabaseWritable);
final DbToGeocacheAdapter dbToGeocacheAdapter = new DbToGeocacheAdapter();
return new CacheWriter(writableDatabase, 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;
public class Time {
public long getCurrentTime() {
return System.currentTimeMillis();
}
} | 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.LocationControlBuffered.GpsDisabledLocation;
import com.google.code.geobeagle.LocationControlBuffered.GpsEnabledLocation;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector.LocationComparator;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.NullSortStrategy;
import com.google.code.geobeagle.location.LocationControl;
import com.google.code.geobeagle.location.LocationControl.LocationChooser;
import android.location.Location;
import android.location.LocationManager;
public class LocationControlDi {
public static LocationControlBuffered create(LocationManager locationManager) {
final LocationChooser locationChooser = new LocationChooser();
final LocationControl locationControl = new LocationControl(locationManager,
locationChooser);
final NullSortStrategy nullSortStrategy = new NullSortStrategy();
final LocationComparator locationComparator = new LocationComparator();
final DistanceSortStrategy distanceSortStrategy = new DistanceSortStrategy(
locationComparator);
final GpsDisabledLocation gpsDisabledLocation = new GpsDisabledLocation();
IGpsLocation lastGpsLocation;
final Location lastKnownLocation = locationManager.getLastKnownLocation("gps");
if (lastKnownLocation == null)
lastGpsLocation = gpsDisabledLocation;
else
lastGpsLocation = new GpsEnabledLocation((float)lastKnownLocation.getLatitude(),
(float)lastKnownLocation.getLongitude());
return new LocationControlBuffered(locationControl, distanceSortStrategy, nullSortStrategy,
gpsDisabledLocation, lastGpsLocation, lastKnownLocation);
}
}
| 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.cachedetails;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public 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 {
try {
mWriter.write(str);
} catch (IOException e) {
throw new IOException("Error writing line '" + str + "'");
}
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity;
import com.google.code.geobeagle.Geocache;
import 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 com.google.code.geobeagle.activity.main.GeocacheFromPreferencesFactory;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
public class ActivityRestorer {
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();
}
}
static class NullRestorer implements Restorer {
@Override
public void restore() {
}
}
interface Restorer {
void restore();
}
static class ViewCacheRestorer implements Restorer {
private final Activity mActivity;
private final GeocacheFromPreferencesFactory mGeocacheFromPreferencesFactory;
private final SharedPreferences mSharedPreferences;
public ViewCacheRestorer(GeocacheFromPreferencesFactory geocacheFromPreferencesFactory,
SharedPreferences sharedPreferences, Activity activity) {
mGeocacheFromPreferencesFactory = geocacheFromPreferencesFactory;
mSharedPreferences = sharedPreferences;
mActivity = activity;
}
@Override
public void restore() {
final Geocache geocache = mGeocacheFromPreferencesFactory.create(mSharedPreferences);
final Intent intent = new Intent(mActivity, GeoBeagle.class);
intent.putExtra("geocache", geocache).setAction(GeocacheListController.SELECT_CACHE);
mActivity.startActivity(intent);
mActivity.finish();
}
}
private final ActivityTypeFactory mActivityTypeFactory;
private final Restorer[] mRestorers;
private final SharedPreferences mSharedPreferences;
public ActivityRestorer(Activity activity,
GeocacheFromPreferencesFactory geocacheFromPreferencesFactory,
ActivityTypeFactory activityTypeFactory, SharedPreferences sharedPreferences) {
mActivityTypeFactory = activityTypeFactory;
mSharedPreferences = sharedPreferences;
final NullRestorer nullRestorer = new NullRestorer();
mRestorers = new Restorer[] {
nullRestorer, new CacheListRestorer(activity), nullRestorer,
new ViewCacheRestorer(geocacheFromPreferencesFactory, sharedPreferences, activity)
};
}
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 |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.Overlay;
import android.util.Log;
import java.util.List;
public class OverlayManager {
static final int DENSITY_MAP_ZOOM_THRESHOLD = 13;
private final CachePinsOverlayFactory mCachePinsOverlayFactory;
private final DensityOverlay mDensityOverlay;
private final GeoMapView mGeoMapView;
private final List<Overlay> mMapOverlays;
private boolean mUsesDensityMap;
public OverlayManager(GeoMapView geoMapView, List<Overlay> mapOverlays,
DensityOverlay densityOverlay, CachePinsOverlayFactory cachePinsOverlayFactory,
boolean usesDensityMap) {
mGeoMapView = geoMapView;
mMapOverlays = mapOverlays;
mDensityOverlay = densityOverlay;
mCachePinsOverlayFactory = cachePinsOverlayFactory;
mUsesDensityMap = usesDensityMap;
}
public void selectOverlay() {
final int zoomLevel = mGeoMapView.getZoomLevel();
Log.d("GeoBeagle", "Zoom: " + zoomLevel);
boolean newZoomUsesDensityMap = zoomLevel < OverlayManager.DENSITY_MAP_ZOOM_THRESHOLD;
if (newZoomUsesDensityMap && mUsesDensityMap)
return;
mUsesDensityMap = newZoomUsesDensityMap;
mMapOverlays.set(0, mUsesDensityMap ? mDensityOverlay : mCachePinsOverlayFactory
.getCachePinsOverlay());
}
public boolean usesDensityMap() {
return mUsesDensityMap;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import java.util.ArrayList;
public class CachePinsOverlayFactory {
private final CacheItemFactory mCacheItemFactory;
private CachePinsOverlay mCachePinsOverlay;
private final Context mContext;
private final Drawable mDefaultMarker;
private final GeoMapView mGeoMapView;
private QueryManager mQueryManager;
public CachePinsOverlayFactory(GeoMapView geoMapView, Context context, Drawable defaultMarker,
CacheItemFactory cacheItemFactory, CachePinsOverlay cachePinsOverlay,
QueryManager queryManager) {
mGeoMapView = geoMapView;
mContext = context;
mDefaultMarker = defaultMarker;
mCacheItemFactory = cacheItemFactory;
mCachePinsOverlay = cachePinsOverlay;
mQueryManager = queryManager;
}
public CachePinsOverlay getCachePinsOverlay() {
Log.d("GeoBeagle", "refresh Caches");
// final CacheListDelegateDI.Timing timing = new
// CacheListDelegateDI.Timing();
Projection projection = mGeoMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mGeoMapView.getRight(), mGeoMapView
.getBottom());
if (!mQueryManager.needsLoading(newTopLeft, newBottomRight))
return mCachePinsOverlay;
// timing.lap("Loaded caches");
// timing.start();
ArrayList<Geocache> list = mQueryManager.load(newTopLeft, newBottomRight);
mCachePinsOverlay = new CachePinsOverlay(mCacheItemFactory, mContext, mDefaultMarker, list);
return mCachePinsOverlay;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import java.util.HashMap;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import com.google.code.geobeagle.CacheType;
class CacheDrawables {
private static Drawable loadAndSizeDrawable(Resources resources, int res) {
Drawable drawable = resources.getDrawable(res);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(-width/2, -height, width/2, 0);
return drawable;
}
private final HashMap<CacheType, Drawable> mCacheDrawables;
CacheDrawables(Resources resources) {
final CacheType[] cacheTypes = CacheType.values();
mCacheDrawables = new HashMap<CacheType, Drawable>(cacheTypes.length);
for (CacheType cacheType : cacheTypes) {
final Drawable loadAndSizeDrawable = loadAndSizeDrawable(resources, cacheType
.iconMap());
mCacheDrawables.put(cacheType, loadAndSizeDrawable);
}
}
Drawable get(CacheType cacheType) {
return mCacheDrawables.get(cacheType);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
class CacheItemFactory {
private final CacheDrawables mCacheDrawables;
CacheItemFactory(CacheDrawables cacheDrawables) {
mCacheDrawables = cacheDrawables;
}
CacheItem createCacheItem(Geocache geocache) {
final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), (String)geocache
.getId(), geocache);
cacheItem.setMarker(mCacheDrawables.get(geocache.getCacheType()));
return cacheItem;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class DensityMatrix {
public static class DensityPatch {
private int mCacheCount;
private final int mLatLowE6;
private final int mLonLowE6;
public DensityPatch(double latLow, double lonLow) {
mCacheCount = 0;
mLatLowE6 = (int)(latLow * 1E6);
mLonLowE6 = (int)(lonLow * 1E6);
}
public int getAlpha() {
return Math.min(210, 10 + 32 * mCacheCount);
}
public int getCacheCount() {
return mCacheCount;
}
public int getLatLowE6() {
return mLatLowE6;
}
public int getLonLowE6() {
return mLonLowE6;
}
public void setCacheCount(int count) {
mCacheCount = count;
}
}
/** Mapping lat -> (mapping lon -> cache count) */
private TreeMap<Integer, Map<Integer, DensityPatch>> mBuckets = new TreeMap<Integer, Map<Integer, DensityPatch>>();
private double mLatResolution;
private double mLonResolution;
public DensityMatrix(double latResolution, double lonResolution) {
mLatResolution = latResolution;
mLonResolution = lonResolution;
}
public void addCaches(ArrayList<Geocache> list) {
for (Geocache cache : list) {
incrementBucket(cache.getLatitude(), cache.getLongitude());
}
}
public List<DensityPatch> getDensityPatches() {
ArrayList<DensityPatch> result = new ArrayList<DensityPatch>();
for (Integer latBucket : mBuckets.keySet()) {
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
result.addAll(lonMap.values());
}
return result;
}
private void incrementBucket(double lat, double lon) {
Integer latBucket = (int)Math.floor(lat / mLatResolution);
Integer lonBucket = (int)Math.floor(lon / mLonResolution);
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
if (lonMap == null) {
// Key didn't exist in map
lonMap = new TreeMap<Integer, DensityPatch>();
mBuckets.put(latBucket, lonMap);
}
DensityPatch patch = lonMap.get(lonBucket);
if (patch == null) {
patch = new DensityPatch(latBucket * mLatResolution, lonBucket * mLonResolution);
lonMap.put(lonBucket, patch);
}
patch.setCacheCount(patch.getCacheCount() + 1);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
import java.util.List;
class DensityPatchManager {
private List<DensityMatrix.DensityPatch> mDensityPatches;
private final QueryManager mQueryManager;
public static final double RESOLUTION_LATITUDE = 0.01;
public static final double RESOLUTION_LONGITUDE = 0.02;
public static final int RESOLUTION_LATITUDE_E6 = (int)(RESOLUTION_LATITUDE * 1E6);
public static final int RESOLUTION_LONGITUDE_E6 = (int)(RESOLUTION_LONGITUDE * 1E6);
DensityPatchManager(List<DensityMatrix.DensityPatch> patches, QueryManager queryManager) {
mDensityPatches = patches;
mQueryManager = queryManager;
}
public List<DensityMatrix.DensityPatch> getDensityPatches(MapView mMapView) {
Projection projection = mMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mMapView.getRight(), mMapView.getBottom());
if (!mQueryManager.needsLoading(newTopLeft, newBottomRight)) {
return mDensityPatches;
}
ArrayList<Geocache> list = mQueryManager.load(newTopLeft, newBottomRight);
DensityMatrix densityMatrix = new DensityMatrix(DensityPatchManager.RESOLUTION_LATITUDE,
DensityPatchManager.RESOLUTION_LONGITUDE);
densityMatrix.addCaches(list);
mDensityPatches = densityMatrix.getDensityPatches();
// Log.d("GeoBeagle", "Density patches:" + mDensityPatches.size());
return mDensityPatches;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.MapView;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.actions.MenuActions;
import android.view.Menu;
import android.view.MenuItem;
public class GeoMapActivityDelegate {
public static class MenuActionToggleSatellite extends MenuActionBase {
private final MapView mMapView;
public MenuActionToggleSatellite(MapView mapView) {
super(R.string.menu_toggle_satellite);
mMapView = mapView;
}
@Override
public void act() {
mMapView.setSatellite(!mMapView.isSatellite());
}
}
private final GeoMapView mMapView;
private final MenuActions mMenuActions;
public GeoMapActivityDelegate(GeoMapView mapView, MenuActions menuActions) {
mMapView = mapView;
mMenuActions = menuActions;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public boolean onMenuOpened(Menu menu) {
menu.findItem(R.string.menu_toggle_satellite).setTitle(
mMapView.isSatellite() ? R.string.map_view : R.string.satellite_view);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.List;
public class DensityOverlayDelegate {
private static final double RESOLUTION_LATITUDE_E6 = (DensityPatchManager.RESOLUTION_LATITUDE * 1E6);
private static final double RESOLUTION_LONGITUDE_E6 = (DensityPatchManager.RESOLUTION_LONGITUDE * 1E6);
private final Paint mPaint;
private final Rect mPatchRect;
private final Point mScreenBottomRight;
private final Point mScreenTopLeft;
private final CacheListDelegateDI.Timing mTiming;
private final DensityPatchManager mDensityPatchManager;
public DensityOverlayDelegate(Rect patchRect, Paint paint, Point screenLow, Point screenHigh,
DensityPatchManager densityPatchManager) {
mTiming = new CacheListDelegateDI.Timing();
mPatchRect = patchRect;
mPaint = paint;
mScreenTopLeft = screenLow;
mScreenBottomRight = screenHigh;
mDensityPatchManager = densityPatchManager;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (shadow)
return; // No shadow layer
// Log.d("GeoBeagle", ">>>>>>>>>>Starting draw");
List<DensityMatrix.DensityPatch> densityPatches = mDensityPatchManager
.getDensityPatches(mapView);
mTiming.start();
final Projection projection = mapView.getProjection();
final GeoPoint newGeoTopLeft = projection.fromPixels(0, 0);
final GeoPoint newGeoBottomRight = projection.fromPixels(mapView.getRight(), mapView
.getBottom());
projection.toPixels(newGeoTopLeft, mScreenTopLeft);
projection.toPixels(newGeoBottomRight, mScreenBottomRight);
final int topLatitudeE6 = newGeoTopLeft.getLatitudeE6();
final int leftLongitudeE6 = newGeoTopLeft.getLongitudeE6();
final int bottomLatitudeE6 = newGeoBottomRight.getLatitudeE6();
final int rightLongitudeE6 = newGeoBottomRight.getLongitudeE6();
final double pixelsPerLatE6Degrees = (double)(mScreenBottomRight.y - mScreenTopLeft.y)
/ (double)(bottomLatitudeE6 - topLatitudeE6);
final double pixelsPerLonE6Degrees = (double)(mScreenBottomRight.x - mScreenTopLeft.x)
/ (double)(rightLongitudeE6 - leftLongitudeE6);
int patchCount = 0;
for (DensityPatch patch : densityPatches) {
final int patchLatLowE6 = patch.getLatLowE6();
final int patchLonLowE6 = patch.getLonLowE6();
int xOffset = (int)((patchLonLowE6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int xEnd = (int)((patchLonLowE6 + RESOLUTION_LONGITUDE_E6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int yOffset = (int)((patchLatLowE6 - topLatitudeE6) * pixelsPerLatE6Degrees);
int yEnd = (int)((patchLatLowE6 + RESOLUTION_LATITUDE_E6 - topLatitudeE6) * pixelsPerLatE6Degrees);
mPatchRect.set(xOffset, yEnd, xEnd, yOffset);
// Log.d("GeoBeagle", "patchrect: " + mPatchRect.bottom + ", " +
// mPatchRect.left
// + ", " + mPatchRect.top + ", " + mPatchRect.right);
mPaint.setAlpha(patch.getAlpha());
canvas.drawRect(mPatchRect, mPaint);
patchCount++;
}
// mTiming.lap("Done drawing");
// Log.d("GeoBeagle", "patchcount: " + patchCount);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.WhereFactoryFixedArea;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.Toaster;
import java.util.ArrayList;
class QueryManager {
/**
* We need to cache "needs loading" status because we might be zoomed out so
* far we see no caches. In that situation, the compass will attempt to
* refresh us every second, and we'll query the database over and over again
* to learn that we have too many caches for the same set of points.
*/
static class CachedNeedsLoading {
private GeoPoint mOldBottomRight;
private GeoPoint mOldTopLeft;
public CachedNeedsLoading(GeoPoint topLeft, GeoPoint bottomRight) {
mOldTopLeft = topLeft;
mOldBottomRight = bottomRight;
}
boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) {
if (mOldTopLeft.equals(newTopLeft) && mOldBottomRight.equals(newBottomRight))
return false;
mOldTopLeft = newTopLeft;
mOldBottomRight = newBottomRight;
return true;
}
}
static class PeggedLoader {
private final DbFrontend mDbFrontend;
private final ArrayList<Geocache> mNullList;
private final Toaster mToaster;
private boolean mTooManyCaches;
PeggedLoader(DbFrontend dbFrontend, ArrayList<Geocache> nullList, Toaster toaster) {
mNullList = nullList;
mDbFrontend = dbFrontend;
mToaster = toaster;
mTooManyCaches = false;
}
ArrayList<Geocache> load(int latMin, int lonMin, int latMax, int lonMax,
WhereFactoryFixedArea where, int[] newBounds) {
if (mDbFrontend.count(0, 0, where) > 1500) {
latMin = latMax = lonMin = lonMax = 0;
if (!mTooManyCaches) {
mToaster.showToast();
mTooManyCaches = true;
}
return mNullList;
}
mTooManyCaches = false;
newBounds[0] = latMin;
newBounds[1] = lonMin;
newBounds[2] = latMax;
newBounds[3] = lonMax;
return mDbFrontend.loadCaches(0, 0, where);
}
}
private final CachedNeedsLoading mCachedNeedsLoading;
private int[] mLatLonMinMax; // i.e. latmin, lonmin, latmax, lonmax
private final PeggedLoader mPeggedLoader;
QueryManager(PeggedLoader peggedLoader, CachedNeedsLoading cachedNeedsLoading,
int[] latLonMinMax) {
mLatLonMinMax = latLonMinMax;
mPeggedLoader = peggedLoader;
mCachedNeedsLoading = cachedNeedsLoading;
}
ArrayList<Geocache> load(GeoPoint newTopLeft, GeoPoint newBottomRight) {
// Expand the area by the resolution so we get complete patches for the
// density map. This isn't needed for the pins overlay, but it doesn't
// hurt either.
final int lonMin = newTopLeft.getLongitudeE6()
- DensityPatchManager.RESOLUTION_LONGITUDE_E6;
final int latMax = newTopLeft.getLatitudeE6() + DensityPatchManager.RESOLUTION_LATITUDE_E6;
final int latMin = newBottomRight.getLatitudeE6()
- DensityPatchManager.RESOLUTION_LATITUDE_E6;
final int lonMax = newBottomRight.getLongitudeE6()
+ DensityPatchManager.RESOLUTION_LONGITUDE_E6;
final WhereFactoryFixedArea where = new WhereFactoryFixedArea((double)latMin / 1E6,
(double)lonMin / 1E6, (double)latMax / 1E6, (double)lonMax / 1E6);
ArrayList<Geocache> list = mPeggedLoader.load(latMin, lonMin, latMax, lonMax, where,
mLatLonMinMax);
return list;
}
boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) {
return mCachedNeedsLoading.needsLoading(newTopLeft, newBottomRight)
&& (newTopLeft.getLatitudeE6() > mLatLonMinMax[2]
|| newTopLeft.getLongitudeE6() < mLatLonMinMax[1]
|| newBottomRight.getLatitudeE6() < mLatLonMinMax[0] || newBottomRight
.getLongitudeE6() > mLatLonMinMax[3]);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.net.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.activity.main;
import android.net.UrlQuerySanitizer;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
public static final String[] geocachingQueryParam = new String[] {
"q"
};
// #Wildwood Park, Saratoga, CA(The Nut Case #89882)
private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)");
private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)");
private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.]+)[^\\d]*");
private static final Pattern PAT_LATLON = Pattern
.compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)");
private static final Pattern PAT_LATLONDEC = Pattern.compile("([\\d.]+)\\s+([\\d.]+)");
private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]");
private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*");
private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]");
public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) {
final double fAbsDegrees = Math.abs(fDegrees);
final int dAbsDegrees = (int)fAbsDegrees;
return String.format(Locale.US, (fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees,
60.0 * (fAbsDegrees - dAbsDegrees));
}
public static double parseCoordinate(CharSequence string) {
int sign = 1;
final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string);
if (negsignMatcher.find()) {
sign = -1;
}
final Matcher signMatcher = PAT_SIGN.matcher(string);
string = signMatcher.replaceAll("");
final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string);
double degrees = 0.0;
for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) {
degrees += Double.parseDouble(dmsMatcher.group(1)) / scale;
}
return sign * degrees;
}
public static CharSequence[] parseDescription(CharSequence string) {
Matcher matcher = PAT_ATLASQUEST.matcher(string);
if (matcher.matches())
return new CharSequence[] {
"LB" + matcher.group(2).trim(), matcher.group(1).trim()
};
return new CharSequence[] {
string, ""
};
}
public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer,
ValueSanitizer valueSanitizer) {
sanitizer.registerParameters(geocachingQueryParam, valueSanitizer);
sanitizer.parseQuery(query);
return sanitizer.getValue("q");
}
public static CharSequence[] splitCoordsAndDescription(CharSequence location) {
Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(2).trim(), matcher.group(1).trim()
};
}
matcher = PAT_PAREN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
}
// No description.
return new CharSequence[] {
location, ""
};
}
public static CharSequence[] splitLatLon(CharSequence string) {
Matcher matcherDecimal = PAT_LATLONDEC.matcher(string);
if (matcherDecimal.matches()) {
return new String[] {
matcherDecimal.group(1).trim(), matcherDecimal.group(2).trim()
};
}
Matcher matcher = PAT_LATLON.matcher(string);
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 |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
/**
* Library for some use useful latitude/longitude math
*/
public class GeoUtils {
private static int EARTH_RADIUS_KM = 6371;
public static int MILLION = 1000000;
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Distance between the two points in kilometers.
*/
public static double distanceKm(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
}
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Distance between the two points in kilometers.
*/
//
// public static double distanceKm(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double)MILLION;
// double lon1 = p1.getLongitudeE6() / (double)MILLION;
// double lat2 = p2.getLatitudeE6() / (double)MILLION;
// double lon2 = p2.getLongitudeE6() / (double)MILLION;
//
// return distanceKm(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
// public static double bearing(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double) MILLION;
// double lon1 = p1.getLongitudeE6() / (double) MILLION;
// double lat2 = p2.getLatitudeE6() / (double) MILLION;
// double lon2 = p2.getLongitudeE6() / (double) MILLION;
//
// return bearing(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
public static double bearing(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* Converts an angle in radians to degrees
*/
public static double radToBearing(double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.text.InputFilter;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Date;
public class FieldNoteSender {
static class DialogHelper {
Dialog createDialog(Builder mDialogBuilder, View fieldNoteDialogView, OnClickOk onClickOk,
OnClickCancel onClickCancel) {
mDialogBuilder.setTitle(R.string.field_note_title);
mDialogBuilder.setView(fieldNoteDialogView);
mDialogBuilder.setPositiveButton(R.string.send_sms, onClickOk);
mDialogBuilder.setNegativeButton(R.string.cancel, onClickCancel);
return mDialogBuilder.create();
}
EditText createEditor(View fieldNoteDialogView, CharSequence prefix,
FieldNoteResources fieldNoteResources) {
final EditText editText = (EditText)fieldNoteDialogView.findViewById(R.id.fieldnote);
final DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
final String timestamp = "(" + dateFormat.format(new Date()) + "/"
+ fieldNoteResources.getString(R.array.geobeagle_sig) + ") ";
final String defaultMessage = fieldNoteResources.getString(R.array.default_msg);
final String msg = timestamp + defaultMessage;
editText.setText(msg);
final InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(
160 - (fieldNoteResources.getString(R.array.fieldnote_code) + prefix).length());
editText.setFilters(new InputFilter[] {
lengthFilter
});
final int len = msg.length();
editText.setSelection(len - defaultMessage.length(), len);
return editText;
}
}
static class OnClickCancel implements OnClickListener {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
static class OnClickOk implements OnClickListener {
private final EditText mEditText;
private final CharSequence mPrefix;
private final FieldNoteResources mFieldNoteResources;
private final Context mContext;
public OnClickOk(FieldNoteResources fieldNoteResources, EditText editText,
CharSequence prefix, Context context) {
mEditText = editText;
mPrefix = prefix;
mFieldNoteResources = fieldNoteResources;
mContext = context;
}
public void onClick(DialogInterface dialog, int whichButton) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("address", "41411");
sendIntent.putExtra("sms_body",
mFieldNoteResources.getString(R.array.fieldnote_code) + mPrefix + mEditText.getText());
sendIntent.setType("vnd.android-dir/mms-sms");
mContext.startActivity(sendIntent);
dialog.dismiss();
}
}
private final Builder mDialogBuilder;
private final DialogHelper mDialogHelper;
private final LayoutInflater mLayoutInflater;
public static class FieldNoteResources {
private final Resources mResources;
private final boolean mDnf;
public FieldNoteResources(Resources resources, int id) {
mResources = resources;
mDnf = (id == R.id.menu_log_dnf);
}
String getString(int id) {
return mResources.getStringArray(id)[mDnf ? 0 : 1];
}
}
FieldNoteSender(LayoutInflater layoutInflater, AlertDialog.Builder builder,
DialogHelper dialogHelper) {
mLayoutInflater = layoutInflater;
mDialogBuilder = builder;
mDialogHelper = dialogHelper;
}
public Dialog createDialog(CharSequence geocacheId, FieldNoteResources fieldNoteResources,
Context context) {
View fieldNoteDialogView = mLayoutInflater.inflate(R.layout.fieldnote, null);
Linkify.addLinks((TextView)fieldNoteDialogView.findViewById(R.id.fieldnote_caveat),
Linkify.WEB_URLS);
CharSequence prefix = geocacheId + " ";
EditText editText = mDialogHelper.createEditor(fieldNoteDialogView, prefix,
fieldNoteResources);
OnClickOk onClickOk = new OnClickOk(fieldNoteResources, editText, prefix, context);
OnClickCancel onClickCancel = new OnClickCancel();
return mDialogHelper.createDialog(mDialogBuilder, fieldNoteDialogView, onClickOk,
onClickCancel);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Provider;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.view.View;
public class WebPageAndDetailsButtonEnabler {
interface CheckButton {
public void check(Geocache geocache);
}
public static class CheckButtons {
private final CheckButton[] mCheckButtons;
public CheckButtons(CheckButton[] checkButtons) {
mCheckButtons = checkButtons;
}
public void check(Geocache geocache) {
for (CheckButton checkButton : mCheckButtons) {
checkButton.check(geocache);
}
}
}
public static class CheckDetailsButton implements CheckButton {
private final View mDetailsButton;
public CheckDetailsButton(View checkDetailsButton) {
mDetailsButton = checkDetailsButton;
}
public void check(Geocache geocache) {
mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX);
}
}
public static class CheckWebPageButton implements CheckButton {
private final View mWebPageButton;
public CheckWebPageButton(View webPageButton) {
mWebPageButton = webPageButton;
}
public void check(Geocache geocache) {
final Provider contentProvider = geocache.getContentProvider();
mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK
|| contentProvider == GeocacheFactory.Provider.ATLAS_QUEST
|| contentProvider == GeocacheFactory.Provider.OPENCACHING);
}
}
private final CheckButtons mCheckButtons;
private final GeoBeagle mGeoBeagle;
public WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, CheckButtons checkButtons) {
mGeoBeagle = geoBeagle;
mCheckButtons = checkButtons;
}
public void check() {
mCheckButtons.check(mGeoBeagle.getGeocache());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
public class CacheDetailsOnClickListener implements View.OnClickListener {
private final Builder mAlertDialogBuilder;
private final CacheDetailsLoader mCacheDetailsLoader;
private final LayoutInflater mEnv;
private final GeoBeagle mGeoBeagle;
public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder,
LayoutInflater env, CacheDetailsLoader cacheDetailsLoader) {
mAlertDialogBuilder = alertDialogBuilder;
mEnv = env;
mCacheDetailsLoader = cacheDetailsLoader;
mGeoBeagle = geoBeagle;
}
public void onClick(View v) {
View detailsView = mEnv.inflate(R.layout.cache_details, null);
CharSequence id = mGeoBeagle.getGeocache().getId();
mAlertDialogBuilder.setTitle(id);
mAlertDialogBuilder.setView(detailsView);
WebView webView = (WebView)detailsView.findViewById(R.id.webview);
webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(id), "text/html", "utf-8",
"about:blank");
mAlertDialogBuilder.create().show();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.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 mActivityNotFoundErrorMessage;
public CacheButtonOnClickListener(IntentStarter intentStarter, String errorMessage,
ErrorDisplayer errorDisplayer) {
mDestinationToIntentFactory = intentStarter;
mErrorDisplayer = errorDisplayer;
mActivityNotFoundErrorMessage = errorMessage;
}
public void onClick(View view) {
try {
mDestinationToIntentFactory.startIntent();
} catch (final ActivityNotFoundException e) {
mErrorDisplayer.displayError(R.string.error2, e.getMessage(),
mActivityNotFoundErrorMessage);
} catch (final Exception e) {
mErrorDisplayer.displayError(R.string.error1, e.getMessage());
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.main.RadarView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheViewer {
public interface AttributeViewer {
void setImage(int attributeValue);
}
public static class LabelledAttributeViewer implements AttributeViewer {
private final UnlabelledAttributeViewer mUnlabelledAttributeViewer;
private final TextView mLabel;
public LabelledAttributeViewer(int[] images, TextView label, ImageView imageView) {
mUnlabelledAttributeViewer = new UnlabelledAttributeViewer(images, imageView);
mLabel = label;
}
@Override
public void setImage(int attributeValue) {
mUnlabelledAttributeViewer.setImage(attributeValue);
mLabel.setVisibility(attributeValue == 0 ? View.GONE : View.VISIBLE);
}
}
public static class UnlabelledAttributeViewer implements AttributeViewer {
private final int[] mImages;
private final ImageView mImageView;
public UnlabelledAttributeViewer(int[] images, ImageView imageView) {
mImages = images;
mImageView = imageView;
}
public void setImage(int attributeValue) {
if (attributeValue == 0) {
mImageView.setVisibility(View.GONE);
return;
}
mImageView.setImageResource(mImages[attributeValue - 1]);
mImageView.setVisibility(View.VISIBLE);
}
}
public static class NameViewer {
private final TextView mName;
public NameViewer(TextView name) {
mName = name;
}
void set(CharSequence name) {
if (name.length() == 0) {
mName.setVisibility(View.GONE);
return;
}
mName.setText(name);
mName.setVisibility(View.VISIBLE);
}
}
public static final int CONTAINER_IMAGES[] = {
R.drawable.size_1, R.drawable.size_2, R.drawable.size_3, R.drawable.size_4
};
public static final int STAR_IMAGES[] = {
R.drawable.stars_1, R.drawable.stars_2, R.drawable.stars_3, R.drawable.stars_4,
R.drawable.stars_5, R.drawable.stars_6, R.drawable.stars_7, R.drawable.stars_8,
R.drawable.stars_9, R.drawable.stars_10
};
private final ImageView mCacheTypeImageView;
private final AttributeViewer mContainer;
private final AttributeViewer mDifficulty;
private final TextView mId;
private final NameViewer mName;
private final RadarView mRadarView;
private final AttributeViewer mTerrain;
public GeocacheViewer(RadarView radarView, TextView gcId, NameViewer gcName,
ImageView cacheTypeImageView, AttributeViewer gcDifficulty, AttributeViewer gcTerrain,
UnlabelledAttributeViewer gcContainer) {
mRadarView = radarView;
mId = gcId;
mName = gcName;
mCacheTypeImageView = cacheTypeImageView;
mDifficulty = gcDifficulty;
mTerrain = gcTerrain;
mContainer = gcContainer;
}
public void set(Geocache geocache) {
final double latitude = geocache.getLatitude();
final double longitude = geocache.getLongitude();
mRadarView.setTarget((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mId.setText(geocache.getId());
mCacheTypeImageView.setImageResource(geocache.getCacheType().iconBig());
mContainer.setImage(geocache.getContainer());
mDifficulty.setImage(geocache.getDifficulty());
mTerrain.setImage(geocache.getTerrain());
mName.set(geocache.getName());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.activity.main.intents.IntentStarter;
import android.app.Activity;
public class OnCacheButtonClickListenerBuilder {
private final Activity mActivity;
private final ErrorDisplayer mErrorDisplayer;
public OnCacheButtonClickListenerBuilder(Activity activity, ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mActivity = activity;
}
public void set(int id, IntentStarter intentStarter, String errorString) {
mActivity.findViewById(id).setOnClickListener(new CacheButtonOnClickListener(
intentStarter, errorString, mErrorDisplayer));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.Util;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Activity;
import android.content.Intent;
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 GeocacheFactory mGeocacheFactory;
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name,
EditText latitude, EditText longitude) {
mGeocacheFactory = geocacheFactory;
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return mGeocacheFactory.create(mId.getText(), mName.getText(), Util
.parseCoordinate(mLatitude.getText()), Util.parseCoordinate(mLongitude
.getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache
.getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache
.getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache
.getContainer());
}
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) {
final Geocache geocache = mGeocacheView.get();
mLocationSaver.saveLocation(geocache);
final Intent i = new Intent();
i.setAction(GeocacheListController.SELECT_CACHE);
i.putExtra("geocache", geocache);
mActivity.setResult(0, i);
mActivity.finish();
}
}
private final CancelButtonOnClickListener mCancelButtonOnClickListener;
private final GeocacheFactory mGeocacheFactory;
private final Activity mParent;
private final LocationSaver mLocationSaver;
public EditCacheActivityDelegate(Activity parent,
CancelButtonOnClickListener cancelButtonOnClickListener,
GeocacheFactory geocacheFactory, LocationSaver locationSaver) {
mParent = parent;
mCancelButtonOnClickListener = cancelButtonOnClickListener;
mGeocacheFactory = geocacheFactory;
mLocationSaver = locationSaver;
}
public void onCreate() {
mParent.setContentView(R.layout.cache_edit);
}
public void onResume() {
final Intent intent = mParent.getIntent();
final Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
final EditCache editCache = new EditCache(mGeocacheFactory, (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);
final SetButtonOnClickListener setButtonOnClickListener = new SetButtonOnClickListener(
mParent, editCache, mLocationSaver);
((Button)mParent.findViewById(R.id.edit_set)).setOnClickListener(setButtonOnClickListener);
((Button)mParent.findViewById(R.id.edit_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.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import android.location.Location;
public class MyLocationProvider {
private final ErrorDisplayer mErrorDisplayer;
private final LocationControlBuffered mLocationControlBuffered;
public MyLocationProvider(LocationControlBuffered locationControlBuffered,
ErrorDisplayer errorDisplayer) {
mLocationControlBuffered = locationControlBuffered;
mErrorDisplayer = errorDisplayer;
}
public Location getLocation() {
Location location = mLocationControlBuffered.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.activity.main;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.ErrorDisplayerDi;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.R.id;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.MenuActionEditGeocache;
import com.google.code.geobeagle.actions.MenuActionSearchOnline;
import com.google.code.geobeagle.actions.MenuActionSettings;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.LogFindClickListener;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSenderDI;
import com.google.code.geobeagle.activity.main.intents.GeocacheToCachePage;
import com.google.code.geobeagle.activity.main.intents.GeocacheToGoogleMap;
import com.google.code.geobeagle.activity.main.intents.IntentFactory;
import com.google.code.geobeagle.activity.main.intents.IntentStarterGeo;
import com.google.code.geobeagle.activity.main.intents.IntentStarterViewUri;
import com.google.code.geobeagle.activity.main.menuactions.MenuActionGoogleMaps;
import com.google.code.geobeagle.activity.main.view.CacheButtonOnClickListener;
import com.google.code.geobeagle.activity.main.view.CacheDetailsOnClickListener;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.Misc;
import com.google.code.geobeagle.activity.main.view.OnCacheButtonClickListenerBuilder;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.AttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.LabelledAttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.NameViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.UnlabelledAttributeViewer;
import com.google.code.geobeagle.activity.map.GeoMapActivity;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.location.LocationLifecycleManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
/*
* Main Activity for GeoBeagle.
*/
public class GeoBeagle extends Activity {
private GeoBeagleDelegate mGeoBeagleDelegate;
private DbFrontend mDbFrontend;
public Geocache getGeocache() {
return mGeoBeagleDelegate.getGeocache();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE) {
Log.d("GeoBeagle", "camera intent has returned.");
} else if (resultCode == 0)
setIntent(data);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "GeoBeagle onCreate");
setContentView(R.layout.main);
final ErrorDisplayer errorDisplayer = ErrorDisplayerDi.createErrorDisplayer(this);
final WebPageAndDetailsButtonEnabler webPageButtonEnabler = Misc.create(this,
findViewById(R.id.cache_page), findViewById(R.id.cache_details));
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationControlBuffered locationControlBuffered = LocationControlDi
.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final TextView gcid = (TextView)findViewById(R.id.gcid);
final AttributeViewer gcDifficulty = new LabelledAttributeViewer(
GeocacheViewer.STAR_IMAGES, (TextView)findViewById(R.id.gc_text_difficulty),
(ImageView)findViewById(R.id.gc_difficulty));
final AttributeViewer gcTerrain = new LabelledAttributeViewer(GeocacheViewer.STAR_IMAGES,
(TextView)findViewById(R.id.gc_text_terrain),
(ImageView)findViewById(R.id.gc_terrain));
final UnlabelledAttributeViewer gcContainer = new UnlabelledAttributeViewer(
GeocacheViewer.CONTAINER_IMAGES, (ImageView)findViewById(R.id.gccontainer));
final NameViewer gcName = new NameViewer(((TextView)findViewById(R.id.gcname)));
final RadarView radar = (RadarView)findViewById(R.id.radarview);
radar.setUseImperial(false);
radar.setDistanceView((TextView)findViewById(R.id.radar_distance),
(TextView)findViewById(R.id.radar_bearing),
(TextView)findViewById(R.id.radar_accuracy));
final GeocacheViewer geocacheViewer = new GeocacheViewer(radar, gcid, gcName,
(ImageView)findViewById(R.id.gcicon),
gcDifficulty, gcTerrain, gcContainer);
locationControlBuffered.onLocationChanged(null);
final IntentFactory intentFactory = new IntentFactory(new UriParser());
// Register for location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, radar);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, radar);
final AppLifecycleManager appLifecycleManager = new AppLifecycleManager(
getPreferences(MODE_PRIVATE), new LifecycleManager[] {
new LocationLifecycleManager(locationControlBuffered, locationManager),
new LocationLifecycleManager(radar, locationManager)
});
final IntentStarterViewUri intentStarterViewUri = new IntentStarterViewUri(this,
intentFactory, new GeocacheToGoogleMap(this));
final SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
final CompassListener compassListener = new CompassListener(new NullRefresher(),
locationControlBuffered, -1440f);
final LayoutInflater layoutInflater = LayoutInflater.from(this);
final FieldNoteSender fieldNoteSender = FieldNoteSenderDI.build(this, layoutInflater);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
final MenuAction[] menuActionArray = {
new MenuActionCacheList(this), new MenuActionEditGeocache(this),
// new MenuActionLogDnf(this), new MenuActionLogFind(this),
new MenuActionSearchOnline(this), new MenuActionSettings(this),
new MenuActionGoogleMaps(intentStarterViewUri)
};
final MenuActions menuActions = new MenuActions(getResources(), menuActionArray);
final Resources resources = this.getResources();
final SharedPreferences defaultSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
final GeocacheFromIntentFactory geocacheFromIntentFactory = new GeocacheFromIntentFactory(
geocacheFactory);
final IncomingIntentHandler incomingIntentHandler = new IncomingIntentHandler(
geocacheFactory, geocacheFromIntentFactory);
final GeocacheFromParcelFactory geocacheFromParcelFactory = new GeocacheFromParcelFactory(
geocacheFactory);
mDbFrontend = new DbFrontend(this);
mGeoBeagleDelegate = new GeoBeagleDelegate(activitySaver, appLifecycleManager,
compassListener, fieldNoteSender, this, geocacheFactory, geocacheViewer,
incomingIntentHandler, menuActions, geocacheFromParcelFactory,
mDbFrontend, radar, resources, sensorManager, defaultSharedPreferences,
webPageButtonEnabler);
// see http://www.androidguys.com/2008/11/07/rotational-forces-part-two/
if (getLastNonConfigurationInstance() != null) {
setIntent((Intent)getLastNonConfigurationInstance());
}
final Intent geoMapActivityIntent = new Intent(this, GeoMapActivity.class);
final IntentStarterGeo intentStarterMapActivity = new IntentStarterGeo(this,
geoMapActivityIntent);
final CacheButtonOnClickListener mapsButtonOnClickListener = new CacheButtonOnClickListener(
intentStarterMapActivity, "Map error", errorDisplayer);
findViewById(id.maps).setOnClickListener(mapsButtonOnClickListener);
final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(this);
final CacheDetailsOnClickListener cacheDetailsOnClickListener = Misc
.createCacheDetailsOnClickListener(this, cacheDetailsBuilder, layoutInflater);
findViewById(R.id.cache_details).setOnClickListener(cacheDetailsOnClickListener);
final GeocacheToCachePage geocacheToCachePage = new GeocacheToCachePage(getResources());
final IntentStarterViewUri cachePageIntentStarter = new IntentStarterViewUri(this,
intentFactory, geocacheToCachePage);
final CacheButtonOnClickListener cacheButtonOnClickListener = new CacheButtonOnClickListener(
cachePageIntentStarter, "", errorDisplayer);
findViewById(id.cache_page).setOnClickListener(cacheButtonOnClickListener);
final OnCacheButtonClickListenerBuilder cacheClickListenerSetter = new OnCacheButtonClickListenerBuilder(
this, errorDisplayer);
cacheClickListenerSetter.set(id.radarview, new IntentStarterGeo(this, new Intent(
"com.google.android.radar.SHOW_RADAR")),
"Please install the Radar application to use Radar.");
findViewById(id.menu_log_find).setOnClickListener(
new LogFindClickListener(this, id.menu_log_find));
findViewById(id.menu_log_dnf).setOnClickListener(
new LogFindClickListener(this, id.menu_log_dnf));
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
return mGeoBeagleDelegate.onCreateDialog(id);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mGeoBeagleDelegate.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.main_menu, menu);
//return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGeoBeagleDelegate.onKeyDown(keyCode, event))
return true;
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mGeoBeagleDelegate.onOptionsItemSelected(item);
}
@Override
public void onPause() {
super.onPause();
Log.d("GeoBeagle", "GeoBeagle onPause");
mGeoBeagleDelegate.onPause();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mGeoBeagleDelegate.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "GeoBeagle onResume");
mGeoBeagleDelegate.onResume();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance() {
return getIntent();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mGeoBeagleDelegate.onSaveInstanceState(outState);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1);
final Source source = mGeocacheFactory.sourceFromInt(iSource);
final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0);
final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType);
return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences
.getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0),
preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString(
Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt(
Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0),
preferences.getInt(Geocache.CONTAINER, 0));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.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.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.LocationSaver;
import android.content.Intent;
import android.net.UrlQuerySanitizer;
public class GeocacheFromIntentFactory {
private final GeocacheFactory mGeocacheFactory;
GeocacheFromIntentFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
Geocache viewCacheFromMapsIntent(Intent intent, LocationSaver locationSaver) {
final String query = intent.getData().getQuery();
final CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(),
UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal());
final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery);
final Geocache geocache = mGeocacheFactory.create(latlon[2], latlon[3], Util
.parseCoordinate(latlon[0]), Util.parseCoordinate(latlon[1]), Source.WEB_URL, null,
CacheType.NULL, 0, 0, 0);
locationSaver.saveLocation(geocache);
return geocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.Refresher;
class NullRefresher implements Refresher {
public void refresh() {
}
} | Java |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
/*
*
* 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 com.google.code.geobeagle.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.SensorListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("deprecation")
public class RadarView extends View implements SensorListener, LocationListener {
private static final long RETAIN_GPS_MILLIS = 10000L;
private Paint mGridPaint;
private Paint mErasePaint;
private float mOrientation;
private double mTargetLat;
private double mTargetLon;
private double mMyLocationLat;
private double mMyLocationLon;
private int mLastScale = -1;
private static float KM_PER_METERS = 0.001f;
private static float METERS_PER_KM = 1000f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using metric units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mMetricScaleChoices[] = {
100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100,
200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This
* array is for metric measurements.)
*/
private static float mMetricDisplayUnitsPerKm[] = {
METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for metric measurements.)
*/
private static String mMetricDisplayFormats[] = {
"%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm"
};
private static float KM_PER_YARDS = 0.0009144f;
private static float KM_PER_MILES = 1.609344f;
private static float YARDS_PER_KM = 1093.6133f;
private static float MILES_PER_KM = 0.621371192f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using standard units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mEnglishScaleChoices[] = {
100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS,
1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES,
20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES,
400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES,
10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This
* array is for standard measurements.)
*/
private static float mEnglishDisplayUnitsPerKm[] = {
YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for standard measurements.)
*/
private static String mEnglishDisplayFormats[] = {
"%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi"
};
private boolean mHaveLocation = false; // True when we have our location
private TextView mDistanceView;
private double mDistance; // Distance to target, in KM
private double mBearing; // Bearing to target, in degrees
// Ratio of the distance to the target to the radius of the outermost ring
// on the radar screen
private float mDistanceRatio;
private Bitmap mBlip; // The bitmap used to draw the target
// True if the display should use metric units; false if the display should
// use standard units
private boolean mUseMetric;
// Time in millis for the last time GPS reported a location
private long mLastGpsFixTime = 0L;
// The last location reported by the network provider. Use this if we can't
// get a location from GPS
private Location mNetworkLocation;
private boolean mGpsAvailable; // True if GPS is reporting a location
// True if the network provider is reporting a location
private boolean mNetworkAvailable;
private TextView mBearingView;
private float mMyLocationAccuracy;
private TextView mAccuracyView;
private final String mDegreesSymbol;
private Path mCompassPath;
private final Paint mCompassPaint;
private final Paint mArrowPaint;
private final Path mArrowPath;
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDegreesSymbol = context.getString(R.string.degrees_symbol);
// Paint used for the rings and ring text
mGridPaint = new Paint();
mGridPaint.setColor(0xFF00FF00);
mGridPaint.setAntiAlias(true);
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(1.0f);
mGridPaint.setTextSize(10.0f);
mGridPaint.setTextAlign(Align.CENTER);
mCompassPaint = new Paint();
mCompassPaint.setColor(0xFF00FF00);
mCompassPaint.setAntiAlias(true);
mCompassPaint.setStyle(Style.STROKE);
mCompassPaint.setStrokeWidth(1.0f);
mCompassPaint.setTextSize(10.0f);
mCompassPaint.setTextAlign(Align.CENTER);
// Paint used to erase the rectangle behind the ring text
mErasePaint = new Paint();
mErasePaint.setColor(0xFF191919);
mErasePaint.setStyle(Style.FILL);
// Paint used for the arrow
mArrowPaint = new Paint();
mArrowPaint.setColor(Color.WHITE);
mArrowPaint.setAntiAlias(true);
mArrowPaint.setStyle(Style.STROKE);
mArrowPaint.setStrokeWidth(16);
mArrowPaint.setAlpha(228);
mArrowPath = new Path();
mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap();
mCompassPath = new Path();
}
/**
* Sets the target to track on the radar
*
* @param latE6 Latitude of the target, multiplied by 1,000,000
* @param lonE6 Longitude of the target, multiplied by 1,000,000
*/
public void setTarget(int latE6, int lonE6) {
mTargetLat = latE6 / (double)GeoUtils.MILLION;
mTargetLon = lonE6 / (double)GeoUtils.MILLION;
}
/**
* Sets the view that we will use to report distance
*
* @param t The text view used to report distance
*/
public void setDistanceView(TextView d, TextView b, TextView a) {
mDistanceView = d;
mBearingView = b;
mAccuracyView = a;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = Math.min(getHeight(), getWidth()) / 2;
int radius = center - 8;
// Draw the rings
final Paint gridPaint = mGridPaint;
gridPaint.setAlpha(100);
canvas.drawCircle(center, center, radius, gridPaint);
canvas.drawCircle(center, center, radius * 3 / 4, gridPaint);
canvas.drawCircle(center, center, radius >> 1, gridPaint);
canvas.drawCircle(center, center, radius >> 2, gridPaint);
int blipRadius = (int)(mDistanceRatio * radius);
// Draw horizontal and vertical lines
canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint);
canvas.drawLine(center, center + (radius >> 2) - 6, center, center + radius + 6, gridPaint);
canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint);
canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint);
if (mHaveLocation) {
double northAngle = Math.toRadians(-mOrientation) - (Math.PI / 2);
float northX = (float)Math.cos(northAngle);
float northY = (float)Math.sin(northAngle);
final int compassLength = radius >> 2;
float tipX = northX * compassLength, tipY = northY * compassLength;
float baseX = northY * 8, baseY = -northX * 8;
double bearingToTarget = mBearing - mOrientation;
double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2);
float cos = (float)Math.cos(drawingAngle);
float sin = (float)Math.sin(drawingAngle);
mArrowPath.reset();
mArrowPath.moveTo(center - cos * radius, center - sin * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
final double arrowRight = drawingAngle + Math.PI / 2;
final double arrowLeft = drawingAngle - Math.PI / 2;
mArrowPath.moveTo(center + (float)Math.cos(arrowRight) * radius, center
+ (float)Math.sin(arrowRight) * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
mArrowPath.lineTo(center + (float)Math.cos(arrowLeft) * radius, center
+ (float)Math.sin(arrowLeft) * radius);
canvas.drawPath(mArrowPath, mArrowPaint);
drawCompassArrow(canvas, center, mCompassPaint, tipX, tipY, baseX, baseY, Color.RED);
drawCompassArrow(canvas, center, mCompassPaint, -tipX, -tipY, baseX, baseY, Color.GRAY);
gridPaint.setAlpha(255);
canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8, center + (sin * blipRadius)
- 8, gridPaint);
}
}
private void drawCompassArrow(Canvas canvas, int center, final Paint gridPaint, float tipX,
float tipY, float baseX, float baseY, int color) {
gridPaint.setStyle(Paint.Style.FILL_AND_STROKE);
gridPaint.setColor(color);
gridPaint.setAlpha(255);
mCompassPath.reset();
mCompassPath.moveTo(center + baseX, center + baseY);
mCompassPath.lineTo(center + tipX, center + tipY);
mCompassPath.lineTo(center - baseX, center - baseY);
mCompassPath.close();
canvas.drawPath(mCompassPath, gridPaint);
gridPaint.setStyle(Paint.Style.STROKE);
}
public void onAccuracyChanged(int sensor, int accuracy) {
}
/**
* Called when we get a new value from the compass
*
* @see android.hardware.SensorListener#onSensorChanged(int, float[])
*/
public void onSensorChanged(int sensor, float[] values) {
mOrientation = values[0];
double bearingToTarget = mBearing - mOrientation;
updateBearing(bearingToTarget);
postInvalidate();
}
/**
* Called when a location provider has a new location to report
*
* @see android.location.LocationListener#onLocationChanged(android.location.Location)
*/
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "radarview::onLocationChanged");
if (!mHaveLocation) {
mHaveLocation = true;
}
final long now = SystemClock.uptimeMillis();
boolean useLocation = false;
final String provider = location.getProvider();
if (LocationManager.GPS_PROVIDER.equals(provider)) {
// Use GPS if available
mLastGpsFixTime = SystemClock.uptimeMillis();
useLocation = true;
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
// Use network provider if GPS is getting stale
useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS;
if (mNetworkLocation == null) {
mNetworkLocation = new Location(location);
} else {
mNetworkLocation.set(location);
}
mLastGpsFixTime = 0L;
}
if (useLocation) {
mMyLocationLat = location.getLatitude();
mMyLocationLon = location.getLongitude();
mMyLocationAccuracy = location.getAccuracy();
mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon);
mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon);
updateDistance(mDistance);
double bearingToTarget = mBearing - mOrientation;
updateBearing(bearingToTarget);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
/**
* Called when a location provider has changed its availability.
*
* @see android.location.LocationListener#onStatusChanged(java.lang.String,
* int, android.os.Bundle)
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
//Log.d("GeoBeagle", "onStatusChanged " + provider + ", " + status);
if (LocationManager.GPS_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mGpsAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mGpsAvailable = false;
if (mNetworkLocation != null && mNetworkAvailable) {
// Fallback to network location
mLastGpsFixTime = 0L;
onLocationChanged(mNetworkLocation);
} else {
handleUnknownLocation();
}
break;
}
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mNetworkAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mNetworkAvailable = false;
if (!mGpsAvailable) {
handleUnknownLocation();
}
break;
}
}
}
/**
* Called when we no longer have a valid location.
*/
public void handleUnknownLocation() {
mHaveLocation = false;
mDistanceView.setText("");
mAccuracyView.setText("");
mBearingView.setText("");
}
/**
* Update state to reflect whether we are using metric or standard units.
*
* @param useMetric True if the display should use metric units
*/
public void setUseImperial(boolean useImperial) {
mUseMetric = !useImperial;
mLastScale = -1;
if (mHaveLocation) {
updateDistance(mDistance);
}
invalidate();
}
private void updateBearing(double bearing) {
bearing = (bearing + 720) % 360;
if (mHaveLocation) {
final String sBearing = ((int)bearing / 5) * 5 + mDegreesSymbol;
mBearingView.setText(sBearing);
}
}
/**
* Update our state to reflect a new distance to the target. This may
* require choosing a new scale for the radar rings.
*
* @param distanceKm The new distance to the target
* @param bearing
*/
private void updateDistance(double distanceKm) {
final double[] scaleChoices;
final float[] displayUnitsPerKm;
final String[] displayFormats;
String distanceStr = null;
String accuracyStr = null;
if (mUseMetric) {
scaleChoices = mMetricScaleChoices;
displayUnitsPerKm = mMetricDisplayUnitsPerKm;
displayFormats = mMetricDisplayFormats;
} else {
scaleChoices = mEnglishScaleChoices;
displayUnitsPerKm = mEnglishDisplayUnitsPerKm;
displayFormats = mEnglishDisplayFormats;
}
final int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
if (distanceKm < scaleChoices[i] || i == (count - 1)) {
String format = displayFormats[i];
double distanceDisplay = distanceKm * displayUnitsPerKm[i];
if (mLastScale != i) {
mLastScale = i;
}
mDistanceRatio = (float)(mDistance / scaleChoices[mLastScale]);
distanceStr = String.format(format, distanceDisplay);
break;
}
}
if (mMyLocationAccuracy != 0.0)
accuracyStr = formatDistance(scaleChoices, displayUnitsPerKm, displayFormats);
mDistanceView.setText(distanceStr);
mAccuracyView.setText("+/-" + accuracyStr);
}
private String formatDistance(final double[] scaleChoices, final float[] displayUnitsPerKm,
final String[] displayFormats) {
int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
final float myLocationAccuracyKm = mMyLocationAccuracy / 1000;
if (myLocationAccuracyKm < scaleChoices[i] || i == (count - 1)) {
final String format = displayFormats[i];
return String.format(format, myLocationAccuracyKm * displayUnitsPerKm[i]);
}
}
return "";
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import android.app.Activity;
public class MenuActionLogDnf extends MenuActionBase {
private final Activity mActivity;
public MenuActionLogDnf(Activity activity) {
super(R.string.menu_log_dnf);
mActivity = activity;
}
@Override
public void act() {
mActivity.showDialog(R.id.menu_log_dnf);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.activity.main.intents.IntentStarterViewUri;
public class MenuActionGoogleMaps extends MenuActionBase {
private final IntentStarterViewUri mIntentStarterViewUri;
public MenuActionGoogleMaps(IntentStarterViewUri intentStarterViewUri) {
super(R.string.menu_google_maps);
mIntentStarterViewUri = intentStarterViewUri;
}
@Override
public void act() {
mIntentStarterViewUri.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.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import android.app.Activity;
public class MenuActionLogFind extends MenuActionBase {
private final Activity mActivity;
public MenuActionLogFind(Activity activity) {
super(R.string.menu_log_find);
mActivity = activity;
}
@Override
public void act() {
mActivity.showDialog(R.id.menu_log_find);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender.FieldNoteResources;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import java.io.File;
public class GeoBeagleDelegate {
public static class LogFindClickListener implements OnClickListener {
private final GeoBeagle mGeoBeagle;
private final int mIdDialog;
LogFindClickListener(GeoBeagle geoBeagle, int idDialog) {
mGeoBeagle = geoBeagle;
mIdDialog = idDialog;
}
public void onClick(View v) {
mGeoBeagle.showDialog(mIdDialog);
}
}
static int ACTIVITY_REQUEST_TAKE_PICTURE = 1;
private final ActivitySaver mActivitySaver;
private final AppLifecycleManager mAppLifecycleManager;
private final CompassListener mCompassListener;
private final FieldNoteSender mFieldNoteSender;
private Geocache mGeocache;
private final GeocacheFactory mGeocacheFactory;
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory;
private final GeocacheViewer mGeocacheViewer;
private final IncomingIntentHandler mIncomingIntentHandler;
private final DbFrontend mDbFrontend;
private final MenuActions mMenuActions;
private final GeoBeagle mParent;
private final RadarView mRadarView;
private final Resources mResources;
private final SensorManager mSensorManager;
private final SharedPreferences mSharedPreferences;
private final WebPageAndDetailsButtonEnabler mWebPageButtonEnabler;
public GeoBeagleDelegate(ActivitySaver activitySaver, AppLifecycleManager appLifecycleManager,
CompassListener compassListener, FieldNoteSender fieldNoteSender, GeoBeagle parent,
GeocacheFactory geocacheFactory, GeocacheViewer geocacheViewer,
IncomingIntentHandler incomingIntentHandler, MenuActions menuActions,
GeocacheFromParcelFactory geocacheFromParcelFactory,
DbFrontend dbFrontend, RadarView radarView, Resources resources,
SensorManager sensorManager, SharedPreferences sharedPreferences,
WebPageAndDetailsButtonEnabler webPageButtonEnabler) {
mParent = parent;
mActivitySaver = activitySaver;
mAppLifecycleManager = appLifecycleManager;
mFieldNoteSender = fieldNoteSender;
mMenuActions = menuActions;
mResources = resources;
mSharedPreferences = sharedPreferences;
mRadarView = radarView;
mCompassListener = compassListener;
mSensorManager = sensorManager;
mGeocacheViewer = geocacheViewer;
mWebPageButtonEnabler = webPageButtonEnabler;
mGeocacheFactory = geocacheFactory;
mIncomingIntentHandler = incomingIntentHandler;
mDbFrontend = dbFrontend;
mGeocacheFromParcelFactory = geocacheFromParcelFactory;
}
public Geocache getGeocache() {
return mGeocache;
}
private void onCameraStart() {
String filename = "/sdcard/GeoBeagle/" + mGeocache.getId()
+ DateFormat.format(" yyyy-MM-dd kk.mm.ss.jpg", System.currentTimeMillis());
Log.d("GeoBeagle", "capturing image to " + filename);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));
mParent.startActivityForResult(intent, GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE);
}
public Dialog onCreateDialog(int idMenu) {
final FieldNoteResources fieldNoteResources = new FieldNoteResources(mResources, idMenu);
return mFieldNoteSender.createDialog(mGeocache.getId(), fieldNoteResources, mParent);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CAMERA && event.getRepeatCount() == 0) {
onCameraStart();
return true;
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
public void onPause() {
mAppLifecycleManager.onPause();
mActivitySaver.save(ActivityType.VIEW_CACHE, mGeocache);
mSensorManager.unregisterListener(mRadarView);
mSensorManager.unregisterListener(mCompassListener);
mDbFrontend.closeDatabase();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
mGeocache = mGeocacheFromParcelFactory.createFromBundle(savedInstanceState);
// Is this really needed???
// mWritableDatabase =
// mGeoBeagleSqliteOpenHelper.getWritableSqliteWrapper();
}
public void onResume() {
mRadarView.handleUnknownLocation();
mRadarView.setUseImperial(mSharedPreferences.getBoolean("imperial", false));
mAppLifecycleManager.onResume();
mSensorManager.registerListener(mRadarView, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mGeocache = mIncomingIntentHandler.maybeGetGeocacheFromIntent(mParent.getIntent(),
mGeocache, new LocationSaver(mDbFrontend));
// Possible fix for issue 53.
if (mGeocache == null) {
mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
}
mGeocacheViewer.set(mGeocache);
mWebPageButtonEnabler.check();
}
public void onSaveInstanceState(Bundle outState) {
// apparently there are cases where getGeocache returns null, causing
// crashes with 0.7.7/0.7.8.
if (mGeocache != null)
mGeocache.saveToBundle(outState);
}
public void setGeocache(Geocache geocache) {
mGeocache = geocache;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.database.LocationSaver;
import android.content.Intent;
public class IncomingIntentHandler {
private GeocacheFactory mGeocacheFactory;
private GeocacheFromIntentFactory mGeocacheFromIntentFactory;
IncomingIntentHandler(GeocacheFactory geocacheFactory,
GeocacheFromIntentFactory geocacheFromIntentFactory) {
mGeocacheFactory = geocacheFactory;
mGeocacheFromIntentFactory = geocacheFromIntentFactory;
}
Geocache maybeGetGeocacheFromIntent(Intent intent, Geocache defaultGeocache,
LocationSaver locationSaver) {
if (intent != null) {
final String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_VIEW) && intent.getType() == null) {
return mGeocacheFromIntentFactory
.viewCacheFromMapsIntent(intent, locationSaver);
} else if (action.equals(GeocacheListController.SELECT_CACHE)) {
Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
if (geocache == null)
geocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
return geocache;
}
}
}
return defaultGeocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
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) {
return createFromBundle(in.readBundle());
}
public Geocache createFromBundle(Bundle bundle) {
return mGeocacheFactory.create(bundle.getCharSequence(Geocache.ID), bundle
.getCharSequence(Geocache.NAME), bundle.getDouble(Geocache.LATITUDE), bundle
.getDouble(Geocache.LONGITUDE), mGeocacheFactory.sourceFromInt(bundle
.getInt(Geocache.SOURCE_TYPE)), bundle.getString(Geocache.SOURCE_NAME),
mGeocacheFactory.cacheTypeFromInt(bundle.getInt(Geocache.CACHE_TYPE)), bundle
.getInt(Geocache.DIFFICULTY), bundle.getInt(Geocache.TERRAIN), bundle
.getInt(Geocache.CONTAINER));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.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.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Intent;
public class IntentStarterGeo implements IntentStarter {
private final GeoBeagle mGeoBeagle;
private final Intent mIntent;
public IntentStarterGeo(GeoBeagle geoBeagle, Intent intent) {
mGeoBeagle = geoBeagle;
mIntent = intent;
}
public void startIntent() {
final Geocache geocache = mGeoBeagle.getGeocache();
mIntent.putExtra("latitude", (float)geocache.getLatitude());
mIntent.putExtra("longitude", (float)geocache.getLongitude());
mGeoBeagle.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.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.Context;
import java.net.URLEncoder;
import java.util.Locale;
public class GeocacheToGoogleMap implements GeocacheToUri {
private final Context mContext;
public GeocacheToGoogleMap(Context context) {
mContext = context;
}
/*
* (non-Javadoc)
* @see
* com.google.code.geobeagle.activity.main.intents.GeocacheToUri#convert
* (com.google.code.geobeagle.Geocache)
*/
public String convert(Geocache geocache) {
// "geo:%1$.5f,%2$.5f?name=cachename"
String idAndName = (String)geocache.getIdAndName();
idAndName = idAndName.replace("(", "[");
idAndName = idAndName.replace(")", "]");
idAndName = URLEncoder.encode(idAndName);
final String format = String.format(Locale.US, mContext
.getString(R.string.map_intent), geocache.getLatitude(), geocache.getLongitude(),
idAndName);
return format;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.res.Resources;
/*
* Convert a Geocache to the cache page url.
*/
public class GeocacheToCachePage implements GeocacheToUri {
private final Resources mResources;
public GeocacheToCachePage(Resources resources) {
mResources = resources;
}
// TODO: move strings into Provider enum.
public String convert(Geocache geocache) {
return String.format(mResources.getStringArray(R.array.cache_page_url)[geocache
.getContentProvider().toInt()], geocache.getShortId());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.activity.main.UriParser;
import android.content.Intent;
public class IntentFactory {
private final UriParser mUriParser;
public IntentFactory(UriParser uriParser) {
mUriParser = uriParser;
}
public Intent createIntent(String action, String uri) {
return new Intent(action, mUriParser.parse(uri));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.activity.main.GeoBeagle;
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,
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.activity.main.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.activity.main.intents;
import com.google.code.geobeagle.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.activity;
import com.google.code.geobeagle.Geocache;
import android.content.SharedPreferences.Editor;
public class ActivitySaver {
private final Editor mEditor;
static final String LAST_ACTIVITY = "lastActivity";
ActivitySaver(Editor editor) {
mEditor = editor;
}
public void save(ActivityType activityType) {
mEditor.putInt("lastActivity", activityType.toInt());
mEditor.commit();
}
public void save(ActivityType activityType, Geocache geocache) {
mEditor.putInt("lastActivity", activityType.toInt());
geocache.writeToPrefs(mEditor);
mEditor.commit();
}
}
| 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.model;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.GeocacheFactory.Source;
import android.location.Location;
public class GeocacheFromMyLocationFactory {
private final GeocacheFactory mGeocacheFactory;
private final LocationControlBuffered mLocationControl;
public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory,
LocationControlBuffered locationControl) {
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
}
public Geocache create() {
Location location = mLocationControl.getLocation();
if (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, CacheType.MY_LOCATION, 0, 0, 0);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.model;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import android.location.Location;
import android.util.FloatMath;
import java.util.Comparator;
public class GeocacheVector {
public static class LocationComparator implements Comparator<GeocacheVector> {
public int compare(GeocacheVector geocacheVector1, GeocacheVector geocacheVector2) {
final float d1 = geocacheVector1.getDistance();
final float d2 = geocacheVector2.getDistance();
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
}
// From http://www.anddev.org/viewtopic.php?p=20195.
public static float calculateDistanceFast(float lat1, float lon1, float lat2, float lon2) {
double dLat = Math.toRadians(lat2 - lat1);
double dLon = Math.toRadians(lon2 - lon1);
final float sinDLat = FloatMath.sin((float)(dLat / 2));
final float sinDLon = FloatMath.sin((float)(dLon / 2));
float a = sinDLat * sinDLat + FloatMath.cos((float)Math.toRadians(lat1))
* FloatMath.cos((float)Math.toRadians(lat2)) * sinDLon * sinDLon;
float c = (float)(2 * Math.atan2(FloatMath.sqrt(a), FloatMath.sqrt(1 - a)));
return 6371000 * c;
}
// TODO: distance formatter shouldn't be in every object.
private final Geocache mGeocache;
private float mDistance;
private final LocationControlBuffered mLocationControlBuffered;
float getDistance() {
return mDistance;
}
public void setDistance(float f) {
mDistance = f;
}
public GeocacheVector(Geocache geocache, LocationControlBuffered locationControlBuffered) {
mGeocache = geocache;
mLocationControlBuffered = locationControlBuffered;
}
public float getDistanceFast() {
Location here = mLocationControlBuffered.getLocation();
return calculateDistanceFast((float)here.getLatitude(), (float)here.getLongitude(),
(float)mGeocache.getLatitude(), (float)mGeocache.getLongitude());
}
public CharSequence getFormattedDistance(DistanceFormatter distanceFormatter,
BearingFormatter relativeBearingFormatter) {
// Use the slower, more accurate distance for display.
final float[] distanceAndBearing = mGeocache
.calculateDistanceAndBearing(mLocationControlBuffered.getLocation());
if (distanceAndBearing[0] == -1) {
return "";
}
final float azimuth = mLocationControlBuffered.getAzimuth();
final CharSequence formattedDistance = distanceFormatter
.formatDistance(distanceAndBearing[0]);
final String formattedBearing = relativeBearingFormatter.formatBearing(distanceAndBearing[1],
azimuth);
return formattedDistance + " " + formattedBearing;
}
public Geocache getGeocache() {
return mGeocache;
}
public CharSequence getId() {
return mGeocache.getId();
}
public CharSequence getName() {
return mGeocache.getName();
}
public CharSequence getFormattedAttributes() {
return mGeocache.getFormattedAttributes();
}
}
| 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.activity.cachelist.model;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.LocationControlBuffered;
import java.util.ArrayList;
public class GeocacheVectors {
private final ArrayList<GeocacheVector> mGeocacheVectorsList;
public GeocacheVectors(ArrayList<GeocacheVector> geocacheVectorsList) {
mGeocacheVectorsList = geocacheVectorsList;
}
public void add(GeocacheVector destinationVector) {
mGeocacheVectorsList.add(0, destinationVector);
}
public void addLocations(ArrayList<Geocache> geocaches,
LocationControlBuffered locationControlBuffered) {
for (Geocache geocache : geocaches) {
add(new GeocacheVector(geocache, locationControlBuffered));
}
}
public GeocacheVector get(int position) {
return mGeocacheVectorsList.get(position);
}
public ArrayList<GeocacheVector> getGeocacheVectorsList() {
return mGeocacheVectorsList;
}
public void remove(int position) {
mGeocacheVectorsList.remove(position);
}
public void reset(int size) {
mGeocacheVectorsList.clear();
mGeocacheVectorsList.ensureCapacity(size);
}
public int size() {
return mGeocacheVectorsList.size();
}
}
| 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.model;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.LocationControlBuffered;
import java.util.ArrayList;
public class CacheListData {
private final GeocacheVectors mGeocacheVectors;
public CacheListData(GeocacheVectors geocacheVectors) {
mGeocacheVectors = geocacheVectors;
}
public void add(ArrayList<Geocache> geocaches, LocationControlBuffered locationControlBuffered) {
mGeocacheVectors.reset(geocaches.size());
mGeocacheVectors.addLocations(geocaches, locationControlBuffered);
}
public ArrayList<GeocacheVector> get() {
return mGeocacheVectors.getGeocacheVectorsList();
}
public int size() {
return mGeocacheVectors.size();
}
}
| 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.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListPresenter;
import com.google.code.geobeagle.database.DbFrontend;
import android.app.Activity;
import android.content.Intent;
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 CacheListRefresh mCacheListRefresh;
private final GeocacheListController mController;
private final DbFrontend mDbFrontend;
private final ImportIntentManager mImportIntentManager;
private final GeocacheListPresenter mPresenter;
public CacheListDelegate(ImportIntentManager importIntentManager, ActivitySaver activitySaver,
CacheListRefresh cacheListRefresh, GeocacheListController geocacheListController,
GeocacheListPresenter geocacheListPresenter, DbFrontend dbFrontend) {
mActivitySaver = activitySaver;
mCacheListRefresh = cacheListRefresh;
mController = geocacheListController;
mPresenter = geocacheListPresenter;
mImportIntentManager = importIntentManager;
mDbFrontend = dbFrontend;
}
public boolean onContextItemSelected(MenuItem menuItem) {
return mController.onContextItemSelected(menuItem);
}
public void onCreate() {
mPresenter.onCreate();
}
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() {
mPresenter.onPause();
mController.onPause();
mActivitySaver.save(ActivityType.CACHE_LIST);
mDbFrontend.closeDatabase();
}
public void onResume() {
// TODO: No need to re-initialize these
mPresenter.onResume(mCacheListRefresh);
mController.onResume(mCacheListRefresh, mImportIntentManager.isImport());
}
}
| 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.context;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater;
import com.google.code.geobeagle.database.DbFrontend;
import android.widget.BaseAdapter;
public class ContextActionDelete implements ContextAction {
private final BaseAdapter mGeocacheListAdapter;
private final GeocacheVectors mGeocacheVectors;
private final TitleUpdater mTitleUpdater;
private final DbFrontend mDbFrontend;
public ContextActionDelete(BaseAdapter geocacheListAdapter, GeocacheVectors geocacheVectors,
TitleUpdater titleUpdater, DbFrontend dbFrontend) {
mGeocacheListAdapter = geocacheListAdapter;
mGeocacheVectors = geocacheVectors;
mTitleUpdater = titleUpdater;
mDbFrontend = dbFrontend;
}
public void act(int position) {
mDbFrontend.getCacheWriter().deleteCache(mGeocacheVectors.get(position).getId());
mGeocacheVectors.remove(position);
mGeocacheListAdapter.notifyDataSetChanged();
//TODO: How to get correct values?
mTitleUpdater.update(mGeocacheVectors.size(), mGeocacheVectors.size());
}
}
| 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.context;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.EditCacheActivity;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import android.content.Context;
import android.content.Intent;
public class ContextActionEdit implements ContextAction {
private final Context mContext;
private final GeocacheVectors mGeocacheVectors;
public ContextActionEdit(GeocacheVectors geocacheVectors, Context context) {
mGeocacheVectors = geocacheVectors;
mContext = context;
}
public void act(int position) {
Geocache selected = mGeocacheVectors.get(position).getGeocache();
Intent intent = new Intent(mContext, EditCacheActivity.class);
intent.putExtra("geocache", selected);
mContext.startActivity(intent);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.actions.context;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import android.content.Context;
import android.content.Intent;
public class ContextActionView implements ContextAction {
private final Context mContext;
private final GeocacheVectors mGeocacheVectors;
private final Intent mGeoBeagleMainIntent;
public ContextActionView(GeocacheVectors geocacheVectors, Context context, Intent intent) {
mGeocacheVectors = geocacheVectors;
mContext = context;
mGeoBeagleMainIntent = intent;
}
public void act(int position) {
mGeoBeagleMainIntent.putExtra("geocache", mGeocacheVectors.get(position).getGeocache())
.setAction(GeocacheListController.SELECT_CACHE);
mContext.startActivity(mGeoBeagleMainIntent);
}
}
| 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.context;
public interface ContextAction {
public void act(int position);
}
| 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.menu;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.database.LocationSaver;
public class MenuActionMyLocation extends MenuActionBase {
private final ErrorDisplayer mErrorDisplayer;
private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory;
private final CacheListRefresh mMenuActionRefresh;
private final LocationSaver mLocationSaver;
public MenuActionMyLocation(CacheListRefresh cacheListRefresh, ErrorDisplayer errorDisplayer,
GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) {
super(R.string.menu_add_my_location);
mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory;
mErrorDisplayer = errorDisplayer;
mMenuActionRefresh = cacheListRefresh;
mLocationSaver = locationSaver;
}
@Override
public void act() {
final Geocache myLocation = mGeocacheFromMyLocationFactory.create();
if (myLocation == null) {
mErrorDisplayer.displayError(R.string.current_location_null);
return;
}
mLocationSaver.saveLocation(myLocation);
mMenuActionRefresh.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.actions.menu;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.activity.cachelist.GpxImporterFactory;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.xmlimport.GpxImporter;
public class MenuActionSyncGpx extends MenuActionBase {
private Abortable mAbortable;
private final CacheListRefresh mCacheListRefresh;
private final GpxImporterFactory mGpxImporterFactory;
private final DbFrontend mDbFrontend;
public MenuActionSyncGpx(Abortable abortable, CacheListRefresh cacheListRefresh,
GpxImporterFactory gpxImporterFactory, DbFrontend dbFrontend) {
super(R.string.menu_sync);
mAbortable = abortable;
mCacheListRefresh = cacheListRefresh;
mGpxImporterFactory = gpxImporterFactory;
mDbFrontend = dbFrontend;
}
public void abort() {
mAbortable.abort();
}
public void act() {
final GpxImporter gpxImporter = mGpxImporterFactory.create(mDbFrontend.getCacheWriter());
mAbortable = gpxImporter;
gpxImporter.importGpxs(mCacheListRefresh);
}
}
| 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.menu;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh;
import com.google.code.geobeagle.database.FilterNearestCaches;
public class MenuActionToggleFilter extends MenuActionBase {
private final FilterNearestCaches mFilterNearestCaches;
private final CacheListRefresh mMenuActionRefresh;
public MenuActionToggleFilter(FilterNearestCaches filterNearestCaches,
CacheListRefresh cacheListRefresh) {
super(R.string.menu_toggle_filter);
mFilterNearestCaches = filterNearestCaches;
mMenuActionRefresh = cacheListRefresh;
}
public void act() {
mFilterNearestCaches.toggle();
mMenuActionRefresh.forceRefresh();
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.actions.menu;
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.presenter;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import java.util.ArrayList;
public interface SortStrategy {
public void sort(ArrayList<GeocacheVector> arrayList);
} | 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;
interface RefreshAction {
public void 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 class DistanceUpdater implements RefreshAction {
private final GeocacheListAdapter mGeocacheListAdapter;
public DistanceUpdater(GeocacheListAdapter geocacheListAdapter) {
mGeocacheListAdapter = geocacheListAdapter;
}
public void refresh() {
// Log.d("GeoBeagle", "notifyDataSetChanged");
mGeocacheListAdapter.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.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import android.util.Log;
public class CacheListRefresh implements Refresher {
public static class ActionManager {
private final ActionAndTolerance mActionAndTolerances[];
public ActionManager(ActionAndTolerance actionAndTolerances[]) {
mActionAndTolerances = actionAndTolerances;
}
public int getMinActionExceedingTolerance(IGpsLocation here, float azimuth, long now) {
int i;
for (i = 0; i < mActionAndTolerances.length; i++) {
if (mActionAndTolerances[i].exceedsTolerance(here, azimuth, now))
break;
}
return i;
}
public void performActions(IGpsLocation here, float azimuth, int startingAction, long now) {
for (int i = startingAction; i < mActionAndTolerances.length; i++) {
mActionAndTolerances[i].refresh();
mActionAndTolerances[i].updateLastRefreshed(here, azimuth, now);
}
}
}
public static class UpdateFlag {
private boolean mUpdateFlag = true;
public void setUpdatesEnabled(boolean enabled) {
Log.d("GeoBeagle", "Update enabled: " + enabled);
mUpdateFlag = enabled;
}
boolean updatesEnabled() {
return mUpdateFlag;
}
}
private final ActionManager mActionManager;
private final LocationControlBuffered mLocationControlBuffered;
private final CacheListDelegateDI.Timing mTiming;
private final UpdateFlag mUpdateFlag;
public CacheListRefresh(ActionManager actionManager, CacheListDelegateDI.Timing timing,
LocationControlBuffered locationControlBuffered, UpdateFlag updateFlag) {
mLocationControlBuffered = locationControlBuffered;
mTiming = timing;
mActionManager = actionManager;
mUpdateFlag = updateFlag;
}
public void forceRefresh() {
mTiming.start();
final long now = mTiming.getTime();
mActionManager.performActions(mLocationControlBuffered.getGpsLocation(),
mLocationControlBuffered.getAzimuth(), 0, now);
}
public void refresh() {
// TODO: Is this check still necessary?
/*
* if (!mSqliteWrapper.isOpen()) { Log.d("GeoBeagle",
* "Refresh: database is closed, punting."); return; }
*/
if (!mUpdateFlag.updatesEnabled())
return;
Log.d("GeoBeagle", "CacheListRefresh.refresh");
mTiming.start();
final long now = mTiming.getTime();
final IGpsLocation here = mLocationControlBuffered.getGpsLocation();
final float azimuth = mLocationControlBuffered.getAzimuth();
final int minActionExceedingTolerance = mActionManager.getMinActionExceedingTolerance(here,
azimuth, now);
mActionManager.performActions(here, azimuth, minActionExceedingTolerance, now);
}
}
| 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.CompassListener;
import android.hardware.SensorManager;
public class SensorManagerWrapper {
private CompassListener mCompassListener;
private final SensorManager mSensorManager;
public SensorManagerWrapper(SensorManager sensorManager) {
mSensorManager = sensorManager;
}
public void unregisterListener() {
mSensorManager.unregisterListener(mCompassListener);
}
public void registerListener(CompassListener compassListener, int sensorOrientation,
int sensorDelayUi) {
mCompassListener = compassListener;
mSensorManager.registerListener(compassListener, sensorOrientation, sensorDelayUi);
}
}
| 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.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.CacheListView;
import com.google.code.geobeagle.activity.cachelist.CompassListenerFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListView.ScrollListener;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController.CacheListOnCreateContextMenuListener;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.app.ListActivity;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
public class GeocacheListPresenter {
public static class CacheListRefreshLocationListener implements LocationListener {
private final CacheListRefresh mCacheListRefresh;
public CacheListRefreshLocationListener(CacheListRefresh cacheListRefresh) {
mCacheListRefresh = cacheListRefresh;
}
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "location changed");
mCacheListRefresh.refresh();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
static final int UPDATE_DELAY = 1000;
private final LocationListener mCombinedLocationListener;
private final CombinedLocationManager mCombinedLocationManager;
// private final SensorEventListener mCompassListener;
// private final SensorListener mCompassListener;
private final CompassListenerFactory mCompassListenerFactory;
private final DistanceFormatterManager mDistanceFormatterManager;
private final GeocacheListAdapter mGeocacheListAdapter;
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final GeocacheVectors mGeocacheVectors;
private final View mGpsStatusWidget;
private final ListActivity mListActivity;
private final LocationControlBuffered mLocationControlBuffered;
private final SensorManagerWrapper mSensorManagerWrapper;
private final UpdateGpsWidgetRunnable mUpdateGpsWidgetRunnable;
private final CacheListView.ScrollListener mScrollListener;
public GeocacheListPresenter(LocationListener combinedLocationListener,
CombinedLocationManager combinedLocationManager,
CompassListenerFactory compassListenerFactory,
DistanceFormatterManager distanceFormatterManager,
GeocacheListAdapter geocacheListAdapter,
GeocacheSummaryRowInflater geocacheSummaryRowInflater, GeocacheVectors geocacheVectors,
View gpsStatusWidget, ListActivity listActivity,
LocationControlBuffered locationControlBuffered,
SensorManagerWrapper sensorManagerWrapper,
UpdateGpsWidgetRunnable updateGpsWidgetRunnable, ScrollListener scrollListener) {
mCombinedLocationListener = combinedLocationListener;
mCombinedLocationManager = combinedLocationManager;
mCompassListenerFactory = compassListenerFactory;
mDistanceFormatterManager = distanceFormatterManager;
mGeocacheListAdapter = geocacheListAdapter;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
mGeocacheVectors = geocacheVectors;
mGpsStatusWidget = gpsStatusWidget;
mListActivity = listActivity;
mLocationControlBuffered = locationControlBuffered;
mUpdateGpsWidgetRunnable = updateGpsWidgetRunnable;
mSensorManagerWrapper = sensorManagerWrapper;
mScrollListener = scrollListener;
}
public void onCreate() {
mListActivity.setContentView(R.layout.cache_list);
final ListView listView = mListActivity.getListView();
listView.addHeaderView(mGpsStatusWidget);
mListActivity.setListAdapter(mGeocacheListAdapter);
listView.setOnCreateContextMenuListener(new CacheListOnCreateContextMenuListener(
mGeocacheVectors));
listView.setOnScrollListener(mScrollListener);
mUpdateGpsWidgetRunnable.run();
// final List<Sensor> sensorList =
// mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
// mCompassSensor = sensorList.get(0);
}
public void onPause() {
mCombinedLocationManager.removeUpdates();
mSensorManagerWrapper.unregisterListener();
}
public void onResume(CacheListRefresh cacheListRefresh) {
final CacheListRefreshLocationListener cacheListRefreshLocationListener = new CacheListRefreshLocationListener(
cacheListRefresh);
final CompassListener mCompassListener = mCompassListenerFactory.create(cacheListRefresh);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, mLocationControlBuffered);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, mCombinedLocationListener);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0,
cacheListRefreshLocationListener);
mDistanceFormatterManager.setFormatter();
// mSensorManager.registerListener(mCompassListener, mCompassSensor,
// SensorManager.SENSOR_DELAY_UI);
mSensorManagerWrapper.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
final boolean absoluteBearing = PreferenceManager
.getDefaultSharedPreferences(mListActivity).getBoolean("absolute-bearing", false);
mGeocacheSummaryRowInflater.setBearingFormatter(absoluteBearing);
}
}
| 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.presenter;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
public interface ToleranceStrategy {
public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now);
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now);
} | 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;
public class AbsoluteBearingFormatter implements BearingFormatter {
private static final String[] LETTERS = {
"N", "NE", "E", "SE", "S", "SW", "W", "NW"
};
public String formatBearing(float absBearing, float myHeading) {
return LETTERS[((((int)(absBearing) + 22 + 720) % 360) / 45)];
}
}
| Java |
/*
** 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.activity.cachelist.model.GeocacheVector;
import java.util.ArrayList;
public class NullSortStrategy implements SortStrategy {
public void sort(ArrayList<GeocacheVector> arrayList) {
return;
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.