code
stringlengths
3
1.18M
language
stringclasses
1 value
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.app.Dialog; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.Window; public class CacheListActivityHoneycomb extends GuiceActivity { private CacheListDelegate cacheListDelegate; public CacheListDelegate getCacheListDelegate() { return cacheListDelegate; } @Override public Dialog onCreateDialog(int idDialog) { super.onCreateDialog(idDialog); return cacheListDelegate.onCreateDialog(this, idDialog); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return cacheListDelegate.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return cacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "CacheListActivityHoneycomb onCreate"); requestWindowFeature(Window.FEATURE_PROGRESS); Injector injector = getInjector(); cacheListDelegate = injector.getInstance(CacheListDelegate.class); cacheListDelegate.onCreate(injector); Log.d("GeoBeagle", "Done creating CacheListActivityHoneycomb"); } @Override protected void onPause() { Log.d("GeoBeagle", "CacheListActivity onPause"); /* * cacheListDelegate closes the database, it must be called before * super.onPause because the guice activity onPause nukes the database * object from the guice map. */ cacheListDelegate.onPause(); super.onPause(); Log.d("GeoBeagle", "CacheListActivityHoneycomb onPauseComplete"); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); cacheListDelegate.onPrepareDialog(id, dialog); } @Override protected void onResume() { super.onResume(); SearchTarget searchTarget = getInjector().getInstance(SearchTarget.class); Log.d("GeoBeagle", "CacheListActivityHoneycomb onResume"); cacheListDelegate.onResume(searchTarget); } }
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.R; import com.google.code.geobeagle.activity.cachelist.actions.context.delete.ContextActionDeleteStore; 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.CacheListRefresh; import com.google.code.geobeagle.database.CacheSqlWriter; import com.google.inject.Inject; import com.google.inject.Provider; import roboguice.inject.ContextScoped; import android.app.Activity; @ContextScoped public class ContextActionDelete implements ContextAction { private final Activity activity; private final Provider<CacheSqlWriter> cacheWriterProvider; private final GeocacheVectors geocacheVectors; private final CacheListRefresh cacheListRefresh; private final ContextActionDeleteStore contextActionDeleteStore; @Inject public ContextActionDelete(GeocacheVectors geocacheVectors, Provider<CacheSqlWriter> cacheWriterProvider, Activity activity, ContextActionDeleteStore contextActionDeleteStore, CacheListRefresh cacheListRefresh) { this.geocacheVectors = geocacheVectors; this.cacheWriterProvider = cacheWriterProvider; this.activity = activity; this.contextActionDeleteStore = contextActionDeleteStore; this.cacheListRefresh = cacheListRefresh; } @Override public void act(int position) { GeocacheVector geocacheVector = geocacheVectors.get(position); String cacheName = geocacheVector.getName().toString(); String cacheId = geocacheVector.getId().toString(); contextActionDeleteStore.saveCacheToDelete(cacheId, cacheName); activity.showDialog(R.id.delete_cache); } public void delete() { String cacheId = contextActionDeleteStore.getCacheId(); cacheWriterProvider.get().deleteCache(cacheId); cacheListRefresh.forceRefresh(); } public CharSequence getConfirmDeleteBodyText() { return String.format(activity.getString(R.string.confirm_delete_body_text), contextActionDeleteStore.getCacheId(), contextActionDeleteStore.getCacheName()); } public CharSequence getConfirmDeleteTitle() { return String.format(activity.getString(R.string.confirm_delete_title), contextActionDeleteStore.getCacheId()); } }
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.delete; import com.google.inject.Inject; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; public class ContextActionDeleteStore { private final SharedPreferences sharedPreferences; static final String CACHE_TO_DELETE_NAME = "cache-to-delete-name"; static final String CACHE_TO_DELETE_ID = "cache-to-delete-id"; @Inject public ContextActionDeleteStore(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public void saveCacheToDelete(String cacheId, String cacheName) { Editor editor = sharedPreferences.edit(); editor.putString(CACHE_TO_DELETE_ID, cacheId); editor.putString(CACHE_TO_DELETE_NAME, cacheName); editor.commit(); } public String getCacheId() { return sharedPreferences.getString(CACHE_TO_DELETE_ID, null); } public String getCacheName() { return sharedPreferences.getString(CACHE_TO_DELETE_NAME, null); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.context.delete; import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete; import com.google.inject.Inject; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; public class OnClickOk implements OnClickListener { private final ContextActionDelete contextActionDelete; @Inject public OnClickOk(ContextActionDelete contextActionDelete) { this.contextActionDelete = contextActionDelete; } @Override public void onClick(DialogInterface dialog, int whichButton) { contextActionDelete.delete(); dialog.dismiss(); } }
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.delete; import com.google.code.geobeagle.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.actions.context.ContextActionDelete; import com.google.inject.Inject; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; public class ContextActionDeleteDialogHelper { private final ContextActionDelete contextActionDelete; private final OnClickOk onClickOk; private final Builder builder; private final LayoutInflater layoutInflater; private final OnClickCancelListener onClickCancelListener; @Inject public ContextActionDeleteDialogHelper(ContextActionDelete contextActionDelete, OnClickOk onClickOk, AlertDialog.Builder builder, LayoutInflater layoutInflater, OnClickCancelListener onClickCancelListener) { this.contextActionDelete = contextActionDelete; this.onClickOk = onClickOk; this.builder = builder; this.layoutInflater = layoutInflater; this.onClickCancelListener = onClickCancelListener; } public Dialog onCreateDialog() { View confirmDeleteCacheView = layoutInflater.inflate(R.layout.confirm_delete_cache, null); builder.setNegativeButton(R.string.confirm_delete_negative, onClickCancelListener); builder.setView(confirmDeleteCacheView); builder.setPositiveButton(R.string.delete_cache, onClickOk); return builder.create(); } public void onPrepareDialog(Dialog dialog) { CharSequence confirmDeleteTitle = contextActionDelete.getConfirmDeleteTitle(); dialog.setTitle(confirmDeleteTitle); TextView textView = (TextView)dialog.findViewById(R.id.delete_cache); textView.setText(contextActionDelete.getConfirmDeleteBodyText()); } }
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 com.google.inject.Inject; import android.content.Context; import android.content.Intent; public class ContextActionEdit implements ContextAction { private final Context mContext; private final GeocacheVectors mGeocacheVectors; @Inject 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 com.google.inject.Inject; import android.content.Context; import android.content.Intent; public class ContextActionView implements ContextAction { private final Context context; private final GeocacheVectors geocacheVectors; @Inject public ContextActionView(GeocacheVectors geocacheVectors, Context context) { this.geocacheVectors = geocacheVectors; this.context = context; } @Override public void act(int position) { Intent intent = new Intent(context, com.google.code.geobeagle.activity.compass.CompassActivity.class); intent.putExtra("geocache", geocacheVectors.get(position).getGeocache()).setAction( GeocacheListController.SELECT_CACHE); context.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; 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 android.app.Activity; public class NullCompassFrameHider implements CompassFrameHider { @Override public void hideCompassFrame(Activity activity) { } }
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.Action; import com.google.code.geobeagle.activity.EditCacheActivity; import com.google.code.geobeagle.activity.cachelist.model.GeocacheFromMyLocationFactory; import com.google.code.geobeagle.database.LocationSaver; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class MenuActionMyLocation implements Action { private final ErrorDisplayer mErrorDisplayer; private final GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory; private final LocationSaver mLocationSaver; private final Activity mActivity; @Inject public MenuActionMyLocation(Activity activity, ErrorDisplayer errorDisplayer, GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) { mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory; mErrorDisplayer = errorDisplayer; mLocationSaver = locationSaver; mActivity = activity; } @Override public void act() { final Geocache myLocation = mGeocacheFromMyLocationFactory.create(); if (myLocation == null) { mErrorDisplayer.displayError(R.string.current_location_null); return; } mLocationSaver.saveLocation(myLocation); final Intent intent = new Intent(mActivity, EditCacheActivity.class); intent.putExtra("geocache", myLocation); mActivity.startActivityForResult(intent, 0); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.actions.menu; import com.google.code.geobeagle.R; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ListActivity; public class HoneycombCompassFrameHider implements CompassFrameHider { @Override public void hideCompassFrame(Activity activity) { ListActivity listActivity = (ListActivity)activity; FragmentManager fragmentManager = listActivity.getFragmentManager(); Fragment compassFragment = fragmentManager.findFragmentById(R.id.compass_frame); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.hide(compassFragment); transaction.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.actions.menu; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.xmlimport.CacheSyncer; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import com.google.inject.Singleton; import android.util.Log; @Singleton public class MenuActionSyncGpx implements Action { private CacheSyncer cacheSyncer; private final Provider<CacheSyncer> cacheSyncerProvider; private boolean syncInProgress; @Inject public MenuActionSyncGpx(Injector injector) { cacheSyncerProvider = injector.getProvider(CacheSyncer.class); syncInProgress = false; } // For testing. public MenuActionSyncGpx(Provider<CacheSyncer> gpxImporterProvider) { cacheSyncerProvider = gpxImporterProvider; syncInProgress = false; } public void abort() { Log.d("GeoBeagle", "MenuActionSyncGpx aborting: " + syncInProgress); if (!syncInProgress) return; cacheSyncer.abort(); syncInProgress = false; } @Override public void act() { Log.d("GeoBeagle", "MenuActionSync importing"); cacheSyncer = cacheSyncerProvider.get(); cacheSyncer.syncGpxs(); syncInProgress = true; } }
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.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.actions.Action; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; public class MenuActionDeleteAllCaches implements Action { private final Activity activity; private final Builder builder; private final CacheListRefresh cacheListRefresh; private final Provider<DbFrontend> cbFrontendProvider; private final BCachingStartTime bcachingLastUpdated; private final CompassFrameHider compassFrameHider; @Inject public MenuActionDeleteAllCaches(CacheListRefresh cacheListRefresh, Activity activity, Provider<DbFrontend> dbFrontendProvider, AlertDialog.Builder builder, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { this.cbFrontendProvider = dbFrontendProvider; this.builder = builder; this.activity = activity; this.cacheListRefresh = cacheListRefresh; this.bcachingLastUpdated = bcachingLastUpdated; this.compassFrameHider = compassFrameHider; } @Override public void act() { buildAlertDialog(cbFrontendProvider, cacheListRefresh, bcachingLastUpdated, compassFrameHider).show(); } private AlertDialog buildAlertDialog(Provider<DbFrontend> dbFrontendProvider, CacheListRefresh cacheListRefresh, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { builder.setTitle(R.string.delete_all_title); final OnClickOkayListener onClickOkayListener = new OnClickOkayListener(activity, dbFrontendProvider, cacheListRefresh, bcachingLastUpdated, compassFrameHider); final DialogInterface.OnClickListener onClickCancelListener = new OnClickCancelListener(); builder.setMessage(R.string.confirm_delete_all) .setPositiveButton(R.string.delete_all_title, onClickOkayListener) .setNegativeButton(R.string.cancel, onClickCancelListener); AlertDialog alertDialog = builder.create(); alertDialog.setOwnerActivity(activity); return alertDialog; } }
Java
package com.google.code.geobeagle.activity.cachelist.actions.menu; import android.app.Activity; public interface CompassFrameHider { public void hideCompassFrame(Activity activity); }
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.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.inject.Provider; import android.app.Activity; import android.content.DialogInterface; class OnClickOkayListener implements DialogInterface.OnClickListener { private final CacheListRefresh cacheListRefresh; private final Provider<DbFrontend> dbFrontendProvider; private final BCachingStartTime bcachingLastUpdated; private final Activity activity; private final CompassFrameHider compassFrameHider; OnClickOkayListener(Activity activity, Provider<DbFrontend> dbFrontendProvider, CacheListRefresh cacheListRefresh, BCachingStartTime bcachingLastUpdated, CompassFrameHider compassFrameHider) { this.activity = activity; this.dbFrontendProvider = dbFrontendProvider; this.cacheListRefresh = cacheListRefresh; this.bcachingLastUpdated = bcachingLastUpdated; this.compassFrameHider = compassFrameHider; } void hideCompassFrame() { } @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); dbFrontendProvider.get().deleteAll(); bcachingLastUpdated.clearStartTime(); cacheListRefresh.forceRefresh(); compassFrameHider.hideCompassFrame(activity); } }
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; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.ProvisionException; import android.location.GpsSatellite; import android.location.GpsStatus; import android.location.LocationManager; import android.util.Log; class GpsStatusListener implements GpsStatus.Listener { private final InflatedGpsStatusWidget inflatedGpsStatusWidget; private final Provider<LocationManager> locationManagerProvider; @Inject public GpsStatusListener(InflatedGpsStatusWidget inflatedGpsStatusWidget, Provider<LocationManager> locationManagerProvider) { this.inflatedGpsStatusWidget = inflatedGpsStatusWidget; this.locationManagerProvider = locationManagerProvider; } @Override public void onGpsStatusChanged(int event) { try { GpsStatus gpsStatus = locationManagerProvider.get().getGpsStatus(null); int satelliteCount = 0; for (@SuppressWarnings("unused") GpsSatellite gpsSatellite : gpsStatus.getSatellites()) { satelliteCount++; } inflatedGpsStatusWidget.getDelegate().setProvider("SAT: " + satelliteCount); } catch (ProvisionException e) { Log.d("GeoBeagle", "Ignoring provision exception during onGpsStatusChanged: " + e); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.inject.Inject; import com.google.inject.Injector; public class DistanceUpdater implements RefreshAction { private final GeocacheListAdapter mGeocacheListAdapter; @Inject public DistanceUpdater(Injector injector) { mGeocacheListAdapter = injector.getInstance(GeocacheListAdapter.class); } public DistanceUpdater(GeocacheListAdapter geocacheListAdapter) { mGeocacheListAdapter = geocacheListAdapter; } @Override public void refresh() { 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 android.location.Location; import android.location.LocationListener; import android.os.Bundle; public class CacheListRefreshLocationListener implements LocationListener { private final CacheListRefresh mCacheListRefresh; public CacheListRefreshLocationListener(CacheListRefresh cacheListRefresh) { mCacheListRefresh = cacheListRefresh; } @Override public void onLocationChanged(Location location) { // Log.d("GeoBeagle", "location changed"); mCacheListRefresh.refresh(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } }
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.filter; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.database.filter.FilterProgressDialog; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.ProgressDialog; public class UpdateFilterMediator { private final CacheListRefresh cacheListRefresh; private final Provider<FilterProgressDialog> clearFilterProgressDialogProvider; private final UpdateFlag updateFlag; private final FilterCleanliness filterCleanliness; @Inject public UpdateFilterMediator(CacheListRefresh cacheListRefresh, UpdateFlag updateFlag, Provider<FilterProgressDialog> clearFilterProgressDialogProvider, FilterCleanliness filterCleanliness) { this.cacheListRefresh = cacheListRefresh; this.updateFlag = updateFlag; this.clearFilterProgressDialogProvider = clearFilterProgressDialogProvider; this.filterCleanliness = filterCleanliness; } public void startFiltering(String string) { updateFlag.setUpdatesEnabled(false); ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.setMessage(string); progressDialog.show(); } public void endFiltering() { filterCleanliness.markDirty(false); updateFlag.setUpdatesEnabled(true); cacheListRefresh.forceRefresh(); ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.dismiss(); } public void setProgressMessage(String message) { ProgressDialog progressDialog = clearFilterProgressDialogProvider.get(); progressDialog.setMessage(message); } }
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.filter; public enum UpdateFilterMessages { END_FILTERING { @Override void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj) { updateFilterMediator.endFiltering(); } }, SET_PROGRESS_MESSAGE { @Override void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj) { updateFilterMediator.setProgressMessage((String)obj); } }; public static UpdateFilterMessages fromOrd(int i) { return UpdateFilterMessages.values()[i]; } abstract void handleMessage(UpdateFilterMediator updateFilterMediator, Object obj); }
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.filter; import com.google.inject.Inject; import android.os.Handler; import android.os.Message; public class UpdateFilterHandler extends Handler { private final UpdateFilterMediator updateFilterMediator; @Inject UpdateFilterHandler(UpdateFilterMediator updateFilterMediator) { this.updateFilterMediator = updateFilterMediator; } @Override public void handleMessage(Message msg) { UpdateFilterMessages updateFilterMessage = UpdateFilterMessages.fromOrd(msg.what); updateFilterMessage.handleMessage(updateFilterMediator, msg.obj); } private void sendMessage(UpdateFilterMessages updateFilterMessage) { sendMessage(updateFilterMessage, null); } private void sendMessage(UpdateFilterMessages updateFilterMessage, String prompt) { sendMessage(obtainMessage(updateFilterMessage.ordinal(), prompt)); } public void endFiltering() { sendMessage(UpdateFilterMessages.END_FILTERING); } public void setProgressMessage(String string) { sendMessage(UpdateFilterMessages.SET_PROGRESS_MESSAGE, string); } }
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.CacheListCompassListener; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.activity.cachelist.CacheListViewScrollListener; import com.google.code.geobeagle.activity.cachelist.GeocacheListController.CacheListOnCreateContextMenuListener; import com.google.code.geobeagle.activity.cachelist.Pausable; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import com.google.code.geobeagle.activity.cachelist.ViewMenuAdder; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.filter.UpdateFilterMediator; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.code.geobeagle.database.filter.UpdateFilterWorker; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable; import com.google.code.geobeagle.location.CombinedLocationListener; import com.google.code.geobeagle.location.CombinedLocationManager; import com.google.code.geobeagle.shakewaker.ShakeWaker; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.app.Activity; import android.hardware.SensorManager; import android.location.LocationListener; import android.util.Log; import android.view.View; import android.widget.ListView; public class CacheListPresenter implements Pausable { static final int UPDATE_DELAY = 1000; private final LocationListener combinedLocationListener; private final CombinedLocationManager combinedLocationManager; private final Provider<CacheListCompassListener> cacheListCompassListenerProvider; private final GeocacheVectors geocacheVectors; private final InflatedGpsStatusWidget inflatedGpsStatusWidget; private final Activity activity; private final LocationControlBuffered locationControlBuffered; private final SensorManagerWrapper sensorManagerWrapper; private final UpdateGpsWidgetRunnable updateGpsWidgetRunnable; private final CacheListViewScrollListener scrollListener; private final GpsStatusListener gpsStatusListener; private final UpdateFilterWorker updateFilterWorker; private final FilterCleanliness filterCleanliness; private final ShakeWaker shakeWaker; private final UpdateFilterMediator updateFilterMediator; private final SearchTarget searchTarget; private final ListFragtivityOnCreateHandler listFragtivityOnCreateHandler; private final ViewMenuAdder viewMenuAdder; public CacheListPresenter(CombinedLocationListener combinedLocationListener, CombinedLocationManager combinedLocationManager, ListFragtivityOnCreateHandler listFragtivityOnCreateHandler, Provider<CacheListCompassListener> cacheListCompassListenerProvider, GeocacheVectors geocacheVectors, InflatedGpsStatusWidget inflatedGpsStatusWidget, Activity listActivity, LocationControlBuffered locationControlBuffered, SensorManagerWrapper sensorManagerWrapper, UpdateGpsWidgetRunnable updateGpsWidgetRunnable, CacheListViewScrollListener cacheListViewScrollListener, GpsStatusListener gpsStatusListener, UpdateFilterWorker updateFilterWorker, FilterCleanliness filterCleanliness, ShakeWaker shakeWaker, UpdateFilterMediator updateFilterMediator, SearchTarget searchTarget, ViewMenuAdder viewMenuAdder) { this.combinedLocationListener = combinedLocationListener; this.combinedLocationManager = combinedLocationManager; this.cacheListCompassListenerProvider = cacheListCompassListenerProvider; this.geocacheVectors = geocacheVectors; this.inflatedGpsStatusWidget = inflatedGpsStatusWidget; this.shakeWaker = shakeWaker; this.activity = listActivity; this.locationControlBuffered = locationControlBuffered; this.updateGpsWidgetRunnable = updateGpsWidgetRunnable; this.sensorManagerWrapper = sensorManagerWrapper; this.scrollListener = cacheListViewScrollListener; this.gpsStatusListener = gpsStatusListener; this.updateFilterWorker = updateFilterWorker; this.filterCleanliness = filterCleanliness; this.updateFilterMediator = updateFilterMediator; this.searchTarget = searchTarget; this.listFragtivityOnCreateHandler = listFragtivityOnCreateHandler; this.viewMenuAdder = viewMenuAdder; } @Inject public CacheListPresenter(Injector injector) { this.combinedLocationListener = injector.getInstance(CombinedLocationListener.class); this.combinedLocationManager = injector.getInstance(CombinedLocationManager.class); this.cacheListCompassListenerProvider = injector .getProvider(CacheListCompassListener.class); this.geocacheVectors = injector.getInstance(GeocacheVectors.class); this.inflatedGpsStatusWidget = injector.getInstance(InflatedGpsStatusWidget.class); this.shakeWaker = injector.getInstance(ShakeWaker.class); this.activity = injector.getInstance(Activity.class); this.locationControlBuffered = injector.getInstance(LocationControlBuffered.class); this.updateGpsWidgetRunnable = injector.getInstance(UpdateGpsWidgetRunnable.class); this.sensorManagerWrapper = injector.getInstance(SensorManagerWrapper.class); this.scrollListener = injector.getInstance(CacheListViewScrollListener.class); this.gpsStatusListener = injector.getInstance(GpsStatusListener.class); this.updateFilterWorker = injector.getInstance(UpdateFilterWorker.class); this.filterCleanliness = injector.getInstance(FilterCleanliness.class); this.updateFilterMediator = injector.getInstance(UpdateFilterMediator.class); this.searchTarget = injector.getInstance(SearchTarget.class); this.listFragtivityOnCreateHandler = injector .getInstance(ListFragtivityOnCreateHandler.class); this.viewMenuAdder = injector.getInstance(ViewMenuAdder.class); } public void onCreate() { listFragtivityOnCreateHandler.onCreateActivity(activity, this); } void setupListView(ListView listView) { NoCachesView noCachesView = (NoCachesView)listView.getEmptyView(); noCachesView.setSearchTarget(searchTarget); listView.addHeaderView((View)inflatedGpsStatusWidget.getTag()); listView.setOnCreateContextMenuListener(new CacheListOnCreateContextMenuListener( geocacheVectors, viewMenuAdder)); listView.setOnScrollListener(scrollListener); } public void onCreateFragment(Object listFragment) { listFragtivityOnCreateHandler.onCreateFragment(this, listFragment); } @Override public void onPause() { combinedLocationManager.removeUpdates(); sensorManagerWrapper.unregisterListener(); shakeWaker.unregister(); } public void onResume(CacheListRefresh cacheListRefresh) { if (filterCleanliness.isDirty()) { updateFilterMediator.startFiltering("Resetting filter"); updateFilterWorker.start(); } CacheListRefreshLocationListener cacheListRefreshLocationListener = new CacheListRefreshLocationListener( cacheListRefresh); CacheListCompassListener compassListener = cacheListCompassListenerProvider.get(); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, locationControlBuffered); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, combinedLocationListener); combinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, cacheListRefreshLocationListener); combinedLocationManager.addGpsStatusListener(gpsStatusListener); updateGpsWidgetRunnable.run(); sensorManagerWrapper.registerListener(compassListener, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); shakeWaker.register(); Log.d("GeoBeagle", "GeocacheListPresenter onResume done"); } }
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.IGpsLocation; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.Timing; import com.google.inject.Inject; import com.google.inject.ProvisionException; import com.google.inject.Singleton; import roboguice.inject.ContextScoped; import android.util.Log; @ContextScoped 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); } } } @Singleton 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 Timing mTiming; private final UpdateFlag mUpdateFlag; @Inject public CacheListRefresh(ActionManager actionManager, Timing timing, LocationControlBuffered locationControlBuffered, UpdateFlag updateFlag) { mLocationControlBuffered = locationControlBuffered; mTiming = timing; mActionManager = actionManager; mUpdateFlag = updateFlag; } public void forceRefresh() { mTiming.start(); if (!mUpdateFlag.updatesEnabled()) return; final long now = mTiming.getTime(); mActionManager.performActions(mLocationControlBuffered.getGpsLocation(), mLocationControlBuffered.getAzimuth(), 0, now); } @Override public void refresh() { if (!mUpdateFlag.updatesEnabled()) return; mTiming.start(); try { // Log.d("GeoBeagle", "REFRESH"); 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); } catch (ProvisionException e) { Log.d("GeoBeagle", "Ignoring provision exception during refresh: " + e); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.CompassListener; import com.google.inject.Inject; import android.hardware.SensorManager; public class SensorManagerWrapper { private CompassListener mCompassListener; private final SensorManager mSensorManager; @Inject 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; 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.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; public class AbsoluteBearingFormatter implements BearingFormatter { private static final String[] LETTERS = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" }; @Override 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.R; import com.google.inject.Inject; import android.app.Activity; import android.app.ListActivity; import android.widget.ListView; public class ListActivityOnCreateHandler implements ListFragtivityOnCreateHandler { private final GeocacheListAdapter geocacheListAdapter; @Inject public ListActivityOnCreateHandler(GeocacheListAdapter geocacheListAdapter) { this.geocacheListAdapter = geocacheListAdapter; } @Override public void onCreateActivity(Activity activity, CacheListPresenter cacheListPresenter) { ListActivity listActivity = (ListActivity)activity; listActivity.setContentView(R.layout.cache_list); ListView listView = listActivity.getListView(); cacheListPresenter.setupListView(listView); listActivity.setListAdapter(geocacheListAdapter); } @Override public void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam) { } }
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
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.formatting.DistanceFormatter; public interface HasDistanceFormatter { public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.GeoBeagleApplication; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.cachelist.model.CacheListData; import com.google.inject.Inject; public class AdapterCachesSorter implements RefreshAction { private final CacheListData mCacheListData; private final LocationControlBuffered mLocationControlBuffered; private final Timing mTiming; @Inject public AdapterCachesSorter(CacheListData cacheListData, Timing timing, LocationControlBuffered locationControlBuffered) { mCacheListData = cacheListData; mTiming = timing; mLocationControlBuffered = locationControlBuffered; } @Override public void refresh() { mLocationControlBuffered.getSortStrategy().sort(mCacheListData.get()); mTiming.lap("sort time"); GeoBeagleApplication.timing.lap("START TIME TO FIRST REFRESH"); // Debug.stopMethodTracing(); } }
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.IGpsLocation; public class LocationTolerance implements ToleranceStrategy { private IGpsLocation mLastRefreshLocation; private final float mLocationTolerance; private final int mMinTimeBetweenRefresh; private long mLastRefreshTime; public LocationTolerance(float locationTolerance, IGpsLocation lastRefreshed, int minTimeBetweenRefresh) { mLocationTolerance = locationTolerance; mLastRefreshLocation = lastRefreshed; mMinTimeBetweenRefresh = minTimeBetweenRefresh; mLastRefreshTime = 0; } @Override public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { if (now < mLastRefreshTime + mMinTimeBetweenRefresh) return false; final float distanceTo = here.distanceTo(mLastRefreshLocation); // Log.d("GeoBeagle", "distance, tolerance: " + distanceTo + ", " + // mLocationTolerance); final boolean fExceedsTolerance = distanceTo >= mLocationTolerance; return fExceedsTolerance; } @Override public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { // Log.d("GeoBeagle", "updateLastRefreshed here: " + here); mLastRefreshLocation = here; mLastRefreshTime = 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.Geocache; import com.google.code.geobeagle.LocationControlBuffered; import com.google.code.geobeagle.Timing; import com.google.code.geobeagle.activity.cachelist.ActivityVisible; import com.google.code.geobeagle.activity.cachelist.model.CacheListData; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.database.filter.FilterNearestCaches; import com.google.inject.Inject; import com.google.inject.Provider; import android.location.Location; import java.util.ArrayList; public class SqlCacheLoader implements RefreshAction { private final CacheListData cacheListData; private final FilterNearestCaches filterNearestCaches; private final Provider<DbFrontend> dbFrontendProvider; private final LocationControlBuffered locationControlBuffered; private final Timing timing; private final TitleUpdater titleUpdater; private final ActivityVisible activityVisible; @Inject public SqlCacheLoader(Provider<DbFrontend> dbFrontendProvider, FilterNearestCaches filterNearestCaches, CacheListData cacheListData, LocationControlBuffered locationControlBuffered, TitleUpdater titleUpdater, Timing timing, ActivityVisible activityVisible) { this.dbFrontendProvider = dbFrontendProvider; this.filterNearestCaches = filterNearestCaches; this.cacheListData = cacheListData; this.locationControlBuffered = locationControlBuffered; this.timing = timing; this.titleUpdater = titleUpdater; this.activityVisible = activityVisible; } @Override public void refresh() { if (!activityVisible.getVisible()) return; Location location = locationControlBuffered.getLocation(); double latitude = 0; double longitude = 0; if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } // Log.d("GeoBeagle", "Location: " + location); DbFrontend dbFrontend = dbFrontendProvider.get(); ArrayList<Geocache> geocaches = dbFrontend.loadCaches(latitude, longitude, filterNearestCaches.getWhereFactory()); timing.lap("SQL time"); cacheListData.add(geocaches, locationControlBuffered); timing.lap("add to list time"); int nearestCachesCount = cacheListData.size(); titleUpdater.update(dbFrontend.countAll(), nearestCachesCount); } }
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 com.google.code.geobeagle.activity.cachelist.model.GeocacheVector.LocationComparator; import com.google.inject.Inject; import java.util.ArrayList; import java.util.Collections; public class DistanceSortStrategy implements SortStrategy { private final LocationComparator mLocationComparator; @Inject public DistanceSortStrategy(LocationComparator locationComparator) { mLocationComparator = locationComparator; } @Override public void sort(ArrayList<GeocacheVector> geocacheVectors) { for (GeocacheVector geocacheVector : geocacheVectors) { geocacheVector.setDistance(geocacheVector.getDistanceFast()); } Collections.sort(geocacheVectors, mLocationComparator); } }
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.Timing; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import com.google.code.geobeagle.database.filter.FilterNearestCaches; import com.google.inject.Inject; import android.app.Activity; public class TitleUpdater { private final FilterNearestCaches mFilterNearestCaches; private final Activity mActivity; private final Timing mTiming; private final SearchTarget mSearchTarget; @Inject public TitleUpdater(Activity activity, FilterNearestCaches filterNearestCaches, Timing timing, SearchTarget searchTarget) { mActivity = activity; mFilterNearestCaches = filterNearestCaches; mTiming = timing; mSearchTarget = searchTarget; } public void update(int sqlCount, int nearestCachesCount) { mActivity.setTitle(mSearchTarget.getTitle() + mActivity.getString(mFilterNearestCaches.getTitleText(), nearestCachesCount, sqlCount)); mTiming.lap("update title 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.activity.cachelist.presenter; import com.google.code.geobeagle.R; import com.google.inject.Inject; import android.app.Activity; import android.app.ListFragment; import android.widget.ListView; public class ListFragmentOnCreateHandler implements ListFragtivityOnCreateHandler { private final GeocacheListAdapter geocacheListAdapter; @Inject public ListFragmentOnCreateHandler(GeocacheListAdapter geocacheListAdapter) { this.geocacheListAdapter = geocacheListAdapter; } @Override public void onCreateActivity(Activity listActivity, CacheListPresenter cacheListPresenter) { listActivity.setContentView(R.layout.cache_list_fragment); } @Override public void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam) { ListFragment listFragment = (ListFragment)listFragmentParam; ListView listView = listFragment.getListView(); cacheListPresenter.setupListView(listView); listFragment.setListAdapter(geocacheListAdapter); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.IGpsLocation; public class ActionAndTolerance { private final RefreshAction mRefreshAction; private final ToleranceStrategy mToleranceStrategy; public ActionAndTolerance(RefreshAction refreshAction, ToleranceStrategy toleranceStrategy) { mRefreshAction = refreshAction; mToleranceStrategy = toleranceStrategy; } public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now) { return mToleranceStrategy.exceedsTolerance(here, azimuth, now); } public void refresh() { mRefreshAction.refresh(); } public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { mToleranceStrategy.updateLastRefreshed(here, azimuth, 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 android.app.Activity; import android.app.ListActivity; public interface ListFragtivityOnCreateHandler { void onCreateActivity(Activity listActivity, CacheListPresenter cacheListPresenter); void onCreateFragment(CacheListPresenter cacheListPresenter, Object listFragmentParam); }
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.ActivityVisible; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater; import com.google.inject.Inject; import com.google.inject.Injector; import roboguice.inject.ContextScoped; import android.graphics.Color; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; @ContextScoped public class GeocacheListAdapter extends BaseAdapter { //TODO(sng): Rename to CacheListAdapter. private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater; private final GeocacheVectors mGeocacheVectors; private final ActivityVisible mActivityVisible; private CharSequence mSelected; public GeocacheListAdapter(GeocacheVectors geocacheVectors, GeocacheSummaryRowInflater geocacheSummaryRowInflater, ActivityVisible activityVisible) { mGeocacheVectors = geocacheVectors; mGeocacheSummaryRowInflater = geocacheSummaryRowInflater; mActivityVisible = activityVisible; } @Inject public GeocacheListAdapter(Injector injector) { mGeocacheVectors = injector.getInstance(GeocacheVectors.class); mGeocacheSummaryRowInflater = injector.getInstance(GeocacheSummaryRowInflater.class); mActivityVisible = injector.getInstance(ActivityVisible.class); } @Override public int getCount() { return mGeocacheVectors.size(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view = mGeocacheSummaryRowInflater.inflate(convertView); if (!mActivityVisible.getVisible()) { // Log.d("GeoBeagle", // "Not visible, punting any real work on getView"); return view; } mGeocacheSummaryRowInflater.setData(view, mGeocacheVectors.get(position)); // ListView listView = (ListView)parent; // boolean isChecked = listView.isItemChecked(position + 1); boolean isChecked = mGeocacheVectors.get(position).getId().equals(mSelected); view.setBackgroundColor(isChecked ? Color.DKGRAY : Color.TRANSPARENT); return view; } public void setSelected(int position) { mSelected = mGeocacheVectors.get(position).getId(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; public class RelativeBearingFormatter implements BearingFormatter { private static final String[] ARROWS = { "^", ">", "v", "<", }; @Override public String formatBearing(float absBearing, float myHeading) { return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)]; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.activity.cachelist.SearchTarget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.util.AttributeSet; import android.webkit.WebSettings; import android.webkit.WebView; public class NoCachesView extends WebView { private static final String NO_CACHES_FOUND_HTML = "file:///android_asset/no_caches_found.html"; private static final String NO_CACHES = "file:///android_asset/no_caches.html"; private SearchTarget searchTarget; public NoCachesView(Context context) { super(context); setup(); } public NoCachesView(Context context, AttributeSet attrs) { super(context, attrs); setup(); } public NoCachesView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); setup(); } @Override public void onDraw(Canvas canvas) { // Log.d("GeoBeagle", "getUrl: " + getUrl()); if (searchTarget == null || searchTarget.getTarget() == null) { if (getUrl() == null || 0 != getUrl().compareTo(NO_CACHES)) loadUrl(NO_CACHES); } else if (getUrl() == null || 0 != getUrl().compareTo(NO_CACHES_FOUND_HTML)) { loadUrl(NO_CACHES_FOUND_HTML); } super.onDraw(canvas); } public void setSearchTarget(SearchTarget searchTarget) { this.searchTarget = searchTarget; } private void setup() { WebSettings webSettings = getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setSupportZoom(false); setBackgroundColor(Color.BLACK); } }
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.IGpsLocation; public class LocationAndAzimuthTolerance implements ToleranceStrategy { private float mLastAzimuth; private final LocationTolerance mLocationTolerance; public LocationAndAzimuthTolerance(LocationTolerance locationTolerance, float lastAzimuth) { mLocationTolerance = locationTolerance; mLastAzimuth = lastAzimuth; } @Override public boolean exceedsTolerance(IGpsLocation here, float currentAzimuth, long now) { if (mLastAzimuth != currentAzimuth) { // Log.d("GeoBeagle", "new azimuth: " + currentAzimuth); mLastAzimuth = currentAzimuth; return true; } return mLocationTolerance.exceedsTolerance(here, currentAzimuth, now); } @Override public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) { mLocationTolerance.updateLastRefreshed(here, azimuth, now); mLastAzimuth = azimuth; } }
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.view; import android.graphics.Color; import android.graphics.Paint; import android.widget.TextView; public class NameFormatter { public void format(TextView name, boolean available, boolean archived) { if (archived) { name.setTextColor(Color.rgb(200, 0, 0)); name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); return; } if (!available) { name.setTextColor(Color.WHITE); name.setPaintFlags(name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); return; } name.setTextColor(Color.WHITE); name.setPaintFlags(name.getPaintFlags() & ~Paint.STRIKE_THRU_TEXT_FLAG); } }
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.view; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GraphicsGenerator; import com.google.code.geobeagle.GraphicsGenerator.AttributesPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlay; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.ListViewBitmapCopier; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.graphics.drawable.Drawable; import android.widget.ImageView; import android.widget.TextView; class RowViews { private final TextView mAttributes; private final TextView mCacheName; private final TextView mDistance; private final ImageView mIcon; private final GraphicsGenerator.IconOverlayFactory mIconOverlayFactory; private final TextView mId; private final NameFormatter mNameFormatter; RowViews(TextView attributes, TextView cacheName, TextView distance, ImageView icon, TextView id, IconOverlayFactory iconOverlayFactory, NameFormatter nameFormatter) { mAttributes = attributes; mCacheName = cacheName; mDistance = distance; mIcon = icon; mId = id; mIconOverlayFactory = iconOverlayFactory; mNameFormatter = nameFormatter; } void set(GeocacheVector geocacheVector, BearingFormatter relativeBearingFormatter, DistanceFormatter distanceFormatter, ListViewBitmapCopier listViewBitmapCopier, IconRenderer iconRenderer, AttributesPainter attributesPainter) { Geocache geocache = geocacheVector.getGeocache(); IconOverlay iconOverlay = mIconOverlayFactory.create(geocache, false); mNameFormatter.format(mCacheName, geocache.getAvailable(), geocache.getArchived()); final Drawable icon = iconRenderer.renderIcon(geocache.getDifficulty(), geocache .getTerrain(), geocache.getCacheType().icon(), iconOverlay, listViewBitmapCopier, attributesPainter); mIcon.setImageDrawable(icon); mId.setText(geocacheVector.getId()); mAttributes.setText(geocacheVector.getFormattedAttributes()); mCacheName.setText(geocacheVector.getName()); mDistance.setText(geocacheVector.getFormattedDistance(distanceFormatter, relativeBearingFormatter)); } }
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.view; import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter; import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory; import com.google.code.geobeagle.GraphicsGenerator.IconRenderer; import com.google.code.geobeagle.GraphicsGenerator.ListViewBitmapCopier; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.TextView; public class GeocacheSummaryRowInflater { private final Provider<BearingFormatter> mBearingFormatterProvider; private final Provider<DistanceFormatter> mDistanceFormatterProvider; private final IconOverlayFactory mIconOverlayFactory; private final IconRenderer mIconRenderer; private final LayoutInflater mLayoutInflater; private final ListViewBitmapCopier mListViewBitmapCopier; private final NameFormatter mNameFormatter; private final DifficultyAndTerrainPainter mDifficultyAndTerrainPainter; public GeocacheSummaryRowInflater(LayoutInflater layoutInflater, Provider<DistanceFormatter> distanceFormatterProvider, Provider<BearingFormatter> bearingFormatterProvider, IconRenderer iconRenderer, ListViewBitmapCopier listViewBitmapCopier, IconOverlayFactory iconOverlayFactory, NameFormatter nameFormatter, DifficultyAndTerrainPainter difficultyAndTerrainPainter) { mLayoutInflater = layoutInflater; mDistanceFormatterProvider = distanceFormatterProvider; mBearingFormatterProvider = bearingFormatterProvider; mIconRenderer = iconRenderer; mListViewBitmapCopier = listViewBitmapCopier; mIconOverlayFactory = iconOverlayFactory; mNameFormatter = nameFormatter; mDifficultyAndTerrainPainter = difficultyAndTerrainPainter; } @Inject public GeocacheSummaryRowInflater(Injector injector) { mLayoutInflater = injector.getInstance(LayoutInflater.class); mDistanceFormatterProvider = injector.getProvider(DistanceFormatter.class); mBearingFormatterProvider = injector.getProvider(BearingFormatter.class); mIconRenderer = injector.getInstance(IconRenderer.class); mListViewBitmapCopier = injector.getInstance(ListViewBitmapCopier.class); mIconOverlayFactory = injector.getInstance(IconOverlayFactory.class); mNameFormatter = injector.getInstance(NameFormatter.class); mDifficultyAndTerrainPainter = injector.getInstance(DifficultyAndTerrainPainter.class); } public View inflate(View convertView) { if (convertView != null) return convertView; // Log.d("GeoBeagle", "SummaryRow::inflate(" + convertView + ")"); View view = mLayoutInflater.inflate(R.layout.cache_row, null); RowViews rowViews = new RowViews((TextView)view.findViewById(R.id.txt_gcattributes), ((TextView)view.findViewById(R.id.txt_cache)), ((TextView)view .findViewById(R.id.distance)), ((ImageView)view .findViewById(R.id.gc_row_icon)), ((TextView)view .findViewById(R.id.txt_gcid)), mIconOverlayFactory, mNameFormatter); view.setTag(rowViews); return view; } public void setData(View view, GeocacheVector geocacheVector) { ((RowViews)view.getTag()).set(geocacheVector, mBearingFormatterProvider.get(), mDistanceFormatterProvider.get(), mListViewBitmapCopier, mIconRenderer, mDifficultyAndTerrainPainter); } }
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.inject.Injector; import roboguice.activity.GuiceListActivity; import android.app.Dialog; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ListView; public class CacheListActivity extends GuiceListActivity { private CacheListDelegate cacheListDelegate; public CacheListDelegate getCacheListDelegate() { return cacheListDelegate; } @Override public boolean onContextItemSelected(MenuItem item) { return cacheListDelegate.onContextItemSelected(item) || super.onContextItemSelected(item); } @Override public Dialog onCreateDialog(int idDialog) { super.onCreateDialog(idDialog); return cacheListDelegate.onCreateDialog(this, idDialog); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); return cacheListDelegate.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return cacheListDelegate.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("GeoBeagle", "CacheListActivity onCreate"); requestWindowFeature(Window.FEATURE_PROGRESS); int sdkVersion = Integer.parseInt(Build.VERSION.SDK); if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) { startActivity(new Intent(this, CacheListActivityHoneycomb.class)); finish(); return; } Injector injector = this.getInjector(); cacheListDelegate = injector.getInstance(CacheListDelegate.class); cacheListDelegate.onCreate(injector); Log.d("GeoBeagle", "Done creating CacheListActivity"); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); cacheListDelegate.onListItemClick(position); } @Override protected void onPause() { Log.d("GeoBeagle", "CacheListActivity onPause"); /* * cacheListDelegate closes the database, it must be called before * super.onPause because the guice activity onPause nukes the database * object from the guice map. */ cacheListDelegate.onPause(); super.onPause(); Log.d("GeoBeagle", "CacheListActivity onPauseComplete"); } @Override protected void onPrepareDialog(int id, Dialog dialog) { super.onPrepareDialog(id, dialog); cacheListDelegate.onPrepareDialog(id, dialog); } @Override protected void onResume() { super.onResume(); SearchTarget searchTarget = getInjector().getInstance(SearchTarget.class); Log.d("GeoBeagle", "CacheListActivity onResume"); cacheListDelegate.onResume(searchTarget); } }
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.R; import com.google.code.geobeagle.actions.MenuActionBase; import com.google.code.geobeagle.actions.MenuActionMap; 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.cachelist.actions.menu.MenuActionDeleteAllCaches; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionMyLocation; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx; import com.google.inject.Inject; import com.google.inject.Injector; import android.content.res.Resources; public class CacheListMenuActions extends MenuActions { @Inject public CacheListMenuActions(Injector injector, Resources resources) { super(resources); add(new MenuActionBase(R.string.menu_sync, injector.getInstance(MenuActionSyncGpx.class))); add(new MenuActionBase(R.string.menu_delete_all_caches, injector.getInstance(MenuActionDeleteAllCaches.class))); add(new MenuActionBase(R.string.menu_add_my_location, injector.getInstance(MenuActionMyLocation.class))); add(new MenuActionBase(R.string.menu_search_online, injector.getInstance(MenuActionSearchOnline.class))); add(new MenuActionBase(R.string.menu_map, injector.getInstance(MenuActionMap.class))); add(new MenuActionBase(R.string.menu_settings, injector.getInstance(MenuActionSettings.class))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.R; import android.view.ContextMenu; public class ViewMenuAdderPreHoneycomb implements ViewMenuAdder { @Override public void addViewMenu(ContextMenu menu) { menu.add(0, GeocacheListController.MENU_VIEW, 0, R.string.context_menu_view); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; public interface Pausable { void onPause(); }
Java
package com.google.code.geobeagle.activity.cachelist; import android.view.ContextMenu; // TODO(sng): Rename to CacheListController. public class ViewMenuAdderHoneycomb implements ViewMenuAdder { @Override public void addViewMenu(ContextMenu 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.cachelist; import com.google.inject.Singleton; @Singleton public class SearchTarget { private String target; public void setTarget(String target) { this.target = target; } public String getTarget() { return target; } public String getTitle() { if (target == null) { return ""; } return "Searching: '" + target + "'; "; } }
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.view.ContextMenu; public interface ViewMenuAdder { abstract void addViewMenu(ContextMenu menu); }
Java
package com.google.code.geobeagle.activity.cachelist; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.inject.Inject; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; public class CacheListViewScrollListener implements OnScrollListener { private final UpdateFlag mUpdateFlag; @Inject public CacheListViewScrollListener(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); } }
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.OnClickCancelListener; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSms; import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSmsFactory; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger.OnClickOk; import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLoggerFactory; import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache; import com.google.code.geobeagle.activity.compass.fieldnotes.OnClickOkFactory; import com.google.inject.Inject; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.view.LayoutInflater; import android.view.View; import android.widget.EditText; import java.text.DateFormat; import java.util.Date; public class LogFindDialogHelper { private static final DateFormat mLocalDateFormat = DateFormat .getTimeInstance(DateFormat.MEDIUM); private final DialogHelperSmsFactory dialogHelperSmsFactory; private final FieldnoteLoggerFactory fieldnoteLoggerFactory; private final OnClickOkFactory onClickOkFactory; private final OnClickCancelListener onClickCancelListener; private final HasGeocache hasGeocache; @Inject LogFindDialogHelper(DialogHelperSmsFactory dialogHelperSmsFactory, FieldnoteLoggerFactory fieldnoteLoggerFactory, OnClickOkFactory onClickOkFactory, OnClickCancelListener onClickCancelListener, HasGeocache hasGeocache) { this.dialogHelperSmsFactory = dialogHelperSmsFactory; this.fieldnoteLoggerFactory = fieldnoteLoggerFactory; this.onClickOkFactory = onClickOkFactory; this.onClickCancelListener = onClickCancelListener; this.hasGeocache = hasGeocache; } public void onPrepareDialog(Activity activity, int id, Dialog dialog) { CharSequence cacheId = hasGeocache.get(activity).getId(); boolean fDnf = id == R.id.menu_log_dnf; DialogHelperSms dialogHelperSms = dialogHelperSmsFactory.create(cacheId.length(), fDnf); FieldnoteLogger fieldnoteLogger = fieldnoteLoggerFactory.create(dialogHelperSms); fieldnoteLogger.onPrepareDialog(dialog, mLocalDateFormat.format(new Date()), fDnf); } public Dialog onCreateDialog(Activity activity, int id) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); View fieldnoteDialogView = LayoutInflater.from(activity).inflate(R.layout.fieldnote, null); boolean fDnf = id == R.id.menu_log_dnf; OnClickOk onClickOk = onClickOkFactory.create( (EditText)fieldnoteDialogView.findViewById(R.id.fieldnote), fDnf); builder.setTitle(R.string.field_note_title); builder.setView(fieldnoteDialogView); builder.setNegativeButton(R.string.cancel, onClickCancelListener); builder.setPositiveButton(R.string.log_cache, onClickOk); AlertDialog alertDialog = builder.create(); return alertDialog; } }
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.R; import com.google.code.geobeagle.actions.ContextActions; import com.google.code.geobeagle.activity.cachelist.actions.menu.MenuActionSyncGpx; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView.AdapterContextMenuInfo; public class GeocacheListController { public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener { private final GeocacheVectors mGeocacheVectors; private final ViewMenuAdder mViewMenuAdder; public CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors, ViewMenuAdder viewMenuAdder) { mGeocacheVectors = geocacheVectors; mViewMenuAdder = viewMenuAdder; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; if (acmi.position > 0) { menu.setHeaderTitle(mGeocacheVectors.get(acmi.position - 1).getId()); mViewMenuAdder.addViewMenu(menu); menu.add(0, MENU_EDIT, 1, R.string.context_menu_edit); menu.add(0, MENU_DELETE, 2, R.string.context_menu_delete); } } } static final int MENU_EDIT = 0; static final int MENU_DELETE = 1; static final int MENU_VIEW = 2; public static final String SELECT_CACHE = "SELECT_CACHE"; private final CacheListRefresh mCacheListRefresh; private final AbortState mAborter; private final Provider<MenuActionSyncGpx> mMenuActionSyncGpxProvider; private final Provider<CacheListMenuActions> mCacheListMenuActionsProvider; private final Provider<ContextActions> mContextActionsProvider; @Inject public GeocacheListController(Injector injector) { mCacheListRefresh = injector.getInstance(CacheListRefresh.class); mAborter = injector.getInstance(AbortState.class); mMenuActionSyncGpxProvider = injector.getProvider(MenuActionSyncGpx.class); mCacheListMenuActionsProvider = injector.getProvider(CacheListMenuActions.class); mContextActionsProvider = injector.getProvider(ContextActions.class); } public GeocacheListController(CacheListRefresh cacheListRefresh, AbortState abortState, Provider<MenuActionSyncGpx> menuActionSyncProvider, Provider<CacheListMenuActions> cacheListMenuActionsProvider, Provider<ContextActions> contextActionsProvider) { mCacheListRefresh = cacheListRefresh; mAborter = abortState; mMenuActionSyncGpxProvider = menuActionSyncProvider; mCacheListMenuActionsProvider = cacheListMenuActionsProvider; mContextActionsProvider = contextActionsProvider; } public boolean onContextItemSelected(MenuItem menuItem) { AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem .getMenuInfo(); mContextActionsProvider.get() .act(menuItem.getItemId(), adapterContextMenuInfo.position - 1); return true; } public boolean onCreateOptionsMenu(Menu menu) { return mCacheListMenuActionsProvider.get().onCreateOptionsMenu(menu); } public void onListItemClick(int position) { if (position > 0) mContextActionsProvider.get().act(MENU_VIEW, position - 1); else mCacheListRefresh.forceRefresh(); } public boolean onOptionsItemSelected(MenuItem item) { return mCacheListMenuActionsProvider.get().act(item.getItemId()); } public void onPause() { Log.d("GeoBeagle", "onPause aborting"); mAborter.abort(); mMenuActionSyncGpxProvider.get().abort(); } public void onResume(boolean fImport) { mCacheListRefresh.forceRefresh(); if (fImport) mMenuActionSyncGpxProvider.get().act(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.cachelist; import com.google.inject.Singleton; @Singleton public class ActivityVisible { private boolean isVisible; public void setVisible(boolean isVisible) { this.isVisible = isVisible; } public boolean getVisible() { return isVisible; } }
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.R; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors; import com.google.code.geobeagle.activity.cachelist.presenter.GeocacheListAdapter; import com.google.code.geobeagle.activity.compass.CompassFragment; import com.google.inject.Injector; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.app.ListFragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.HeaderViewListAdapter; import android.widget.ListView; public class CacheListFragment extends ListFragment { private GeocacheVectors geocacheVectors; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getCacheListDelegate().onCreateFragment(this); } @Override public boolean onContextItemSelected(MenuItem item) { return getCacheListDelegate().onContextItemSelected(item) || super.onContextItemSelected(item); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Injector injector = ((CacheListActivityHoneycomb)getActivity()).getInjector(); geocacheVectors = injector.getInstance(GeocacheVectors.class); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.cache_list, container, false); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); HeaderViewListAdapter adapter = (HeaderViewListAdapter)l.getAdapter(); GeocacheListAdapter wrappedAdapter = (GeocacheListAdapter)adapter.getWrappedAdapter(); wrappedAdapter.setSelected(position-1); showDetails(position - 1); } void showDetails(int position) { int positionToShow = position; int cacheCount = geocacheVectors.size(); if (cacheCount == 0) return; if (positionToShow >= cacheCount) positionToShow = cacheCount - 1; CompassFragment compassFragment = new CompassFragment(); Bundle bundle = new Bundle(); geocacheVectors.get(position).getGeocache().saveToBundle(bundle); compassFragment.setArguments(bundle); FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.compass_frame, compassFragment); fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); fragmentTransaction.commit(); } @Override public boolean onOptionsItemSelected(MenuItem item) { return getCacheListDelegate().onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } private CacheListDelegate getCacheListDelegate() { return ((CacheListActivityHoneycomb)getActivity()).getCacheListDelegate(); } }
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.CacheListActivityStarter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate; import com.google.code.geobeagle.gpsstatuswidget.InflatedGpsStatusWidget; import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable; import com.google.inject.Injector; import roboguice.activity.GuiceActivity; import android.graphics.Color; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; public class SearchOnlineActivity extends GuiceActivity { private SearchOnlineActivityDelegate mSearchOnlineActivityDelegate; private UpdateGpsWidgetRunnable mUpdateGpsWidgetRunnable; private CacheListActivityStarter mCacheListActivityStarter; SearchOnlineActivityDelegate getMSearchOnlineActivityDelegate() { return mSearchOnlineActivityDelegate; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); Log.d("GeoBeagle", "SearchOnlineActivity onCreate"); Injector injector = this.getInjector(); final InflatedGpsStatusWidget mInflatedGpsStatusWidget = injector .getInstance(InflatedGpsStatusWidget.class); GpsStatusWidgetDelegate gpsStatusWidgetDelegate = injector .getInstance(GpsStatusWidgetDelegate.class); mUpdateGpsWidgetRunnable = injector.getInstance(UpdateGpsWidgetRunnable.class); mInflatedGpsStatusWidget.setDelegate(gpsStatusWidgetDelegate); mInflatedGpsStatusWidget.setBackgroundColor(Color.BLACK); mSearchOnlineActivityDelegate = injector.getInstance(SearchOnlineActivityDelegate.class); mSearchOnlineActivityDelegate.configureWebView(); mCacheListActivityStarter = injector.getInstance(CacheListActivityStarter.class); } @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); mCacheListActivityStarter.start(); return true; } @Override protected void onPause() { Log.d("GeoBeagle", "SearchOnlineActivity onPause"); mSearchOnlineActivityDelegate.onPause(); // Must call super so that context scope is cleared only after listeners // are removed. super.onPause(); } @Override protected void onResume() { super.onResume(); Log.d("GeoBeagle", "SearchOnlineActivity onResume"); mSearchOnlineActivityDelegate.onResume(); mUpdateGpsWidgetRunnable.run(); } }
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.LocationControlBuffered; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.ActivitySaver; import com.google.code.geobeagle.activity.ActivityType; import com.google.code.geobeagle.activity.cachelist.ActivityVisible; import com.google.code.geobeagle.location.CombinedLocationListener; import com.google.code.geobeagle.location.CombinedLocationManager; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.Activity; import android.graphics.Color; import android.hardware.SensorManager; import android.webkit.WebSettings; import android.webkit.WebView; public class SearchOnlineActivityDelegate { private final ActivitySaver mActivitySaver; private final CombinedLocationListener mCombinedLocationListener; private final CombinedLocationManager mCombinedLocationManager; private final Provider<CompassListener> mCompassListenerProvider; private final LocationControlBuffered mLocationControlBuffered; private final SensorManager mSensorManager; private final WebView mWebView; private final ActivityVisible mActivityVisible; private final JsInterface mJsInterface; @Inject public SearchOnlineActivityDelegate(Activity activity, SensorManager sensorManager, Provider<CompassListener> compassListenerProvider, CombinedLocationManager combinedLocationManager, CombinedLocationListener combinedLocationListener, LocationControlBuffered locationControlBuffered, ActivitySaver activitySaver, ActivityVisible activityVisible, JsInterface jsInterface) { mSensorManager = sensorManager; mCompassListenerProvider = compassListenerProvider; mCombinedLocationListener = combinedLocationListener; mCombinedLocationManager = combinedLocationManager; mLocationControlBuffered = locationControlBuffered; mWebView = (WebView)activity.findViewById(R.id.help_contents); mActivitySaver = activitySaver; mActivityVisible = activityVisible; mJsInterface = jsInterface; } public void configureWebView() { mWebView.loadUrl("file:///android_asset/search.html"); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setBackgroundColor(Color.BLACK); mWebView.addJavascriptInterface(mJsInterface, "gb"); } public void onPause() { mCombinedLocationManager.removeUpdates(); mSensorManager.unregisterListener(mCompassListenerProvider.get()); mActivityVisible.setVisible(false); mActivitySaver.save(ActivityType.SEARCH_ONLINE); } public void onResume() { mCombinedLocationManager.requestLocationUpdates(1000, 0, mLocationControlBuffered); mCombinedLocationManager.requestLocationUpdates(1000, 0, mCombinedLocationListener); mSensorManager.registerListener(mCompassListenerProvider.get(), SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); mActivityVisible.setVisible(true); } }
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.R; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; import android.location.Location; import android.location.LocationManager; import android.net.Uri; import android.widget.Toast; import java.util.Locale; class JsInterface { private final JsInterfaceHelper mHelper; private final Toaster mToaster; private final LocationManager mLocationManager; static class JsInterfaceHelper { private final Activity mActivity; @Inject public JsInterfaceHelper(Activity activity) { mActivity = activity; } public void launch(String uri) { mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri))); } public String getTemplate(int ix) { return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix]; } public String getNS(double latitude) { return latitude > 0 ? "N" : "S"; } public String getEW(double longitude) { return longitude > 0 ? "E" : "W"; } } @Inject public JsInterface(JsInterfaceHelper jsInterfaceHelper, Toaster toaster, LocationManager locationManager) { mHelper = jsInterfaceHelper; mToaster = toaster; mLocationManager = locationManager; } public int atlasQuestOrGroundspeak(int ix) { Location location = getLocation(); if (location == null) return 0; final String uriTemplate = mHelper.getTemplate(ix); mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location.getLongitude())); return 0; } private Location getLocation() { Location location = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) { mToaster.toast(R.string.current_location_null, Toast.LENGTH_LONG); } return location; } public int openCaching(int ix) { Location location = getLocation(); if (location == null) return 0; final String uriTemplate = mHelper.getTemplate(ix); final double latitude = location.getLatitude(); final double longitude = location.getLongitude(); final String NS = mHelper.getNS(latitude); final String EW = mHelper.getEW(longitude); final double abs_latitude = Math.abs(latitude); final double abs_longitude = Math.abs(longitude); final int lat_h = (int)abs_latitude; final double lat_m = 60 * (abs_latitude - lat_h); final int lon_h = (int)abs_longitude; final double lon_m = 60 * (abs_longitude - lon_h); mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m)); return 0; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.activity.preferences; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.code.geobeagle.database.filter.FilterCleanliness; import com.google.inject.Inject; import roboguice.activity.GuicePreferenceActivity; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.widget.Toast; public class EditPreferences extends GuicePreferenceActivity { static class SyncPreferencesChangeListener implements OnPreferenceChangeListener { private final SharedPreferences sharedPreferences; private final Toaster toaster; @Inject public SyncPreferencesChangeListener(SharedPreferences sharedPreferences, Toaster toaster) { this.sharedPreferences = sharedPreferences; this.toaster = toaster; } @Override public boolean onPreferenceChange(Preference preference, Object newValue) { String otherKey = preference.getKey().equals(Preferences.BCACHING_ENABLED) ? Preferences.SDCARD_ENABLED : Preferences.BCACHING_ENABLED; if (newValue == Boolean.FALSE && !sharedPreferences.getBoolean(otherKey, false)) { toaster.toast(R.string.must_have_a_sync_method, Toast.LENGTH_SHORT); return false; } return true; } } private FilterCleanliness filterCleanliness; private FilterSettingsChangeListener onPreferenceChangeListener; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); Preference showFoundCachesPreference = findPreference(Preferences.SHOW_FOUND_CACHES); Preference showDnfCachesPreference = findPreference(Preferences.SHOW_DNF_CACHES); Preference showUnavailableCachesPreference = findPreference(Preferences.SHOW_UNAVAILABLE_CACHES); Preference showWaypointsPreference = findPreference(Preferences.SHOW_WAYPOINTS); onPreferenceChangeListener = getInjector().getInstance(FilterSettingsChangeListener.class); SyncPreferencesChangeListener syncPreferencesChangeListener = getInjector().getInstance( SyncPreferencesChangeListener.class); showWaypointsPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showFoundCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showDnfCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); showUnavailableCachesPreference.setOnPreferenceChangeListener(onPreferenceChangeListener); Preference sdCardEnabledPreference = findPreference(Preferences.SDCARD_ENABLED); Preference bcachingEnabledPreference = findPreference(Preferences.BCACHING_ENABLED); sdCardEnabledPreference.setOnPreferenceChangeListener(syncPreferencesChangeListener); bcachingEnabledPreference.setOnPreferenceChangeListener(syncPreferencesChangeListener); filterCleanliness = getInjector().getInstance(FilterCleanliness.class); } @Override public void onPause() { super.onPause(); filterCleanliness.markDirty(onPreferenceChangeListener.hasChanged()); } @Override public void onResume() { super.onResume(); // Defensively set dirty bit in case we crash before onPause. This is // better than setting the dirty bit every time the preferences change // because it doesn't slow down clicking/unclicking the checkbox. filterCleanliness.markDirty(true); onPreferenceChangeListener.resetHasChanged(); } }
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; public class Preferences { public static final String BCACHING_ENABLED = "bcaching-enabled"; public static final String BCACHING_HOSTNAME = "bcaching-hostname"; public static final String BCACHING_PASSWORD = "bcaching-password"; public static final String BCACHING_USERNAME = "bcaching-username"; public static final String SDCARD_ENABLED = "sdcard-enabled"; public static final String SHOW_DNF_CACHES = "show-dnf-caches"; public static final String SHOW_FOUND_CACHES = "show-found-caches"; public static final String SHOW_UNAVAILABLE_CACHES = "show-unavailable-caches"; public static final String SHOW_WAYPOINTS = "show-waypoints"; }
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 android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; class FilterSettingsChangeListener implements OnPreferenceChangeListener { private boolean hasChanged = false; @Override public boolean onPreferenceChange(Preference preference, Object newValue) { hasChanged = true; return true; } public void resetHasChanged() { hasChanged = false; } public boolean hasChanged() { return hasChanged; } }
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.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.compass.CompassActivity; import com.google.code.geobeagle.activity.compass.GeocacheFromPreferencesFactory; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; class ViewCacheRestorer implements Restorer { private final Activity activity; private final GeocacheFromPreferencesFactory geocacheFromPreferencesFactory; private final SharedPreferences sharedPreferences; public ViewCacheRestorer(GeocacheFromPreferencesFactory geocacheFromPreferencesFactory, SharedPreferences sharedPreferences, Activity activity) { this.geocacheFromPreferencesFactory = geocacheFromPreferencesFactory; this.sharedPreferences = sharedPreferences; this.activity = activity; } @Override public void restore() { final Geocache geocache = geocacheFromPreferencesFactory.create(sharedPreferences); final Intent intent = new Intent(activity, CompassActivity.class); intent.putExtra("geocache", geocache).setAction(GeocacheListController.SELECT_CACHE); activity.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; interface Restorer { void 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; import com.google.code.geobeagle.activity.cachelist.CacheListActivityHoneycomb; import com.google.inject.Inject; import android.app.Activity; import android.content.Intent; public class CacheListActivityStarterHoneycomb implements CacheListActivityStarter { private Activity activity; @Inject CacheListActivityStarterHoneycomb(Activity activity) { this.activity = activity; } @Override public void start() { activity.startActivity(new Intent(activity, CacheListActivityHoneycomb.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector; public class GpsEnabledLocation implements IGpsLocation { private final float mLatitude; private final float mLongitude; public GpsEnabledLocation(float latitude, float longitude) { mLatitude = latitude; mLongitude = longitude; } @Override public float distanceTo(IGpsLocation gpsLocation) { return gpsLocation.distanceToGpsEnabledLocation(this); } @Override public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) { final float calculateDistanceFast = GeocacheVector.calculateDistanceFast(mLatitude, mLongitude, gpsEnabledLocation.mLatitude, gpsEnabledLocation.mLongitude); return calculateDistanceFast; } }
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.inject.Inject; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.DialogInterface.OnClickListener; public class ErrorDisplayer { static class DisplayErrorRunnable implements Runnable { private final Builder mAlertDialogBuilder; DisplayErrorRunnable(Builder alertDialogBuilder) { mAlertDialogBuilder = alertDialogBuilder; } @Override public void run() { mAlertDialogBuilder.create().show(); } } private final Activity mActivity; private final OnClickListener mOnClickListener; @Inject public ErrorDisplayer(Activity activity, OnClickListenerNOP onClickListener) { mActivity = activity; mOnClickListener = onClickListener; } public void displayError(int resId, Object... args) { final Builder alertDialogBuilder = new Builder(mActivity); alertDialogBuilder.setMessage(String.format((String)mActivity.getText(resId), args)); alertDialogBuilder.setNeutralButton("Ok", mOnClickListener); mActivity.runOnUiThread(new DisplayErrorRunnable(alertDialogBuilder)); } }
Java
/* ** 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 java.util.HashMap; class Tag { final HashMap<String, String> attributes; final String name; Tag(String name, HashMap<String, String> attributes) { this.name = name; this.attributes = attributes; } }
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 java.io.IOException; public class EventHandlerGpx implements EventHandler { private final CacheXmlTagHandler cacheXmlTagHandler; private XmlPullParser xmlPullParser; public EventHandlerGpx(CacheXmlTagHandler cacheXmlTagHandler) { this.cacheXmlTagHandler = cacheXmlTagHandler; } @Override public void endTag(String name, String previousFullPath) throws IOException { GpxPath.fromString(previousFullPath).endTag(cacheXmlTagHandler); } @Override public void startTag(String name, String fullPath) throws IOException { GpxPath.fromString(fullPath).startTag(xmlPullParser, cacheXmlTagHandler); } @Override public boolean text(String fullPath, String text) throws IOException { return GpxPath.fromString(fullPath).text(text, cacheXmlTagHandler); } @Override public void start(XmlPullParser xmlPullParser) { this.xmlPullParser = xmlPullParser; } @Override public void end() { } }
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.activity.cachelist.presenter.CacheListRefresh; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.cachedetails.FileDataVersionWriter; import com.google.code.geobeagle.database.ClearCachesFromSourceImpl; import com.google.code.geobeagle.database.GpxTableWriterGpxFiles; import com.google.code.geobeagle.xmlimport.GpxToCache.GpxToCacheFactory; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.inject.Inject; import android.content.SharedPreferences; class GpxSyncerFactory { private final CacheListRefresh cacheListRefresh; private final FileDataVersionWriter fileDataVersionWriter; private final GpxAndZipFiles gpxAndZipFiles; private final GpxToCacheFactory gpxToCacheFactory; private final MessageHandler messageHandlerInterface; private final OldCacheFilesCleaner oldCacheFilesCleaner; private final UpdateFlag updateFlag; private final GeoBeagleEnvironment geoBeagleEnvironment; private final GpxTableWriterGpxFiles gpxTableWriterGpxFiles; private final SharedPreferences sharedPreferences; private final ClearCachesFromSourceImpl clearCachesFromSource; @Inject public GpxSyncerFactory(MessageHandler messageHandler, CacheListRefresh cacheListRefresh, GpxAndZipFiles gpxAndZipFiles, GpxToCacheFactory gpxToCacheFactory, FileDataVersionWriter fileDataVersionWriter, OldCacheFilesCleaner oldCacheFilesCleaner, UpdateFlag updateFlag, GeoBeagleEnvironment geoBeagleEnvironment, GpxTableWriterGpxFiles gpxTableWriterGpxFiles, SharedPreferences sharedPreferences, ClearCachesFromSourceImpl clearCachesFromSource) { this.messageHandlerInterface = messageHandler; this.cacheListRefresh = cacheListRefresh; this.gpxAndZipFiles = gpxAndZipFiles; this.gpxToCacheFactory = gpxToCacheFactory; this.fileDataVersionWriter = fileDataVersionWriter; this.oldCacheFilesCleaner = oldCacheFilesCleaner; this.updateFlag = updateFlag; this.geoBeagleEnvironment = geoBeagleEnvironment; this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.sharedPreferences = sharedPreferences; this.clearCachesFromSource = clearCachesFromSource; } public GpxSyncer create() { messageHandlerInterface.start(cacheListRefresh); final GpxToCache gpxToCache = gpxToCacheFactory.create(messageHandlerInterface, gpxTableWriterGpxFiles, clearCachesFromSource); return new GpxSyncer(gpxAndZipFiles, fileDataVersionWriter, messageHandlerInterface, oldCacheFilesCleaner, gpxToCache, updateFlag, geoBeagleEnvironment, sharedPreferences); } }
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.gpx.gpx; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.inject.Provider; public class GpxFileOpener { public static class GpxFileIter implements IGpxReaderIter { private final Provider<AbortState> aborterProvider; private String filename; public GpxFileIter(Provider<AbortState> aborterProvider, String filename) { this.aborterProvider = aborterProvider; this.filename = filename; } @Override public boolean hasNext() { if (aborterProvider.get().isAborted()) return false; return filename != null; } @Override public IGpxReader next() { final IGpxReader gpxReader = new GpxReader(filename); filename = null; return gpxReader; } } private final Provider<AbortState> aborterProvider; private final String filename; public GpxFileOpener(String filename, Provider<AbortState> aborterProvider) { this.filename = filename; this.aborterProvider = aborterProvider; } public GpxFileIter iterator() { return new GpxFileIter(aborterProvider, 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.gpx.gpx; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String path; public GpxReader(String path) { this.path = path; } @Override public String getFilename() { return path; } @Override public Reader open() throws FileNotFoundException { return new BufferedReader(new FileReader(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.gpx; import java.io.IOException; public interface IGpxReaderIter { public boolean hasNext() throws IOException; public IGpxReader next() throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.preferences.Preferences; import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment; import com.google.code.geobeagle.xmlimport.ImportException; import com.google.inject.Inject; import android.content.SharedPreferences; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class GpxAndZipFiles { public static class GpxAndZipFilenameFilter implements FilenameFilter { private final GpxFilenameFilter mGpxFilenameFilter; @Inject public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } @Override public boolean accept(File dir, String name) { String lowerCaseName = name.toLowerCase(); if (!lowerCaseName.startsWith(".") && lowerCaseName.endsWith(".zip")) return true; return mGpxFilenameFilter.accept(lowerCaseName); } } public static class GpxFilenameFilter { public boolean accept(String name) { String lowerCaseName = name.toLowerCase(); return !lowerCaseName.startsWith(".") && (lowerCaseName.endsWith(".gpx") || lowerCaseName.endsWith(".loc")); } } public static class GpxFilesAndZipFilesIter { private final String[] mFileList; private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory; private int mIxFileList; private IGpxReaderIter mSubIter; GpxFilesAndZipFilesIter(String[] fileList, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFileList = fileList; mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mIxFileList = 0; } public boolean hasNext() throws IOException { // Iterate through actual zip, loc, and gpx files on the filesystem. // If a zip file, a sub iterator will walk through the zip file // contents, otherwise the sub iterator will return just the loc/gpx // file. if (mSubIter != null && mSubIter.hasNext()) return true; while (mIxFileList < mFileList.length) { mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]); if (mSubIter.hasNext()) return true; } return false; } public IGpxReader next() throws IOException { return mSubIter.next(); } } private final FilenameFilter mFilenameFilter; private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory; private final GeoBeagleEnvironment mGeoBeagleEnvironment; private final SharedPreferences mSharedPreferences; @Inject public GpxAndZipFiles(GpxAndZipFilenameFilter filenameFilter, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory, GeoBeagleEnvironment geoBeagleEnvironment, SharedPreferences sharedPreferences) { mFilenameFilter = filenameFilter; mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mGeoBeagleEnvironment = geoBeagleEnvironment; mSharedPreferences = sharedPreferences; } public GpxFilesAndZipFilesIter iterator() throws ImportException { String[] fileList; if (!mSharedPreferences.getBoolean(Preferences.SDCARD_ENABLED, true)) { fileList = new String[0]; } else { String gpxDir = mGeoBeagleEnvironment.getImportFolder(); fileList = new File(gpxDir).list(mFilenameFilter); if (fileList == null) throw new ImportException(R.string.error_cant_read_sd, gpxDir); } mGpxFileIterAndZipFileIterFactory.resetAborter(); return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory); } }
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.gpx; import java.io.FileNotFoundException; import java.io.Reader; public interface IGpxReader { String getFilename(); Reader open() throws FileNotFoundException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class GpxZipInputStream { private ZipEntry mNextEntry; private final ZipInputStream mZipInputStream; public GpxZipInputStream(ZipInputStream zipInputStream) { mZipInputStream = zipInputStream; } ZipEntry getNextEntry() throws IOException { mNextEntry = mZipInputStream.getNextEntry(); return mNextEntry; } InputStream getStream() { return mZipInputStream; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String filename; private final Reader reader; GpxReader(String filename, Reader reader) { this.filename = filename; this.reader = reader; } @Override public String getFilename() { return filename; } @Override public Reader open() { return reader; } }
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.gpx.zip; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.AbortState; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.inject.Inject; import com.google.inject.Provider; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.ZipEntry; public class ZipFileOpener { public static class ZipFileIter implements IGpxReaderIter { private final Provider<AbortState> mAborterProvider; private ZipEntry mNextZipEntry; private final ZipInputFileTester mZipInputFileTester; private final GpxZipInputStream mZipInputStream; ZipFileIter(GpxZipInputStream zipInputStream, Provider<AbortState> aborterProvider, ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) { mZipInputStream = zipInputStream; mNextZipEntry = nextZipEntry; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } ZipFileIter(GpxZipInputStream zipInputStream, Provider<AbortState> aborterProvider, ZipInputFileTester zipInputFileTester) { mZipInputStream = zipInputStream; mNextZipEntry = null; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } @Override public boolean hasNext() throws IOException { // Iterate through zip file entries. if (mNextZipEntry == null) { do { if (mAborterProvider.get().isAborted()) break; mNextZipEntry = mZipInputStream.getNextEntry(); } while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry)); } return mNextZipEntry != null; } @Override public IGpxReader next() throws IOException { final String name = mNextZipEntry.getName(); mNextZipEntry = null; return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream())); } } public static class ZipInputFileTester { private final GpxFilenameFilter mGpxFilenameFilter; @Inject public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean isValid(ZipEntry zipEntry) { return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName())); } } private final Provider<AbortState> mAborterProvider; private final String mFilename; private final ZipInputFileTester mZipInputFileTester; private final ZipInputStreamFactory mZipInputStreamFactory; public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory, ZipInputFileTester zipInputFileTester, Provider<AbortState> aborterProvider) { mFilename = filename; mZipInputStreamFactory = zipInputStreamFactory; mAborterProvider = aborterProvider; mZipInputFileTester = zipInputFileTester; } public ZipFileIter iterator() throws IOException { return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborterProvider, mZipInputFileTester); } }
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; @SuppressWarnings("serial") public class ImportException extends Exception { private final int error; private final String path; public ImportException(int error, String path) { super(); this.error = error; this.path = path; } public int getError() { return error; } public String getPath() { return 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.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.bcaching.ImportBCachingWorker; import com.google.code.geobeagle.bcaching.communication.BCachingException; import com.google.code.geobeagle.bcaching.preferences.BCachingStartTime; import com.google.code.geobeagle.database.DbFrontend; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import com.google.inject.Inject; import com.google.inject.Injector; import com.google.inject.Provider; import roboguice.util.RoboThread; import android.util.Log; import java.io.FileNotFoundException; import java.io.IOException; public class ImportThread extends RoboThread { static class ImportThreadFactory { private final GpxSyncerFactory gpxSyncerFactory; private final Provider<ImportBCachingWorker> importBCachingWorkerProvider; private final ErrorDisplayer errorDisplayer; private final BCachingStartTime bcachingStartTime; private final DbFrontend dbFrontend; private final SyncCollectingParameter syncCollectingParameter; @Inject ImportThreadFactory(Injector injector) { this.gpxSyncerFactory = injector.getInstance(GpxSyncerFactory.class); this.importBCachingWorkerProvider = injector.getProvider(ImportBCachingWorker.class); this.errorDisplayer = injector.getInstance(ErrorDisplayer.class); this.bcachingStartTime = injector.getInstance(BCachingStartTime.class); this.dbFrontend = injector.getInstance(DbFrontend.class); this.syncCollectingParameter = injector.getInstance(SyncCollectingParameter.class); } ImportThread create() { return new ImportThread(gpxSyncerFactory.create(), importBCachingWorkerProvider.get(), errorDisplayer, bcachingStartTime, dbFrontend, syncCollectingParameter); } } private final GpxSyncer gpxSyncer; private final ImportBCachingWorker importBCachingWorker; private boolean isAlive; private final ErrorDisplayer errorDisplayer; private final BCachingStartTime bcachingStartTime; private final DbFrontend dbFrontend; private final SyncCollectingParameter syncCollectingParameter; ImportThread(GpxSyncer gpxSyncer, ImportBCachingWorker importBCachingWorker, ErrorDisplayer errorDisplayer, BCachingStartTime bcachingStartTime, DbFrontend dbFrontend, SyncCollectingParameter syncCollectingParameter) { this.gpxSyncer = gpxSyncer; this.importBCachingWorker = importBCachingWorker; this.errorDisplayer = errorDisplayer; this.bcachingStartTime = bcachingStartTime; this.dbFrontend = dbFrontend; this.syncCollectingParameter = syncCollectingParameter; } @Override public void run() { isAlive = true; try { syncCollectingParameter.reset(); gpxSyncer.sync(syncCollectingParameter); importBCachingWorker.sync(syncCollectingParameter); errorDisplayer.displayError(R.string.string, syncCollectingParameter.getLog()); } catch (final FileNotFoundException e) { errorDisplayer.displayError(R.string.error_opening_file, e.getMessage()); return; } catch (IOException e) { errorDisplayer.displayError(R.string.error_reading_file, e.getMessage()); return; } catch (ImportException e) { errorDisplayer.displayError(e.getError(), e.getPath()); return; } catch (BCachingException e) { errorDisplayer.displayError(R.string.problem_importing_from_bcaching, e.getLocalizedMessage()); } catch (CancelException e) { // Toast can't be displayed in this thread; it must be displayed in // main UI thread. return; } finally { Log.d("GeoBeagle", "<<< Syncing"); isAlive = false; } } public boolean isAliveHack() { return isAlive; } }
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.activity.cachelist.presenter.CacheListRefresh; import com.google.inject.Inject; import roboguice.inject.ContextScoped; import android.os.Handler; import android.os.Message; import android.util.Log; @ContextScoped public class MessageHandler extends Handler implements MessageHandlerInterface { public static final String GEOBEAGLE = "GeoBeagle"; static final int MSG_DONE = 1; static final int MSG_PROGRESS = 0; private int mCacheCount; private boolean mLoadAborted; private CacheListRefresh mMenuActionRefresh; private final ProgressDialogWrapper mProgressDialogWrapper; private String mSource; private String mStatus; private String mWaypointId; @Inject public MessageHandler(ProgressDialogWrapper progressDialogWrapper) { mProgressDialogWrapper = progressDialogWrapper; } @Override 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; } } @Override public void loadComplete() { sendEmptyMessage(MessageHandler.MSG_DONE); } @Override public void start(CacheListRefresh cacheListRefresh) { mCacheCount = 0; mLoadAborted = false; mMenuActionRefresh = cacheListRefresh; // TODO: move text into resource. mProgressDialogWrapper.show("Sync from sdcard", "Please wait..."); } @Override public void updateName(String name) { mStatus = mCacheCount++ + ": " + mSource + " - " + mWaypointId + " - " + name; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void updateSource(String text) { mSource = text; mStatus = "Opening: " + mSource + "..."; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void updateWaypointId(String wpt) { mWaypointId = wpt; } @Override public void updateStatus(String status) { mStatus = status; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } @Override public void deletingCacheFiles() { mStatus = "Deleting old cache files...."; if (!hasMessages(MessageHandler.MSG_PROGRESS)) sendEmptyMessage(MessageHandler.MSG_PROGRESS); } }
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.inject.Inject; import android.content.SharedPreferences; import android.os.Environment; public class GeoBeagleEnvironment { public static final String IMPORT_FOLDER = "import-folder"; private final SharedPreferences sharedPreferences; private static final String DETAILS_DIR = "GeoBeagle/data/"; private static final String FIELDNOTES_FILE = "GeoBeagleFieldNotes.txt"; @Inject GeoBeagleEnvironment(SharedPreferences sharedPreferences) { this.sharedPreferences = sharedPreferences; } public String getExternalStorageDir() { return Environment.getExternalStorageDirectory().getAbsolutePath(); } public String getDetailsDirectory() { return getExternalStorageDir() + "/" + GeoBeagleEnvironment.DETAILS_DIR; } public String getVersionPath() { return getDetailsDirectory() + "/VERSION"; } public String getOldDetailsDirectory() { return getExternalStorageDir() + "/" + "GeoBeagle"; } public String getImportFolder() { String string = sharedPreferences.getString(IMPORT_FOLDER, Environment .getExternalStorageDirectory() + "/Download"); if ((!string.endsWith("/"))) return string + "/"; return string; } public String getFieldNotesFilename() { return getExternalStorageDir() + "/" + FIELDNOTES_FILE; } }
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.R; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.UpdateFlag; import com.google.code.geobeagle.activity.preferences.Preferences; import com.google.code.geobeagle.cachedetails.FileDataVersionWriter; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import android.content.SharedPreferences; import android.util.Log; import java.io.File; import java.io.IOException; public class GpxSyncer { private final FileDataVersionWriter fileDataVersionWriter; private final GpxAndZipFiles gpxAndZipFiles; private final GpxToCache gpxToCache; private boolean mHasFiles; private final MessageHandler messageHandler; private final OldCacheFilesCleaner oldCacheFilesCleaner; private final UpdateFlag updateFlag; private final GeoBeagleEnvironment geoBeagleEnvironment; private final SharedPreferences sharedPreferences; public GpxSyncer(GpxAndZipFiles gpxAndZipFiles, FileDataVersionWriter fileDataVersionWriter, MessageHandler messageHandlerInterface, OldCacheFilesCleaner oldCacheFilesCleaner, GpxToCache gpxToCache, UpdateFlag updateFlag, GeoBeagleEnvironment geoBeagleEnvironment, SharedPreferences sharedPreferences) { this.gpxAndZipFiles = gpxAndZipFiles; this.fileDataVersionWriter = fileDataVersionWriter; this.messageHandler = messageHandlerInterface; this.mHasFiles = false; this.oldCacheFilesCleaner = oldCacheFilesCleaner; this.gpxToCache = gpxToCache; this.updateFlag = updateFlag; this.geoBeagleEnvironment = geoBeagleEnvironment; this.sharedPreferences = sharedPreferences; } public void sync(SyncCollectingParameter syncCollectingParameter) throws IOException, ImportException, CancelException { try { updateFlag.setUpdatesEnabled(false); if (!sharedPreferences.getBoolean(Preferences.SDCARD_ENABLED, true)) return; GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = startImport(); while (gpxFilesAndZipFilesIter.hasNext()) { processFile(syncCollectingParameter, gpxFilesAndZipFilesIter); } if (!mHasFiles) syncCollectingParameter.Log(R.string.error_no_gpx_files, geoBeagleEnvironment.getImportFolder()); endImport(); } finally { Log.d("GeoBeagle", "<<< Syncing"); updateFlag.setUpdatesEnabled(true); messageHandler.loadComplete(); } } private void endImport() throws IOException { fileDataVersionWriter.writeVersion(); gpxToCache.end(); } private void processFile(SyncCollectingParameter syncCollectingParameter, GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter) throws IOException, CancelException { IGpxReader gpxReader = gpxFilesAndZipFilesIter.next(); String filename = gpxReader.getFilename(); syncCollectingParameter.Log("***" + (new File(filename).getName()) + "***"); mHasFiles = true; int cachesLoaded = gpxToCache.load(filename, gpxReader.open()); if (cachesLoaded == -1) { syncCollectingParameter.Log(" synced 0 caches"); } else { syncCollectingParameter.Log(" synced " + cachesLoaded + " caches"); } } private GpxFilesAndZipFilesIter startImport() throws ImportException { oldCacheFilesCleaner.clean(messageHandler); gpxToCache.start(); GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = gpxAndZipFiles.iterator(); return gpxFilesAndZipFilesIter; } }
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 roboguice.inject.ContextScoped; import android.util.Log; @ContextScoped public class AbortState { private static boolean aborted = false; AbortState() { aborted = false; } public void abort() { Log.d("GeoBeagle", this + ": aborting"); aborted = true; } public boolean isAborted() { return aborted; } public void reset() { aborted = false; } }
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.cachedetails.StringWriterWrapper; import com.google.inject.Inject; import java.io.IOException; public class CacheXmlTagsToUrl extends CacheXmlTagHandler { private final StringWriterWrapper stringWriterWrapper; @Inject CacheXmlTagsToUrl(StringWriterWrapper stringWriterWrapper) { this.stringWriterWrapper = stringWriterWrapper; } @Override public void url(String text) { try { stringWriterWrapper.open(); stringWriterWrapper.write(text); } catch (IOException e) { e.printStackTrace(); } } }
Java
package com.google.code.geobeagle.xmlimport; import com.google.inject.Inject; import com.google.inject.Provider; import android.app.ProgressDialog; import android.content.Context; public class ProgressDialogWrapper { private final Provider<Context> mContextProvider; private ProgressDialog mProgressDialog; @Inject public ProgressDialogWrapper(Provider<Context> context) { mContextProvider = 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(mContextProvider.get(), title, msg); // mProgressDialog.setCancelable(true); } }
Java
package com.google.code.geobeagle.xmlimport; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import com.google.inject.BindingAnnotation; import java.lang.annotation.Retention; import java.lang.annotation.Target; public class XmlimportAnnotations { private XmlimportAnnotations() { } @BindingAnnotation @Target( { FIELD, PARAMETER, METHOD }) @Retention(RUNTIME) public static @interface SDCard { } }
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.inject.Inject; import com.google.inject.Singleton; import android.content.res.Resources; @Singleton public class SyncCollectingParameter { private String log; private final Resources resources; @Inject public SyncCollectingParameter(Resources resources) { this.resources = resources; reset(); } public void Log(int resId, Object... args) { Log(resources.getString(resId, args)); } public void NestedLog(int resId, Object... args) { Log(" " + resources.getString(resId, args)); } public void Log(String s) { this.log += s + "\n"; } public String getLog() { return this.log; } public void reset() { this.log = ""; } }
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.inject.Inject; import android.util.Log; import java.io.File; public class OldCacheFilesCleaner { private final String directory; @Inject public OldCacheFilesCleaner(GeoBeagleEnvironment geoBeagleEnvironment) { this.directory = geoBeagleEnvironment.getOldDetailsDirectory(); } public void clean(MessageHandlerInterface messageHandler) { messageHandler.deletingCacheFiles(); String[] list = new File(directory).list(new ExtensionFilter(".html")); if (list == null) return; for (int i = 0; i < list.length; i++) { messageHandler.updateStatus(String.format("Deleting old cache files: [%d/%d] %s", i, list.length, list[i])); File file = new File(directory, list[i]); Log.d("GeoBeagle", file + " deleted : " + file.delete()); } } }
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.cachedetails.DetailsDatabaseWriter; import com.google.inject.Inject; class TagWriter { private static final String SPACES = " "; private int mLevel; private final DetailsDatabaseWriter writer; private final StringBuffer stringBuffer; private String wpt; @Inject public TagWriter(DetailsDatabaseWriter writer) { this.writer = writer; stringBuffer = new StringBuffer(); } public void close() { writer.write(wpt, stringBuffer.toString()); wpt = null; } public void endTag(String name) { mLevel--; stringBuffer.append("</" + name + ">"); } public void open(String wpt) { mLevel = 0; this.wpt = wpt; stringBuffer.setLength(0); stringBuffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); } public void startTag(Tag tag) { stringBuffer.append("\n" + SPACES.substring(0, Math.min(mLevel, SPACES.length()))); mLevel++; stringBuffer.append("<" + tag.name); for (String key : tag.attributes.keySet()) { stringBuffer.append(" " + key + "='" + tag.attributes.get(key) + "'"); } stringBuffer.append(">"); } public void text(String text) { stringBuffer.append(text.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")); } public void start() { writer.start(); } public void end() { writer.end(); } }
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.R; import com.google.code.geobeagle.activity.cachelist.Pausable; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListPresenter; import com.google.code.geobeagle.activity.compass.fieldnotes.Toaster; import com.google.code.geobeagle.xmlimport.ImportThread.ImportThreadFactory; import com.google.inject.Inject; import com.google.inject.Injector; import android.util.Log; import android.widget.Toast; public class CacheSyncer { private final MessageHandler messageHandler; private final Toaster toaster; private final Pausable geocacheListPresenter; private final AbortState abortState; private final ImportThreadFactory importThreadFactory; private ImportThread importThread; CacheSyncer(CacheListPresenter cacheListPresenter, MessageHandler messageHandler, Toaster toaster, AbortState abortState, ImportThreadFactory importThreadFactory) { this.messageHandler = messageHandler; this.toaster = toaster; this.geocacheListPresenter = cacheListPresenter; this.abortState = abortState; this.importThreadFactory = importThreadFactory; } @Inject CacheSyncer(Injector injector) { abortState = injector.getInstance(AbortState.class); messageHandler = injector.getInstance(MessageHandler.class); toaster = injector.getInstance(Toaster.class); geocacheListPresenter = injector.getInstance(CacheListPresenter.class); importThreadFactory = injector.getInstance(ImportThreadFactory.class); } public void abort() { Log.d("GeoBeagle", "CacheSyncer:abort() " + isAlive()); //TODO(sng): Why not use AbortState()? messageHandler.abortLoad(); abortState.abort(); if (isAlive()) { join(); toaster.toast(R.string.import_canceled, Toast.LENGTH_SHORT); } Log.d("GeoBeagle", "CacheSyncer:abort() ending: " + isAlive()); } boolean isAlive() { return importThread.isAliveHack(); } void join() { try { while (isAlive()) { Thread.sleep(1000); } } catch (InterruptedException e) { // Ignore; we are aborting anyway. } } public void syncGpxs() { // TODO(sng): check when onResume is called. geocacheListPresenter.onPause(); importThread = importThreadFactory.create(); importThread.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; import java.util.HashMap; import java.util.Map; public enum GpxPath { GPX_AU_DESCRIPTION("/gpx/wpt/geocache/description", PathType.LINE), GPX_AU_GEOCACHER("/gpx/wpt/geocache/logs/log/geocacher", PathType.LINE), GPX_AU_LOGTEXT("/gpx/wpt/geocache/logs/log/text", PathType.LINE), GPX_AU_LOGTYPE("/gpx/wpt/geocache/logs/log/type", PathType.LINE), GPX_AU_OWNER("/gpx/wpt/geocache/owner", PathType.LINE), GPX_AU_SUMMARY("/gpx/wpt/geocache/summary", PathType.LINE), GPX_CACHE("/gpx/wpt/groundspeak:cache", PathType.CACHE), GPX_CACHE_CONTAINER("/gpx/wpt/groundspeak:cache/groundspeak:container", PathType.CONTAINER), GPX_CACHE_DIFFICULTY("/gpx/wpt/groundspeak:cache/groundspeak:difficulty", PathType.DIFFICULTY), GPX_CACHE_TERRAIN("/gpx/wpt/groundspeak:cache/groundspeak:terrain", PathType.TERRAIN), GPX_EXT_LONGDESC("/gpx/wpt/extensions/cache/long_description", PathType.LONG_DESCRIPTION), GPX_EXT_SHORTDESC("/gpx/wpt/extensions/cache/short_description", PathType.SHORT_DESCRIPTION), GPX_GEOCACHE_CONTAINER("/gpx/wpt/geocache/container", PathType.CONTAINER), GPX_GEOCACHE_DIFFICULTY("/gpx/wpt/geocache/difficulty", PathType.DIFFICULTY), GPX_GEOCACHE_EXT_DIFFICULTY("/gpx/wpt/extensions/cache/difficulty", PathType.DIFFICULTY), GPX_GEOCACHE_EXT_TERRAIN("/gpx/wpt/extensions/cache/terrain", PathType.TERRAIN), GPX_GEOCACHE_TERRAIN("/gpx/wpt/geocache/terrain", PathType.TERRAIN), GPX_GEOCACHE_TYPE("/gpx/wpt/geocache/type", PathType.CACHE_TYPE), GPX_GEOCACHEHINT("/gpx/wpt/geocache/hints", PathType.HINT), GPX_GEOCACHELOGDATE("/gpx/wpt/geocache/logs/log/time", PathType.LOG_DATE), GPX_GEOCACHENAME("/gpx/wpt/geocache/name", PathType.NAME), GPX_GPXTIME("/gpx/time", PathType.GPX_TIME), GPX_GROUNDSPEAKFINDER( "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", PathType.LINE), GPX_GROUNDSPEAKNAME("/gpx/wpt/groundspeak:cache/groundspeak:name", PathType.NAME), GPX_HINT("/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints", PathType.HINT), GPX_LAST_MODIFIED("/gpx/wpt/bcaching:cache/bcaching:lastModified", PathType.LAST_MODIFIED), GPX_LOGDATE("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date", PathType.LOG_DATE), GPX_LOGFINDER("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", PathType.LOG_FINDER), GPX_LOGTEXT("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text", PathType.LOG_TEXT), GPX_LOGTYPE("/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", PathType.LOG_TYPE), GPX_LONGDESC("/gpx/wpt/groundspeak:cache/groundspeak:long_description", PathType.LONG_DESCRIPTION), GPX_OCLOGDATE("/gpx/wpt/extensions/cache/logs/log/date", PathType.LOG_DATE), GPX_OCLOGDATE_OLD("/gpx/wpt/extensions/cache/logs/log/time", PathType.LOG_DATE), GPX_OCLOGFINDER("/gpx/wpt/extensions/cache/logs/log/finder", PathType.LOG_FINDER), GPX_OCLOGFINDER_OLD("/gpx/wpt/extensions/cache/logs/log/geocacher", PathType.LOG_FINDER), GPX_OCLOGTEXT("/gpx/wpt/extensions/cache/logs/log/text", PathType.LOG_TEXT), GPX_OCLOGTYPE("/gpx/wpt/extensions/cache/logs/log/type", PathType.LOG_TYPE), GPX_OCNAME("/gpx/wpt/extensions/cache/name", PathType.NAME), GPX_OCOWNER("/gpx/wpt/extensions/cache/owner", PathType.PLACED_BY), GPX_PLACEDBY("/gpx/wpt/groundspeak:cache/groundspeak:placed_by", PathType.PLACED_BY), GPX_SHORTDESC("/gpx/wpt/groundspeak:cache/groundspeak:short_description", PathType.SHORT_DESCRIPTION), GPX_SYM("/gpx/wpt/sym", PathType.SYMBOL), GPX_TERRACACHINGGPXTIME("/gpx/metadata/time", PathType.GPX_TIME), GPX_URL("/gpx/wpt/url", PathType.GPX_URL), GPX_WAYPOINT_TYPE("/gpx/wpt/type", PathType.CACHE_TYPE), GPX_WPT("/gpx/wpt", PathType.WPT), GPX_WPT_COMMENT("/gpx/wpt/cmt", PathType.LINE), GPX_WPTDESC("/gpx/wpt/desc", PathType.DESC), GPX_WPTNAME("/gpx/wpt/name", PathType.WPT_NAME), GPX_WPTTIME("/gpx/wpt/time", PathType.WPT_TIME), LOC_COORD("/loc/waypoint/coord", PathType.LOC_COORD), LOC_LONGDESC("/loc/waypoint/desc", PathType.LONG_DESCRIPTION), LOC_WPT("/loc/waypoint", PathType.LOC_WPT), LOC_WPTNAME("/loc/waypoint/name", PathType.LOC_WPTNAME), NO_MATCH(null, PathType.NOP); private static final Map<String, GpxPath> stringToEnum = new HashMap<String, GpxPath>(); static { for (GpxPath gpxPath : values()) stringToEnum.put(gpxPath.getPath(), gpxPath); } public static GpxPath fromString(String symbol) { final GpxPath gpxPath = stringToEnum.get(symbol); if (gpxPath == null) { return GpxPath.NO_MATCH; } return gpxPath; } private final String path; private final PathType pathType; GpxPath(String path, PathType pathType) { this.path = path; this.pathType = pathType; } public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { pathType.endTag(cacheXmlTagHandler); } public String getPath() { return path; } public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { pathType.startTag(xmlPullParser, cacheXmlTagHandler); } public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { String trimmedText = text.trim(); if (trimmedText.length() <= 0) return true; return pathType.text(trimmedText, cacheXmlTagHandler); } }
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.inject.Inject; import com.google.inject.Singleton; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; import java.util.HashMap; @Singleton public class XmlWriter implements EventHandler { private final TagWriter tagWriter; private Tag tagWpt; private String time; private XmlPullParser xmlPullParser; private static String GPX_WPT = "/gpx/wpt"; private static String GPX_WPTTIME = "/gpx/wpt/time"; private static String GPX_WPTNAME = "/gpx/wpt/name"; private final HashMap<String, String> emptyHashMap; private boolean isWritingCache; @Inject public XmlWriter(TagWriter tagWriter) { this.tagWriter = tagWriter; emptyHashMap = new HashMap<String, String>(); isWritingCache = false; } @Override public void endTag(String name, String previousFullPath) throws IOException { if (!previousFullPath.startsWith(GPX_WPT)) return; if (isWritingCache) tagWriter.endTag(name); if (previousFullPath.equals(GPX_WPT)) { tagWriter.endTag("gpx"); tagWriter.close(); isWritingCache = false; } } @Override public void startTag(String name, String fullPath) throws IOException { if (!fullPath.startsWith(GPX_WPT)) return; HashMap<String, String> attributes = new HashMap<String, String>(); int attributeCount = xmlPullParser.getAttributeCount(); for (int i = 0; i < attributeCount; i++) { attributes.put(xmlPullParser.getAttributeName(i), xmlPullParser.getAttributeValue(i)); } Tag tag = new Tag(name, attributes); if (fullPath.equals(GPX_WPT)) { tagWpt = tag; } else if (isWritingCache) { tagWriter.startTag(tag); } } @Override public boolean text(String fullPath, String text) throws IOException { if (!fullPath.startsWith(GPX_WPT)) return true; if (text.trim().length() == 0) return true; if (fullPath.equals(GPX_WPTTIME)) { time = text; } else if (fullPath.equals(GPX_WPTNAME)) { tagWriter.open(text); tagWriter.startTag(new Tag("gpx", emptyHashMap)); tagWriter.startTag(tagWpt); if (time != null) { tagWriter.startTag(new Tag("time", emptyHashMap)); tagWriter.text(time); tagWriter.endTag("time"); } tagWriter.startTag(new Tag("name", emptyHashMap)); isWritingCache = true; } if (isWritingCache) tagWriter.text(text); return true; } @Override public void start(XmlPullParser xmlPullParser) { this.xmlPullParser = xmlPullParser; tagWriter.start(); } @Override public void end() { tagWriter.end(); } }
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 java.io.IOException; public interface EventHandler { void endTag(String name, String previousFullPath) throws IOException; void startTag(String name, String mFullPath) throws IOException; boolean text(String fullPath, String text) throws IOException; void start(XmlPullParser xmlPullParser); void end(); }
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.GeocacheFactory.Source; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; enum PathType { CACHE { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.available(xmlPullParser.getAttributeValue(null, "available")); cacheXmlTagHandler.archived(xmlPullParser.getAttributeValue(null, "archived")); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.symbol(text); return true; } }, CACHE_TYPE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.cacheType(text); return true; } }, CONTAINER { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.container(text); return true; } }, DESC { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptDesc(text); return true; } }, DIFFICULTY { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.difficulty(text); return true; } }, GPX_TIME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return cacheXmlTagHandler.gpxTime(text); } }, HINT { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { if (!text.equals("")) cacheXmlTagHandler.hint(text); return true; } }, LAST_MODIFIED { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }, LINE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.line(text); return true; } }, LOC_COORD { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser.getAttributeValue(null, "lon")); } }, LOC_WPT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.endCache(Source.LOC); } }, LOC_WPTNAME { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.startCache(); cacheXmlTagHandler.wptName(xmlPullParser.getAttributeValue(null, "id")); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.groundspeakName(text.trim()); return true; } }, LOG_DATE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logDate(text); return true; } }, LOG_TEXT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.setEncrypted(false); } @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.setEncrypted("true".equalsIgnoreCase(xmlPullParser .getAttributeValue(null, "encoded"))); } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logText(text); return true; } }, LOG_TYPE { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logType(text); return true; } }, LONG_DESCRIPTION { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.longDescription(text); return true; } }, NAME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.groundspeakName(text); return true; } }, NOP { @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { } @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }, PLACED_BY { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.placedBy(text); return true; } }, SHORT_DESCRIPTION { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.shortDescription(text); return true; } }, SYMBOL { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.symbol(text); return true; } }, TERRAIN { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.terrain(text); return true; } }, WPT { @Override public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.endCache(Source.GPX); } @Override public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) { cacheXmlTagHandler.startCache(); cacheXmlTagHandler.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser.getAttributeValue(null, "lon")); } }, WPT_NAME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptName(text); return true; } }, WPT_TIME { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.wptTime(text); return true; } }, LOG_FINDER { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.logFinder(text); return true; } }, GPX_URL { @Override public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { cacheXmlTagHandler.url(text); return true; } }; @SuppressWarnings("unused") public void endTag(CacheXmlTagHandler cacheXmlTagHandler) throws IOException { } @SuppressWarnings("unused") public void startTag(XmlPullParser xmlPullParser, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { } @SuppressWarnings("unused") public boolean text(String text, CacheXmlTagHandler cacheXmlTagHandler) throws IOException { return true; } }
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.R; import com.google.code.geobeagle.database.ClearCachesFromSource; import com.google.code.geobeagle.database.GpxTableWriter; import com.google.code.geobeagle.xmlimport.CacheXmlTagsToSql.CacheXmlTagsToSqlFactory; import com.google.code.geobeagle.xmlimport.EventDispatcher.EventDispatcherFactory; import com.google.code.geobeagle.xmlimport.EventHandlerSqlAndFileWriter.EventHandlerSqlAndFileWriterFactory; import com.google.inject.Inject; import com.google.inject.Provider; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.database.sqlite.SQLiteException; import android.util.Log; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; public class GpxToCache { @SuppressWarnings("serial") public static class CancelException extends Exception { } public static class GpxToCacheFactory { private final AbortState abortState; private final EventDispatcherFactory eventDispatcherFactory; private final EventHandlerSqlAndFileWriterFactory eventHandlerSqlAndFileWriterFactory; private final LocAlreadyLoadedChecker locAlreadyLoadedChecker; private final Provider<ImportWakeLock> importWakeLockProvider; private final ErrorDisplayer errorDisplayer; private final CacheXmlTagsToSqlFactory cacheXmlTagsToSqlFactory; @Inject public GpxToCacheFactory(AbortState abortState, LocAlreadyLoadedChecker locAlreadyLoadedChecker, EventDispatcherFactory eventHelperFactory, EventHandlerSqlAndFileWriterFactory eventHandlerSqlAndFileWriterFactory, Provider<ImportWakeLock> importWakeLockProvider, ErrorDisplayer errorDisplayer, CacheXmlTagsToSqlFactory cacheXmlTagsToSqlFactory) { this.abortState = abortState; this.locAlreadyLoadedChecker = locAlreadyLoadedChecker; this.eventDispatcherFactory = eventHelperFactory; this.eventHandlerSqlAndFileWriterFactory = eventHandlerSqlAndFileWriterFactory; this.importWakeLockProvider = importWakeLockProvider; this.errorDisplayer = errorDisplayer; this.cacheXmlTagsToSqlFactory = cacheXmlTagsToSqlFactory; } public GpxToCache create(MessageHandlerInterface messageHandler, GpxTableWriter gpxTableWriter, ClearCachesFromSource clearCachesFromSource) { CacheXmlTagsToSql cacheXmlTagsToSql = cacheXmlTagsToSqlFactory.create(messageHandler, gpxTableWriter, clearCachesFromSource); EventHandlerSqlAndFileWriter eventHandlerSqlAndFileWriter = eventHandlerSqlAndFileWriterFactory .create(cacheXmlTagsToSql); return new GpxToCache(abortState, locAlreadyLoadedChecker, eventDispatcherFactory.create(eventHandlerSqlAndFileWriter), cacheXmlTagsToSql, importWakeLockProvider, errorDisplayer); } } private final AbortState abortState; private final CacheXmlTagsToSql cacheXmlTagsToSql; private final EventDispatcher eventDispatcher; private final LocAlreadyLoadedChecker locAlreadyLoadedChecker; private final Provider<ImportWakeLock> importWakeLockProvider; public static final int WAKELOCK_DURATION = 15000; private final ErrorDisplayer errorDisplayer; GpxToCache(AbortState abortState, LocAlreadyLoadedChecker locAlreadyLoadedChecker, EventDispatcher eventDispatcher, CacheXmlTagsToSql cacheXmlTagsToSql, Provider<ImportWakeLock> importWakeLockProvider, ErrorDisplayer errorDisplayer) { this.abortState = abortState; this.locAlreadyLoadedChecker = locAlreadyLoadedChecker; this.eventDispatcher = eventDispatcher; this.cacheXmlTagsToSql = cacheXmlTagsToSql; this.importWakeLockProvider = importWakeLockProvider; this.errorDisplayer = errorDisplayer; } public void end() { cacheXmlTagsToSql.end(); } public int load(String path, Reader reader) throws CancelException { try { String filename = new File(path).getName(); importWakeLockProvider.get().acquire(WAKELOCK_DURATION); return loadFile(path, filename, reader); } catch (SQLiteException e) { errorDisplayer.displayError(R.string.error_writing_cache, path + ": " + e.getMessage()); } catch (XmlPullParserException e) { errorDisplayer.displayError(R.string.error_parsing_file, path + ": " + e.getMessage()); } catch (FileNotFoundException e) { errorDisplayer.displayError(R.string.file_not_found, path + ": " + e.getMessage()); } catch (IOException e) { errorDisplayer.displayError(R.string.error_reading_file, path + ": " + e.getMessage()); } catch (CancelException e) { } throw new CancelException(); } private int loadFile(String source, String filename, Reader reader) throws XmlPullParserException, IOException, CancelException { eventDispatcher.setInput(reader); // Just use the filename, not the whole path. cacheXmlTagsToSql.open(filename); boolean markAsComplete = false; try { Log.d("GeoBeagle", this + ": GpxToCache: load"); if (locAlreadyLoadedChecker.isAlreadyLoaded(source)) { return -1; } eventDispatcher.open(); int eventType; for (eventType = eventDispatcher.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = eventDispatcher .next()) { // Log.d("GeoBeagle", "event: " + eventType); if (abortState.isAborted()) { throw new CancelException(); } // File already loaded. if (!eventDispatcher.handleEvent(eventType)) { return -1; } } // Pick up END_DOCUMENT event as well. eventDispatcher.handleEvent(eventType); markAsComplete = true; } finally { eventDispatcher.close(); cacheXmlTagsToSql.close(markAsComplete); } return cacheXmlTagsToSql.getNumberOfCachesLoad(); } public void start() { cacheXmlTagsToSql.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.database.GpxTableWriterGpxFiles; import com.google.inject.Inject; import android.util.Log; import java.io.File; import java.text.SimpleDateFormat; public class LocAlreadyLoadedChecker { private final GpxTableWriterGpxFiles gpxTableWriterGpxFiles; private final SimpleDateFormat simpleDateFormat; // For testing. public LocAlreadyLoadedChecker(GpxTableWriterGpxFiles gpxTableWriterGpxFiles, SimpleDateFormat dateFormat) { this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.simpleDateFormat = dateFormat; } @Inject public LocAlreadyLoadedChecker(GpxTableWriterGpxFiles gpxTableWriterGpxFiles) { this.gpxTableWriterGpxFiles = gpxTableWriterGpxFiles; this.simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); } boolean isAlreadyLoaded(String source) { int len = source.length(); String extension = source.substring(Math.max(0, len - 4), len).toLowerCase(); if (!extension.equalsIgnoreCase(".loc")) return false; File file = new File(source); long lastModified = file.lastModified(); String sqlDate = simpleDateFormat.format(lastModified); Log.d("GeoBeagle", "GET NAME: " + sqlDate + ", " + source + ", " + lastModified); if (gpxTableWriterGpxFiles.isGpxAlreadyLoaded(file.getName(), sqlDate)) { return true; } return false; } }
Java