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.location;
import android.location.Location;
import android.location.LocationManager;
public class LocationControl {
public static class LocationChooser {
/**
* Choose the better of two locations: If one location is newer and more
* accurate, choose that. (This favors the gps). Otherwise, if one
* location is newer, less accurate, but farther away than the sum of
* the two accuracies, choose that. (This favors the network locator if
* you've driven a distance and haven't been able to get a gps fix yet.)
*/
public Location choose(Location location1, Location location2) {
if (location1 == null)
return location2;
if (location2 == null)
return location1;
if (location2.getTime() > location1.getTime()) {
if (location2.getAccuracy() <= location1.getAccuracy())
return location2;
else if (location1.distanceTo(location2) >= location1.getAccuracy()
+ location2.getAccuracy()) {
return location2;
}
}
return location1;
}
}
private final LocationChooser mLocationChooser;
private final LocationManager mLocationManager;
public LocationControl(LocationManager locationManager, LocationChooser locationChooser) {
mLocationManager = locationManager;
mLocationChooser = locationChooser;
}
/*
* (non-Javadoc)
* @see
* com.android.geobrowse.GpsControlI#getLocation(android.content.Context)
*/
public Location getLocation() {
final Location choose = mLocationChooser.choose(mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER), mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
// choose.setLatitude(choose.getLatitude() + .1 * Math.random());
return choose;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.location;
import com.google.code.geobeagle.activity.main.LifecycleManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.LocationListener;
import android.location.LocationManager;
/*
* Handle onPause and onResume for the LocationManager.
*/
public class LocationLifecycleManager implements LifecycleManager {
private final LocationListener mLocationListener;
private final LocationManager mLocationManager;
public LocationLifecycleManager(LocationListener locationListener,
LocationManager locationManager) {
mLocationListener = locationListener;
mLocationManager = locationManager;
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onPause()
*/
public void onPause(Editor editor) {
mLocationManager.removeUpdates(mLocationListener);
}
/*
* (non-Javadoc)
* @see com.google.code.geobeagle.LifecycleManager#onResume()
*/
public void onResume(SharedPreferences preferences) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
mLocationListener);
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
mLocationListener);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.Time;
import android.view.View;
class MeterFader {
private long mLastUpdateTime;
private final MeterBars mMeterView;
private final View mParent;
private final Time mTime;
MeterFader(View parent, MeterBars meterBars, Time time) {
mLastUpdateTime = -1;
mMeterView = meterBars;
mParent = parent;
mTime = time;
}
void paint() {
final long currentTime = mTime.getCurrentTime();
if (mLastUpdateTime == -1)
mLastUpdateTime = currentTime;
long lastUpdateLag = currentTime - mLastUpdateTime;
mMeterView.setLag(lastUpdateLag);
if (lastUpdateLag < 1000)
mParent.postInvalidateDelayed(100);
// Log.d("GeoBeagle", "painting " + lastUpdateLag);
}
void reset() {
mLastUpdateTime = -1;
mParent.postInvalidate();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.Time;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.location.Location;
import android.widget.TextView;
import java.util.Formatter;
class TextLagUpdater {
static interface Lag {
String getFormatted(long currentTime);
}
static class LagImpl implements Lag {
private final long mLastTextLagUpdateTime;
LagImpl(long lastTextLagUpdateTime) {
mLastTextLagUpdateTime = lastTextLagUpdateTime;
}
@Override
public String getFormatted(long currentTime) {
return formatTime((currentTime - mLastTextLagUpdateTime) / 1000);
}
}
static class LagNull implements Lag {
@Override
public String getFormatted(long currentTime) {
return "";
}
}
static class LastKnownLocation implements LastLocation {
private final LagImpl mLagImpl;
public LastKnownLocation(long time) {
mLagImpl = new LagImpl(time);
}
public Lag getLag() {
return mLagImpl;
}
}
static class LastKnownLocationUnavailable implements LastLocation {
private final Lag mLagNull;
public LastKnownLocationUnavailable(LagNull lagNull) {
mLagNull = lagNull;
}
public Lag getLag() {
return mLagNull;
}
}
static interface LastLocation {
Lag getLag();
}
static class LastLocationUnknown implements LastLocation {
private final CombinedLocationManager mCombinedLocationManager;
private final LastKnownLocationUnavailable mLastKnownLocationUnavailable;
public LastLocationUnknown(CombinedLocationManager combinedLocationManager,
LastKnownLocationUnavailable lastKnownLocationUnavailable) {
mCombinedLocationManager = combinedLocationManager;
mLastKnownLocationUnavailable = lastKnownLocationUnavailable;
}
@Override
public Lag getLag() {
return getLastLocation(mCombinedLocationManager.getLastKnownLocation()).getLag();
}
private LastLocation getLastLocation(Location lastKnownLocation) {
if (lastKnownLocation == null)
return mLastKnownLocationUnavailable;
return new LastKnownLocation(lastKnownLocation.getTime());
}
}
private final static StringBuilder aStringBuilder = new StringBuilder();
private final static Formatter mFormatter = new Formatter(aStringBuilder);
static String formatTime(long l) {
aStringBuilder.setLength(0);
if (l < 60) {
return mFormatter.format("%ds", l).toString();
} else if (l < 3600) {
return mFormatter.format("%dm %ds", l / 60, l % 60).toString();
}
return mFormatter.format("%dh %dm", l / 3600, (l % 3600) / 60).toString();
}
private LastLocation mLastLocation;
private final TextView mTextLag;
private final Time mTime;
TextLagUpdater(LastLocationUnknown lastLocationUnknown, TextView textLag, Time time) {
mLastLocation = lastLocationUnknown;
mTextLag = textLag;
mTime = time;
}
void reset(long time) {
mLastLocation = new LastKnownLocation(time);
}
void setDisabled() {
mTextLag.setText("");
}
void updateTextLag() {
mTextLag.setText(mLastLocation.getLag().getFormatted(mTime.getCurrentTime()));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.LocationControlBuffered;
import android.os.Handler;
public class UpdateGpsWidgetRunnable implements Runnable {
private final Handler mHandler;
private final LocationControlBuffered mLocationControlBuffered;
private final Meter mMeterWrapper;
private final TextLagUpdater mTextLagUpdater;
UpdateGpsWidgetRunnable(Handler handler, LocationControlBuffered locationControlBuffered,
Meter meter, TextLagUpdater textLagUpdater) {
mMeterWrapper = meter;
mLocationControlBuffered = locationControlBuffered;
mTextLagUpdater = textLagUpdater;
mHandler = handler;
}
public void run() {
// Update the lag time and the orientation.
mTextLagUpdater.updateTextLag();
mMeterWrapper.setAzimuth(mLocationControlBuffered.getAzimuth());
mHandler.postDelayed(this, 500);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
/*
* Displays the accuracy (graphically) and azimuth of the gps.
*/
import android.graphics.Color;
import android.widget.TextView;
class MeterBars {
private final TextView mBarsAndAzimuth;
private final MeterFormatter mMeterFormatter;
MeterBars(TextView textView, MeterFormatter meterFormatter) {
mBarsAndAzimuth = textView;
mMeterFormatter = meterFormatter;
}
void set(float accuracy, float azimuth) {
final String center = String.valueOf((int)azimuth);
final int barCount = mMeterFormatter.accuracyToBarCount(accuracy);
final String barsToMeterText = mMeterFormatter.barsToMeterText(barCount, center);
mBarsAndAzimuth.setText(barsToMeterText);
}
void setLag(long lag) {
mBarsAndAzimuth.setTextColor(Color.argb(mMeterFormatter.lagToAlpha(lag), 147, 190, 38));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.R;
import android.content.Context;
class MeterFormatter {
private static String mMeterLeft;
private static String mMeterRight;
private static String mDegreesSymbol;
private static StringBuilder mStringBuilder;
MeterFormatter(Context context) {
mMeterLeft = context.getString(R.string.meter_left);
mMeterRight = context.getString(R.string.meter_right);
mDegreesSymbol = context.getString(R.string.degrees_symbol);
mStringBuilder = new StringBuilder();
}
int accuracyToBarCount(float accuracy) {
return Math.min(mMeterLeft.length(), (int)(Math.log(Math.max(1, accuracy)) / Math.log(2)));
}
String barsToMeterText(int bars, String center) {
mStringBuilder.setLength(0);
mStringBuilder.append('[').append(mMeterLeft.substring(mMeterLeft.length() - bars)).append(
center + mDegreesSymbol).append(mMeterRight.substring(0, bars)).append(']');
return mStringBuilder.toString();
}
int lagToAlpha(long milliseconds) {
return Math.max(128, 255 - (int)(milliseconds >> 3));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import android.widget.TextView;
class Meter {
private float mAccuracy;
private final TextView mAccuracyView;
private float mAzimuth;
private final MeterBars mMeterView;
Meter(MeterBars meterBars, TextView accuracyView) {
mAccuracyView = accuracyView;
mMeterView = meterBars;
}
void setAccuracy(float accuracy, DistanceFormatter distanceFormatter) {
mAccuracy = accuracy;
distanceFormatter.formatDistance(accuracy);
mAccuracyView.setText(distanceFormatter.formatDistance(accuracy));
mMeterView.set(accuracy, mAzimuth);
}
void setAzimuth(float azimuth) {
mAzimuth = azimuth;
mMeterView.set(mAccuracy, azimuth);
}
void setDisabled() {
mAccuracyView.setText("");
mMeterView.set(Float.MAX_VALUE, 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.gpsstatuswidget;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationProvider;
import android.os.Bundle;
import android.widget.TextView;
public class GpsStatusWidgetDelegate implements HasDistanceFormatter, LocationListener {
private final CombinedLocationManager mCombinedLocationManager;
private DistanceFormatter mDistanceFormatter;
private final MeterFader mMeterFader;
private final Meter mMeterWrapper;
private final TextView mProvider;
private final Context mContext;
private final TextView mStatus;
private final TextLagUpdater mTextLagUpdater;
public GpsStatusWidgetDelegate(CombinedLocationManager combinedLocationManager,
DistanceFormatter distanceFormatter, Meter meter, MeterFader meterFader,
TextView provider, Context context, TextView status, TextLagUpdater textLagUpdater) {
mCombinedLocationManager = combinedLocationManager;
mDistanceFormatter = distanceFormatter;
mMeterFader = meterFader;
mMeterWrapper = meter;
mProvider = provider;
mContext = context;
mStatus = status;
mTextLagUpdater = textLagUpdater;
}
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "GpsStatusWidget onLocationChanged " + location);
if (location == null)
return;
if (!mCombinedLocationManager.isProviderEnabled()) {
mMeterWrapper.setDisabled();
mTextLagUpdater.setDisabled();
return;
}
mProvider.setText(location.getProvider());
mMeterWrapper.setAccuracy(location.getAccuracy(), mDistanceFormatter);
mMeterFader.reset();
mTextLagUpdater.reset(location.getTime());
}
public void onProviderDisabled(String provider) {
mStatus.setText(provider + " DISABLED");
}
public void onProviderEnabled(String provider) {
mStatus.setText(provider + " ENABLED");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
mStatus.setText(provider + " status: "
+ mContext.getString(R.string.out_of_service));
break;
case LocationProvider.AVAILABLE:
mStatus.setText(provider + " status: " + mContext.getString(R.string.available));
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mStatus.setText(provider + " status: "
+ mContext.getString(R.string.temporarily_unavailable));
break;
}
}
public void paint() {
mMeterFader.paint();
}
public void setDistanceFormatter(DistanceFormatter distanceFormatter) {
mDistanceFormatter = distanceFormatter;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.preferences.EditPreferences;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSettings extends MenuActionBase {
private final Activity mActivity;
public MenuActionSettings(Activity activity) {
super(R.string.menu_settings);
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, EditPreferences.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.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.searchonline.SearchOnlineActivity;
import android.app.Activity;
import android.content.Intent;
public class MenuActionSearchOnline extends MenuActionBase {
private final Activity mActivity;
public MenuActionSearchOnline(Activity activity) {
super(R.string.menu_search_online);
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, SearchOnlineActivity.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.actions;
public interface MenuAction {
public void act();
/** Must be the id of a resource string - used to set label */
public int 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.actions;
public abstract class MenuActionBase implements MenuAction {
private final int mId;
public MenuActionBase(int id) {
mId = id;
}
@Override
public int getId() {
return mId;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.actions;
import android.content.res.Resources;
import android.util.Log;
import android.view.Menu;
import java.util.ArrayList;
public class MenuActions {
private ArrayList<MenuAction> mMenuActions = new ArrayList<MenuAction>();
private final Resources mResources;
public MenuActions(Resources resources) {
mResources = resources;
}
public MenuActions(Resources resources, MenuAction[] menuActions) {
mResources = resources;
for (int ix = 0; ix < menuActions.length; ix++) {
add(menuActions[ix]);
}
}
public boolean act(int itemId) {
for (MenuAction action : mMenuActions) {
if (action.getId() == itemId) {
action.act();
return true;
}
}
return false;
}
public void add(MenuAction action) {
mMenuActions.add(action);
}
/** Creates an Options Menu from the items in this MenuActions */
public boolean onCreateOptionsMenu(Menu menu) {
if (mMenuActions.isEmpty()) {
Log.w("GeoBeagle", "MenuActions.onCreateOptionsMenu: menu is empty, will not be shown");
return false;
}
menu.clear();
int ix = 0;
for (MenuAction action : mMenuActions) {
final int id = action.getId();
menu.add(0, id, ix, mResources.getString(id));
ix++;
}
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.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.CacheListActivity;
import android.app.Activity;
import android.content.Intent;
public class MenuActionCacheList extends MenuActionBase {
private Activity mActivity;
public MenuActionCacheList(Activity activity) {
super(R.string.menu_cache_list);
mActivity = activity;
}
@Override
public void act() {
mActivity.startActivity(new Intent(mActivity, CacheListActivity.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.actions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.EditCacheActivity;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Intent;
public class MenuActionEditGeocache extends MenuActionBase {
private final GeoBeagle mParent;
public MenuActionEditGeocache(GeoBeagle parent) {
super(R.string.menu_edit_geocache);
mParent = parent;
}
@Override
public void act() {
final Intent intent = new Intent(mParent, EditCacheActivity.class);
intent.putExtra("geocache", mParent.getGeocache());
mParent.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.database;
import com.google.code.geobeagle.database.DatabaseDI.CacheReaderCursorFactory;
import android.database.Cursor;
public class CacheReader {
public static final String[] READER_COLUMNS = new String[] {
"Latitude", "Longitude", "Id", "Description", "Source", "CacheType", "Difficulty",
"Terrain", "Container"
};
public static final String SQL_QUERY_LIMIT = "1000";
private final CacheReaderCursorFactory mCacheReaderCursorFactory;
private final ISQLiteDatabase mSqliteWrapper;
CacheReader(ISQLiteDatabase sqliteWrapper, CacheReaderCursorFactory cacheReaderCursorFactory) {
mSqliteWrapper = sqliteWrapper;
mCacheReaderCursorFactory = cacheReaderCursorFactory;
}
public int getTotalCount() {
Cursor cursor = mSqliteWrapper
.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
return count;
}
public CacheReaderCursor open(double latitude, double longitude, WhereFactory whereFactory,
String limit) {
String where = whereFactory.getWhere(mSqliteWrapper, latitude, longitude);
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, CacheReader.READER_COLUMNS,
where, null, null, null, limit);
if (!cursor.moveToFirst()) {
cursor.close();
return null;
}
return mCacheReaderCursorFactory.create(cursor);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public class OpenHelperDelegate {
public void onCreate(ISQLiteDatabase db) {
db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V11);
db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10);
db.execSQL(Database.SQL_CREATE_IDX_LATITUDE);
db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE);
db.execSQL(Database.SQL_CREATE_IDX_SOURCE);
}
public void onUpgrade(ISQLiteDatabase db, int oldVersion) {
if (oldVersion < 9) {
db.execSQL(Database.SQL_DROP_CACHE_TABLE);
db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V08);
db.execSQL(Database.SQL_CREATE_IDX_LATITUDE);
db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE);
db.execSQL(Database.SQL_CREATE_IDX_SOURCE);
}
if (oldVersion < 10) {
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DELETE_ME);
db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10);
}
if (oldVersion < 11) {
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CACHE_TYPE);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CONTAINER);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DIFFICULTY);
db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_TERRAIN);
// This date has to precede 2000-01-01 (due to a bug in
// CacheTagSqlWriter.java in v10).
db.execSQL("UPDATE GPX SET ExportTime = \"1990-01-01\"");
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.Geocache;
//TODO: Merge into Geocache class
public class LocationSaver {
private final DbFrontend mDbFrontend;
public LocationSaver(DbFrontend dbFrontend) {
mDbFrontend = dbFrontend;
}
public void saveLocation(Geocache geocache) {
final CharSequence id = geocache.getId();
CacheWriter cacheWriter = mDbFrontend.getCacheWriter();
cacheWriter.startWriting();
cacheWriter.insertAndUpdateCache(id, geocache.getName(), geocache.getLatitude(), geocache
.getLongitude(), geocache.getSourceType(), geocache.getSourceName(), geocache
.getCacheType(), 0, 0, 0);
cacheWriter.stopWriting();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public class WhereFactoryAllCaches implements WhereFactory {
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
return 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.database;
import com.google.code.geobeagle.database.DatabaseDI.SearchFactory;
import android.database.Cursor;
import android.util.Log;
public class WhereFactoryNearestCaches implements WhereFactory {
static class BoundingBox {
public static final String[] ID_COLUMN = new String[] {
"Id"
};
private final ISQLiteDatabase mSqliteWrapper;
private final WhereStringFactory mWhereStringFactory;
private final double mLatitude;
private final double mLongitude;
BoundingBox(double latitude, double longitude, ISQLiteDatabase sqliteWrapper,
WhereStringFactory whereStringFactory) {
mLatitude = latitude;
mLongitude = longitude;
mSqliteWrapper = sqliteWrapper;
mWhereStringFactory = whereStringFactory;
}
int getCount(float degreesDelta, int maxCount) {
String where = mWhereStringFactory.getWhereString(mLatitude, mLongitude, degreesDelta);
Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, ID_COLUMN, where, null, null,
null, "" + maxCount);
int count = cursor.getCount();
Log.d("GeoBeagle", "search: " + degreesDelta + ", count/maxCount: " + count + "/"
+ maxCount + " where: " + where);
cursor.close();
return count;
}
}
static class Search {
private final BoundingBox mBoundingBox;
private final SearchDown mSearchDown;
private final SearchUp mSearchUp;
public Search(BoundingBox boundingBox, SearchDown searchDown, SearchUp searchUp) {
mBoundingBox = boundingBox;
mSearchDown = searchDown;
mSearchUp = searchUp;
}
public float search(float guess, int target) {
if (mBoundingBox.getCount(guess, target + 1) > target)
return mSearchDown.search(guess, target);
return mSearchUp.search(guess, target);
}
}
static public class SearchDown {
private final BoundingBox mHasValue;
private final float mMin;
public SearchDown(BoundingBox boundingBox, float min) {
mHasValue = boundingBox;
mMin = min;
}
public float search(float guess, int targetMin) {
final float lowerGuess = guess / WhereFactoryNearestCaches.DISTANCE_MULTIPLIER;
if (lowerGuess < mMin)
return guess;
if (mHasValue.getCount(lowerGuess, targetMin + 1) >= targetMin)
return search(lowerGuess, targetMin);
return guess;
}
}
static class SearchUp {
private final BoundingBox mBoundingBox;
private final float mMax;
public SearchUp(BoundingBox boundingBox, float max) {
mBoundingBox = boundingBox;
mMax = max;
}
public float search(float guess, int targetMin) {
final float nextGuess = guess * WhereFactoryNearestCaches.DISTANCE_MULTIPLIER;
if (nextGuess > mMax)
return guess;
if (mBoundingBox.getCount(guess, targetMin) < targetMin) {
return search(nextGuess, targetMin);
}
return guess;
}
}
// 1 degree ~= 111km
static final float DEGREES_DELTA = 0.1f;
static final float DISTANCE_MULTIPLIER = 1.414f;
static final int GUESS_MAX = 180;
static final float GUESS_MIN = 0.01f;
static final int MAX_NUMBER_OF_CACHES = 30;
public static class WhereStringFactory {
String getWhereString(double latitude, double longitude, float degrees) {
double latLow = latitude - degrees;
double latHigh = latitude + degrees;
double lat_radians = Math.toRadians(latitude);
double cos_lat = Math.cos(lat_radians);
double lonLow = Math.max(-180, longitude - degrees / cos_lat);
double lonHigh = Math.min(180, longitude + degrees / cos_lat);
return "Latitude > " + latLow + " AND Latitude < " + latHigh + " AND Longitude > "
+ lonLow + " AND Longitude < " + lonHigh;
}
}
private float mLastGuess = 0.1f;
private final SearchFactory mSearchFactory;
private final WhereStringFactory mWhereStringFactory;
public WhereFactoryNearestCaches(SearchFactory searchFactory,
WhereStringFactory whereStringFactory) {
mSearchFactory = searchFactory;
mWhereStringFactory = whereStringFactory;
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
mLastGuess = mSearchFactory.createSearch(latitude, longitude, GUESS_MIN, GUESS_MAX,
sqliteWrapper).search(mLastGuess, MAX_NUMBER_OF_CACHES);
return mWhereStringFactory.getWhereString(latitude, longitude, mLastGuess);
}
}
| Java |
package com.google.code.geobeagle.database;
public interface HasValue {
int get(float search, int maxCaches);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import android.database.Cursor;
public class CacheReaderCursor {
private final Cursor mCursor;
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
private final GeocacheFactory mGeocacheFactory;
public CacheReaderCursor(Cursor cursor, GeocacheFactory geocacheFactory,
DbToGeocacheAdapter dbToGeocacheAdapter) {
mCursor = cursor;
mGeocacheFactory = geocacheFactory;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
public void close() {
mCursor.close();
}
public Geocache getCache() {
String sourceName = mCursor.getString(4);
CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(Integer.parseInt(mCursor
.getString(5)));
int difficulty = Integer.parseInt(mCursor.getString(6));
int terrain = Integer.parseInt(mCursor.getString(7));
int container = Integer.parseInt(mCursor.getString(8));
return mGeocacheFactory.create(mCursor.getString(2), mCursor.getString(3), mCursor
.getDouble(0), mCursor.getDouble(1), mDbToGeocacheAdapter
.sourceNameToSourceType(sourceName), sourceName, cacheType, difficulty, terrain,
container);
}
public int count() {
return mCursor.getCount();
}
public boolean moveToNext() {
return mCursor.moveToNext();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.R;
public class FilterNearestCaches {
private boolean mIsFiltered = true;
private final WhereFactory mWhereFactories[];
public FilterNearestCaches(WhereFactoryAllCaches whereFactoryAllCaches,
WhereFactory whereFactoryNearestCaches) {
mWhereFactories = new WhereFactory[] {
whereFactoryAllCaches, whereFactoryNearestCaches
};
}
public int getMenuString() {
return mIsFiltered ? R.string.menu_show_all_caches : R.string.menu_show_nearest_caches;
}
public int getTitleText() {
return mIsFiltered ? R.string.cache_list_title : R.string.cache_list_title_all;
}
public WhereFactory getWhereFactory() {
return mWhereFactories[mIsFiltered ? 1 : 0];
}
public void toggle() {
mIsFiltered = !mIsFiltered;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
/**
* Where clause with limits set during construction, not when calling getWhere()
*/
public class WhereFactoryFixedArea implements WhereFactory {
private final double mLatLow;
private final double mLonLow;
private final double mLatHigh;
private final double mLonHigh;
public WhereFactoryFixedArea(double latLow, double lonLow, double latHigh, double lonHigh) {
mLatLow = Math.min(latLow, latHigh);
mLonLow = Math.min(lonLow, lonHigh);
mLatHigh = Math.max(latLow, latHigh);
mLonHigh = Math.max(lonLow, lonHigh);
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
return "Latitude >= " + mLatLow + " AND Latitude < " + mLatHigh + " AND Longitude >= "
+ mLonLow + " AND Longitude < " + mLonHigh;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public class WhereFactoryWithinRange implements WhereFactory {
private double mSpanLat;
private double mSpanLon;
public WhereFactoryWithinRange(double spanLat, double spanLon) {
mSpanLat = spanLat;
mSpanLon = spanLon;
}
@Override
public String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude) {
double latLow = latitude - mSpanLat/2.0;
double latHigh = latitude + mSpanLat/2.0;
double lonLow = longitude - mSpanLon/2.0;
double lonHigh = longitude + mSpanLon/2.0;
return "Latitude > " + latLow + " AND Latitude < " + latHigh +
" AND Longitude > " + lonLow + " AND Longitude < " + lonHigh;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.database.DatabaseDI;
import com.google.code.geobeagle.database.DatabaseDI.GeoBeagleSqliteOpenHelper;
/**
* Will develop to represent the front-end to access a database. It takes
* responsibility to open and close the actual database connection without
* involving the clients of this class.
*/
public class DbFrontend {
CacheReader mCacheReader;
Context mContext;
GeoBeagleSqliteOpenHelper open;
boolean mIsDatabaseOpen;
CacheWriter mCacheWriter;
ISQLiteDatabase mDatabase;
public DbFrontend(Context context) {
mContext = context;
mIsDatabaseOpen = false;
}
public void openDatabase() {
if (mIsDatabaseOpen)
return;
Log.d("GeoBeagle", "DbFrontend.openDatabase()");
mIsDatabaseOpen = true;
open = new GeoBeagleSqliteOpenHelper(mContext);
final SQLiteDatabase sqDb = open.getReadableDatabase();
mDatabase = new DatabaseDI.SQLiteWrapper(sqDb);
mCacheReader = DatabaseDI.createCacheReader(mDatabase);
}
public void closeDatabase() {
if (!mIsDatabaseOpen)
return;
Log.d("GeoBeagle", "DbFrontend.closeDatabase()");
mIsDatabaseOpen = false;
open.close();
mCacheWriter = null;
mDatabase = null;
}
public ArrayList<Geocache> loadCaches(double latitude, double longitude,
WhereFactory whereFactory) {
Log.d("GeoBeagle", "DbFrontend.loadCaches");
openDatabase();
CacheReaderCursor cursor = mCacheReader.open(latitude, longitude, whereFactory, null);
ArrayList<Geocache> geocaches = new ArrayList<Geocache>();
if (cursor != null) {
do {
geocaches.add(cursor.getCache());
} while (cursor.moveToNext());
cursor.close();
}
return geocaches;
}
public CacheWriter getCacheWriter() {
if (mCacheWriter != null)
return mCacheWriter;
openDatabase();
mCacheWriter = DatabaseDI.createCacheWriter(mDatabase);
return mCacheWriter;
}
public int count(int latitude, int longitude, WhereFactoryFixedArea whereFactory) {
openDatabase();
Cursor countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES
+ " WHERE " + whereFactory.getWhere(mDatabase, latitude, longitude), null);
countCursor.moveToFirst();
int count = countCursor.getInt(0);
countCursor.close();
Log.d("GeoBeagle", "DbFrontEnd.count:" + count);
return count;
}
/*
* public void onPause() { closeDatabase(); }
*/
/*
* public void onResume() { //Lazy evaluation - open database when needed }
*/
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
public class Geocaches {
private final ArrayList<Geocache> mGeocaches;
public Geocaches() {
mGeocaches = new ArrayList<Geocache>();
}
public void add(Geocache geocache) {
mGeocaches.add(geocache);
}
public void clear() {
mGeocaches.clear();
}
public ArrayList<Geocache> getAll() {
return mGeocaches;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
public interface WhereFactory {
public abstract String getWhere(ISQLiteDatabase sqliteWrapper, double latitude, double longitude);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.GeocacheFactory.Source;
/**
* @author sng
*/
public class CacheWriter {
public static final String SQLS_CLEAR_EARLIER_LOADS[] = {
Database.SQL_DELETE_OLD_CACHES, Database.SQL_DELETE_OLD_GPX,
Database.SQL_RESET_DELETE_ME_CACHES, Database.SQL_RESET_DELETE_ME_GPX
};
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
private final ISQLiteDatabase mSqlite;
CacheWriter(ISQLiteDatabase sqlite, DbToGeocacheAdapter dbToGeocacheAdapter) {
mSqlite = sqlite;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
public void clearCaches(String source) {
mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source);
}
/**
* Deletes any cache/gpx entries marked delete_me, then marks all remaining
* gpx-based caches, and gpx entries with delete_me = 1.
*/
public void clearEarlierLoads() {
for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) {
mSqlite.execSQL(sql);
}
}
public void deleteCache(CharSequence id) {
mSqlite.execSQL(Database.SQL_DELETE_CACHE, id);
}
public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude,
double longitude, Source sourceType, String sourceName, CacheType cacheType,
int difficulty, int terrain, int container) {
mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double(
longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName),
cacheType.toInt(), difficulty, terrain, container);
}
/**
* Return True if the gpx is already loaded. Mark this gpx and its caches in
* the database to protect them from being nuked when the load is complete.
*
* @param gpxName
* @param gpxTime
* @return
*/
public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) {
// TODO:countResults is slow; replace with a query, and moveToFirst.
boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX,
Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0;
if (gpxAlreadyLoaded) {
mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName);
mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName);
}
return gpxAlreadyLoaded;
}
public void startWriting() {
mSqlite.beginTransaction();
}
public void stopWriting() {
// TODO: abort if no writes--otherwise sqlite is unhappy.
mSqlite.setTransactionSuccessful();
mSqlite.endTransaction();
}
public void writeGpx(String gpxName, String pocketQueryExportTime) {
mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import android.database.Cursor;
public interface ISQLiteDatabase {
void beginTransaction();
void close();
int countResults(String table, String sql, String... args);
void endTransaction();
void execSQL(String s, Object... bindArg1);
Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs);
Cursor rawQuery(String string, String[] object);
void setTransactionSuccessful();
boolean isOpen();
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.database;
import com.google.code.geobeagle.GeocacheFactory.Source;
public class DbToGeocacheAdapter {
public Source sourceNameToSourceType(String sourceName) {
if (sourceName.equals("intent"))
return Source.WEB_URL;
else if (sourceName.equals("mylocation"))
return Source.MY_LOCATION;
else if (sourceName.toLowerCase().endsWith((".loc")))
return Source.LOC;
return Source.GPX;
}
public String sourceTypeToSourceName(Source source, String sourceName) {
if (source == Source.MY_LOCATION)
return "mylocation";
else if (source == Source.WEB_URL)
return "intent";
return sourceName;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface.OnClickListener;
public class ErrorDisplayer {
static class DisplayErrorRunnable implements Runnable {
private final Builder mAlertDialogBuilder;
DisplayErrorRunnable(Builder alertDialogBuilder) {
mAlertDialogBuilder = alertDialogBuilder;
}
public void run() {
mAlertDialogBuilder.create().show();
}
}
private final Activity mActivity;
private final OnClickListener mOnClickListener;
public ErrorDisplayer(Activity activity, OnClickListener onClickListener) {
mActivity = activity;
mOnClickListener = onClickListener;
}
public void displayError(int resId, Object... args) {
final Builder alertDialogBuilder = new Builder(mActivity);
alertDialogBuilder.setMessage(String.format((String)mActivity.getText(resId), args));
alertDialogBuilder.setNeutralButton("Ok", mOnClickListener);
mActivity.runOnUiThread(new DisplayErrorRunnable(alertDialogBuilder));
}
}
| Java |
package com.google.code.geobeagle.formatting;
public class DistanceFormatterImperial implements DistanceFormatter {
public CharSequence formatDistance(float distance) {
if (distance == -1) {
return "";
}
final float miles = distance / 1609.344f;
if (miles > 0.05)
return String.format("%1$1.2fmi", miles);
final int yards = (int)(miles * (5280 / 3));
return String.format("%1$1dyd", yards);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.formatting;
public interface DistanceFormatter {
public abstract CharSequence formatDistance(float distance);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.formatting;
public class DistanceFormatterMetric implements DistanceFormatter {
public CharSequence formatDistance(float distance) {
if (distance == -1) {
return "";
}
if (distance >= 1000) {
return String.format("%1$1.2fkm", distance / 1000.0);
}
return String.format("%1$dm", (int)distance);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.NullSortStrategy;
import com.google.code.geobeagle.activity.cachelist.presenter.SortStrategy;
import com.google.code.geobeagle.location.LocationControl;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
public class LocationControlBuffered implements LocationListener {
public static class GpsDisabledLocation implements IGpsLocation {
public float distanceTo(IGpsLocation dest) {
return Float.MAX_VALUE;
}
public float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation) {
return Float.MAX_VALUE;
}
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
return Float.MAX_VALUE;
}
}
public static class GpsEnabledLocation implements IGpsLocation {
private final float mLatitude;
private final float mLongitude;
public GpsEnabledLocation(float latitude, float longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
public float distanceTo(IGpsLocation gpsLocation) {
return gpsLocation.distanceToGpsEnabledLocation(this);
}
public float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation) {
return Float.MAX_VALUE;
}
public float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation) {
final float calculateDistanceFast = GeocacheVector.calculateDistanceFast(mLatitude,
mLongitude, gpsEnabledLocation.mLatitude, gpsEnabledLocation.mLongitude);
return calculateDistanceFast;
}
}
public static interface IGpsLocation {
public float distanceTo(IGpsLocation dest);
float distanceToGpsDisabledLocation(GpsDisabledLocation gpsLocation);
float distanceToGpsEnabledLocation(GpsEnabledLocation gpsEnabledLocation);
}
private final DistanceSortStrategy mDistanceSortStrategy;
private GpsDisabledLocation mGpsDisabledLocation;
private IGpsLocation mGpsLocation;
private Location mLocation;
private LocationControl mLocationControl;
private final NullSortStrategy mNullSortStrategy;
private float mAzimuth;
public LocationControlBuffered(LocationControl locationControl,
DistanceSortStrategy distanceSortStrategy, NullSortStrategy nullSortStrategy,
GpsDisabledLocation gpsDisabledLocation, IGpsLocation lastGpsLocation,
Location lastLocation) {
mLocationControl = locationControl;
mDistanceSortStrategy = distanceSortStrategy;
mNullSortStrategy = nullSortStrategy;
mGpsDisabledLocation = gpsDisabledLocation;
mGpsLocation = lastGpsLocation;
mLocation = lastLocation;
}
public IGpsLocation getGpsLocation() {
return mGpsLocation;
}
public Location getLocation() {
return mLocation;
}
public SortStrategy getSortStrategy() {
if (mLocation == null)
return mNullSortStrategy;
return mDistanceSortStrategy;
}
public void onLocationChanged(Location location) {
mLocation = mLocationControl.getLocation();
if (location == null) {
mGpsLocation = mGpsDisabledLocation;
} else {
mGpsLocation = new GpsEnabledLocation((float)location.getLatitude(), (float)location
.getLongitude());
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void setAzimuth(float azimuth) {
mAzimuth = azimuth;
}
public float getAzimuth() {
return mAzimuth;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.hardware.SensorListener;
@SuppressWarnings("deprecation")
public class CompassListener implements SensorListener {
private final Refresher mRefresher;
private final LocationControlBuffered mLocationControlBuffered;
private float mLastAzimuth;
public CompassListener(Refresher refresher,
LocationControlBuffered locationControlBuffered, float lastAzimuth) {
mRefresher = refresher;
mLocationControlBuffered = locationControlBuffered;
mLastAzimuth = lastAzimuth;
}
// public void onAccuracyChanged(Sensor sensor, int accuracy) {
// }
// public void onSensorChanged(SensorEvent event) {
// onSensorChanged(SensorManager.SENSOR_ORIENTATION, event.values);
// }
public void onAccuracyChanged(int sensor, int accuracy) {
}
public void onSensorChanged(int sensor, float[] values) {
final float currentAzimuth = values[0];
if (Math.abs(currentAzimuth - mLastAzimuth) > 5) {
// Log.d("GeoBeagle", "azimuth now " + sensor +", " +
// currentAzimuth);
mLocationControlBuffered.setAzimuth(((int)currentAzimuth / 5) * 5);
mRefresher.refresh();
mLastAzimuth = currentAzimuth;
}
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
public interface Refresher {
public void refresh();
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.WhereFactoryFixedArea;
import com.google.code.geobeagle.xmlimport.GpxImporterDI.Toaster;
import java.util.ArrayList;
class QueryManager {
/**
* We need to cache "needs loading" status because we might be zoomed out so
* far we see no caches. In that situation, the compass will attempt to
* refresh us every second, and we'll query the database over and over again
* to learn that we have too many caches for the same set of points.
*/
static class CachedNeedsLoading {
private GeoPoint mOldBottomRight;
private GeoPoint mOldTopLeft;
public CachedNeedsLoading(GeoPoint topLeft, GeoPoint bottomRight) {
mOldTopLeft = topLeft;
mOldBottomRight = bottomRight;
}
boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) {
if (mOldTopLeft.equals(newTopLeft) && mOldBottomRight.equals(newBottomRight))
return false;
mOldTopLeft = newTopLeft;
mOldBottomRight = newBottomRight;
return true;
}
}
static class PeggedLoader {
private final DbFrontend mDbFrontend;
private final ArrayList<Geocache> mNullList;
private final Toaster mToaster;
private boolean mTooManyCaches;
PeggedLoader(DbFrontend dbFrontend, ArrayList<Geocache> nullList, Toaster toaster) {
mNullList = nullList;
mDbFrontend = dbFrontend;
mToaster = toaster;
mTooManyCaches = false;
}
ArrayList<Geocache> load(int latMin, int lonMin, int latMax, int lonMax,
WhereFactoryFixedArea where, int[] newBounds) {
if (mDbFrontend.count(0, 0, where) > 1500) {
latMin = latMax = lonMin = lonMax = 0;
if (!mTooManyCaches) {
mToaster.showToast();
mTooManyCaches = true;
}
return mNullList;
}
mTooManyCaches = false;
newBounds[0] = latMin;
newBounds[1] = lonMin;
newBounds[2] = latMax;
newBounds[3] = lonMax;
return mDbFrontend.loadCaches(0, 0, where);
}
}
private final CachedNeedsLoading mCachedNeedsLoading;
private int[] mLatLonMinMax; // i.e. latmin, lonmin, latmax, lonmax
private final PeggedLoader mPeggedLoader;
QueryManager(PeggedLoader peggedLoader, CachedNeedsLoading cachedNeedsLoading,
int[] latLonMinMax) {
mLatLonMinMax = latLonMinMax;
mPeggedLoader = peggedLoader;
mCachedNeedsLoading = cachedNeedsLoading;
}
ArrayList<Geocache> load(GeoPoint newTopLeft, GeoPoint newBottomRight) {
// Expand the area by the resolution so we get complete patches for the
// density map. This isn't needed for the pins overlay, but it doesn't
// hurt either.
final int lonMin = newTopLeft.getLongitudeE6()
- DensityPatchManager.RESOLUTION_LONGITUDE_E6;
final int latMax = newTopLeft.getLatitudeE6() + DensityPatchManager.RESOLUTION_LATITUDE_E6;
final int latMin = newBottomRight.getLatitudeE6()
- DensityPatchManager.RESOLUTION_LATITUDE_E6;
final int lonMax = newBottomRight.getLongitudeE6()
+ DensityPatchManager.RESOLUTION_LONGITUDE_E6;
final WhereFactoryFixedArea where = new WhereFactoryFixedArea((double)latMin / 1E6,
(double)lonMin / 1E6, (double)latMax / 1E6, (double)lonMax / 1E6);
ArrayList<Geocache> list = mPeggedLoader.load(latMin, lonMin, latMax, lonMax, where,
mLatLonMinMax);
return list;
}
boolean needsLoading(GeoPoint newTopLeft, GeoPoint newBottomRight) {
return mCachedNeedsLoading.needsLoading(newTopLeft, newBottomRight)
&& (newTopLeft.getLatitudeE6() > mLatLonMinMax[2]
|| newTopLeft.getLongitudeE6() < mLatLonMinMax[1]
|| newBottomRight.getLatitudeE6() < mLatLonMinMax[0] || newBottomRight
.getLongitudeE6() > mLatLonMinMax[3]);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
import java.util.List;
class DensityPatchManager {
private List<DensityMatrix.DensityPatch> mDensityPatches;
private final QueryManager mQueryManager;
public static final double RESOLUTION_LATITUDE = 0.01;
public static final double RESOLUTION_LONGITUDE = 0.02;
public static final int RESOLUTION_LATITUDE_E6 = (int)(RESOLUTION_LATITUDE * 1E6);
public static final int RESOLUTION_LONGITUDE_E6 = (int)(RESOLUTION_LONGITUDE * 1E6);
DensityPatchManager(List<DensityMatrix.DensityPatch> patches, QueryManager queryManager) {
mDensityPatches = patches;
mQueryManager = queryManager;
}
public List<DensityMatrix.DensityPatch> getDensityPatches(MapView mMapView) {
Projection projection = mMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mMapView.getRight(), mMapView.getBottom());
if (!mQueryManager.needsLoading(newTopLeft, newBottomRight)) {
return mDensityPatches;
}
ArrayList<Geocache> list = mQueryManager.load(newTopLeft, newBottomRight);
DensityMatrix densityMatrix = new DensityMatrix(DensityPatchManager.RESOLUTION_LATITUDE,
DensityPatchManager.RESOLUTION_LONGITUDE);
densityMatrix.addCaches(list);
mDensityPatches = densityMatrix.getDensityPatches();
// Log.d("GeoBeagle", "Density patches:" + mDensityPatches.size());
return mDensityPatches;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import java.util.HashMap;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import com.google.code.geobeagle.CacheType;
class CacheDrawables {
private static Drawable loadAndSizeDrawable(Resources resources, int res) {
Drawable drawable = resources.getDrawable(res);
int width = drawable.getIntrinsicWidth();
int height = drawable.getIntrinsicHeight();
drawable.setBounds(-width/2, -height, width/2, 0);
return drawable;
}
private final HashMap<CacheType, Drawable> mCacheDrawables;
CacheDrawables(Resources resources) {
final CacheType[] cacheTypes = CacheType.values();
mCacheDrawables = new HashMap<CacheType, Drawable>(cacheTypes.length);
for (CacheType cacheType : cacheTypes) {
final Drawable loadAndSizeDrawable = loadAndSizeDrawable(resources, cacheType
.iconMap());
mCacheDrawables.put(cacheType, loadAndSizeDrawable);
}
}
Drawable get(CacheType cacheType) {
return mCacheDrawables.get(cacheType);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.Overlay;
import android.util.Log;
import java.util.List;
public class OverlayManager {
static final int DENSITY_MAP_ZOOM_THRESHOLD = 13;
private final CachePinsOverlayFactory mCachePinsOverlayFactory;
private final DensityOverlay mDensityOverlay;
private final GeoMapView mGeoMapView;
private final List<Overlay> mMapOverlays;
private boolean mUsesDensityMap;
public OverlayManager(GeoMapView geoMapView, List<Overlay> mapOverlays,
DensityOverlay densityOverlay, CachePinsOverlayFactory cachePinsOverlayFactory,
boolean usesDensityMap) {
mGeoMapView = geoMapView;
mMapOverlays = mapOverlays;
mDensityOverlay = densityOverlay;
mCachePinsOverlayFactory = cachePinsOverlayFactory;
mUsesDensityMap = usesDensityMap;
}
public void selectOverlay() {
final int zoomLevel = mGeoMapView.getZoomLevel();
Log.d("GeoBeagle", "Zoom: " + zoomLevel);
boolean newZoomUsesDensityMap = zoomLevel < OverlayManager.DENSITY_MAP_ZOOM_THRESHOLD;
if (newZoomUsesDensityMap && mUsesDensityMap)
return;
mUsesDensityMap = newZoomUsesDensityMap;
mMapOverlays.set(0, mUsesDensityMap ? mDensityOverlay : mCachePinsOverlayFactory
.getCachePinsOverlay());
}
public boolean usesDensityMap() {
return mUsesDensityMap;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.MapView;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.actions.MenuActions;
import android.view.Menu;
import android.view.MenuItem;
public class GeoMapActivityDelegate {
public static class MenuActionToggleSatellite extends MenuActionBase {
private final MapView mMapView;
public MenuActionToggleSatellite(MapView mapView) {
super(R.string.menu_toggle_satellite);
mMapView = mapView;
}
@Override
public void act() {
mMapView.setSatellite(!mMapView.isSatellite());
}
}
private final GeoMapView mMapView;
private final MenuActions mMenuActions;
public GeoMapActivityDelegate(GeoMapView mapView, MenuActions menuActions) {
mMapView = mapView;
mMenuActions = menuActions;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
public boolean onMenuOpened(Menu menu) {
menu.findItem(R.string.menu_toggle_satellite).setTitle(
mMapView.isSatellite() ? R.string.map_view : R.string.satellite_view);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.Geocache;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.Log;
import java.util.ArrayList;
public class CachePinsOverlayFactory {
private final CacheItemFactory mCacheItemFactory;
private CachePinsOverlay mCachePinsOverlay;
private final Context mContext;
private final Drawable mDefaultMarker;
private final GeoMapView mGeoMapView;
private QueryManager mQueryManager;
public CachePinsOverlayFactory(GeoMapView geoMapView, Context context, Drawable defaultMarker,
CacheItemFactory cacheItemFactory, CachePinsOverlay cachePinsOverlay,
QueryManager queryManager) {
mGeoMapView = geoMapView;
mContext = context;
mDefaultMarker = defaultMarker;
mCacheItemFactory = cacheItemFactory;
mCachePinsOverlay = cachePinsOverlay;
mQueryManager = queryManager;
}
public CachePinsOverlay getCachePinsOverlay() {
Log.d("GeoBeagle", "refresh Caches");
// final CacheListDelegateDI.Timing timing = new
// CacheListDelegateDI.Timing();
Projection projection = mGeoMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(mGeoMapView.getRight(), mGeoMapView
.getBottom());
if (!mQueryManager.needsLoading(newTopLeft, newBottomRight))
return mCachePinsOverlay;
// timing.lap("Loaded caches");
// timing.start();
ArrayList<Geocache> list = mQueryManager.load(newTopLeft, newBottomRight);
mCachePinsOverlay = new CachePinsOverlay(mCacheItemFactory, mContext, mDefaultMarker, list);
return mCachePinsOverlay;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Projection;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import com.google.code.geobeagle.activity.map.DensityMatrix.DensityPatch;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import java.util.List;
public class DensityOverlayDelegate {
private static final double RESOLUTION_LATITUDE_E6 = (DensityPatchManager.RESOLUTION_LATITUDE * 1E6);
private static final double RESOLUTION_LONGITUDE_E6 = (DensityPatchManager.RESOLUTION_LONGITUDE * 1E6);
private final Paint mPaint;
private final Rect mPatchRect;
private final Point mScreenBottomRight;
private final Point mScreenTopLeft;
private final CacheListDelegateDI.Timing mTiming;
private final DensityPatchManager mDensityPatchManager;
public DensityOverlayDelegate(Rect patchRect, Paint paint, Point screenLow, Point screenHigh,
DensityPatchManager densityPatchManager) {
mTiming = new CacheListDelegateDI.Timing();
mPatchRect = patchRect;
mPaint = paint;
mScreenTopLeft = screenLow;
mScreenBottomRight = screenHigh;
mDensityPatchManager = densityPatchManager;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (shadow)
return; // No shadow layer
// Log.d("GeoBeagle", ">>>>>>>>>>Starting draw");
List<DensityMatrix.DensityPatch> densityPatches = mDensityPatchManager
.getDensityPatches(mapView);
mTiming.start();
final Projection projection = mapView.getProjection();
final GeoPoint newGeoTopLeft = projection.fromPixels(0, 0);
final GeoPoint newGeoBottomRight = projection.fromPixels(mapView.getRight(), mapView
.getBottom());
projection.toPixels(newGeoTopLeft, mScreenTopLeft);
projection.toPixels(newGeoBottomRight, mScreenBottomRight);
final int topLatitudeE6 = newGeoTopLeft.getLatitudeE6();
final int leftLongitudeE6 = newGeoTopLeft.getLongitudeE6();
final int bottomLatitudeE6 = newGeoBottomRight.getLatitudeE6();
final int rightLongitudeE6 = newGeoBottomRight.getLongitudeE6();
final double pixelsPerLatE6Degrees = (double)(mScreenBottomRight.y - mScreenTopLeft.y)
/ (double)(bottomLatitudeE6 - topLatitudeE6);
final double pixelsPerLonE6Degrees = (double)(mScreenBottomRight.x - mScreenTopLeft.x)
/ (double)(rightLongitudeE6 - leftLongitudeE6);
int patchCount = 0;
for (DensityPatch patch : densityPatches) {
final int patchLatLowE6 = patch.getLatLowE6();
final int patchLonLowE6 = patch.getLonLowE6();
int xOffset = (int)((patchLonLowE6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int xEnd = (int)((patchLonLowE6 + RESOLUTION_LONGITUDE_E6 - leftLongitudeE6) * pixelsPerLonE6Degrees);
int yOffset = (int)((patchLatLowE6 - topLatitudeE6) * pixelsPerLatE6Degrees);
int yEnd = (int)((patchLatLowE6 + RESOLUTION_LATITUDE_E6 - topLatitudeE6) * pixelsPerLatE6Degrees);
mPatchRect.set(xOffset, yEnd, xEnd, yOffset);
// Log.d("GeoBeagle", "patchrect: " + mPatchRect.bottom + ", " +
// mPatchRect.left
// + ", " + mPatchRect.top + ", " + mPatchRect.right);
mPaint.setAlpha(patch.getAlpha());
canvas.drawRect(mPatchRect, mPaint);
patchCount++;
}
// mTiming.lap("Done drawing");
// Log.d("GeoBeagle", "patchcount: " + patchCount);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class DensityMatrix {
public static class DensityPatch {
private int mCacheCount;
private final int mLatLowE6;
private final int mLonLowE6;
public DensityPatch(double latLow, double lonLow) {
mCacheCount = 0;
mLatLowE6 = (int)(latLow * 1E6);
mLonLowE6 = (int)(lonLow * 1E6);
}
public int getAlpha() {
return Math.min(210, 10 + 32 * mCacheCount);
}
public int getCacheCount() {
return mCacheCount;
}
public int getLatLowE6() {
return mLatLowE6;
}
public int getLonLowE6() {
return mLonLowE6;
}
public void setCacheCount(int count) {
mCacheCount = count;
}
}
/** Mapping lat -> (mapping lon -> cache count) */
private TreeMap<Integer, Map<Integer, DensityPatch>> mBuckets = new TreeMap<Integer, Map<Integer, DensityPatch>>();
private double mLatResolution;
private double mLonResolution;
public DensityMatrix(double latResolution, double lonResolution) {
mLatResolution = latResolution;
mLonResolution = lonResolution;
}
public void addCaches(ArrayList<Geocache> list) {
for (Geocache cache : list) {
incrementBucket(cache.getLatitude(), cache.getLongitude());
}
}
public List<DensityPatch> getDensityPatches() {
ArrayList<DensityPatch> result = new ArrayList<DensityPatch>();
for (Integer latBucket : mBuckets.keySet()) {
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
result.addAll(lonMap.values());
}
return result;
}
private void incrementBucket(double lat, double lon) {
Integer latBucket = (int)Math.floor(lat / mLatResolution);
Integer lonBucket = (int)Math.floor(lon / mLonResolution);
Map<Integer, DensityPatch> lonMap = mBuckets.get(latBucket);
if (lonMap == null) {
// Key didn't exist in map
lonMap = new TreeMap<Integer, DensityPatch>();
mBuckets.put(latBucket, lonMap);
}
DensityPatch patch = lonMap.get(lonBucket);
if (patch == null) {
patch = new DensityPatch(latBucket * mLatResolution, lonBucket * mLonResolution);
lonMap.put(lonBucket, patch);
}
patch.setCacheCount(patch.getCacheCount() + 1);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
class CacheItemFactory {
private final CacheDrawables mCacheDrawables;
CacheItemFactory(CacheDrawables cacheDrawables) {
mCacheDrawables = cacheDrawables;
}
CacheItem createCacheItem(Geocache geocache) {
final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), (String)geocache
.getId(), geocache);
cacheItem.setMarker(mCacheDrawables.get(geocache.getCacheType()));
return cacheItem;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity;
import com.google.code.geobeagle.Geocache;
import android.content.SharedPreferences.Editor;
public class ActivitySaver {
private final Editor mEditor;
static final String LAST_ACTIVITY = "lastActivity";
ActivitySaver(Editor editor) {
mEditor = editor;
}
public void save(ActivityType activityType) {
mEditor.putInt("lastActivity", activityType.toInt());
mEditor.commit();
}
public void save(ActivityType activityType, Geocache geocache) {
mEditor.putInt("lastActivity", activityType.toInt());
geocache.writeToPrefs(mEditor);
mEditor.commit();
}
}
| Java |
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceFormatterManager;
import com.google.code.geobeagle.location.CombinedLocationListener;
import com.google.code.geobeagle.location.CombinedLocationManager;
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 CompassListener mCompassListener;
private final DistanceFormatterManager mDistanceFormatterManager;
private final LocationControlBuffered mLocationControlBuffered;
private final SensorManager mSensorManager;
private final WebView mWebView;
public SearchOnlineActivityDelegate(WebView webView, SensorManager sensorManager,
CompassListener compassListener, CombinedLocationManager combinedLocationManager,
CombinedLocationListener combinedLocationListener,
LocationControlBuffered locationControlBuffered,
DistanceFormatterManager distanceFormatterManager, ActivitySaver activitySaver) {
mSensorManager = sensorManager;
mCompassListener = compassListener;
mCombinedLocationListener = combinedLocationListener;
mCombinedLocationManager = combinedLocationManager;
mLocationControlBuffered = locationControlBuffered;
mWebView = webView;
mDistanceFormatterManager = distanceFormatterManager;
mActivitySaver = activitySaver;
}
public void configureWebView(JsInterface jsInterface) {
mWebView.loadUrl("file:///android_asset/search.html");
WebSettings webSettings = mWebView.getSettings();
webSettings.setSavePassword(false);
webSettings.setSaveFormData(false);
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
mWebView.setBackgroundColor(Color.BLACK);
mWebView.addJavascriptInterface(jsInterface, "gb");
}
public void onPause() {
mCombinedLocationManager.removeUpdates();
mSensorManager.unregisterListener(mCompassListener);
mActivitySaver.save(ActivityType.SEARCH_ONLINE);
}
public void onResume() {
mCombinedLocationManager.requestLocationUpdates(1000, 0, mLocationControlBuffered);
mCombinedLocationManager.requestLocationUpdates(1000, 0, mCombinedLocationListener);
mSensorManager.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mDistanceFormatterManager.setFormatter();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.net.Uri;
import java.util.Locale;
class JsInterface {
private final LocationControlBuffered mLocationControlBuffered;
private final JsInterfaceHelper mHelper;
static class JsInterfaceHelper {
private final Activity mActivity;
public JsInterfaceHelper(Activity activity) {
mActivity = activity;
}
public void launch(String uri) {
mActivity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
}
public String getTemplate(int ix) {
return mActivity.getResources().getStringArray(R.array.nearest_objects)[ix];
}
public String getNS(double latitude) {
return latitude > 0 ? "N" : "S";
}
public String getEW(double longitude) {
return longitude > 0 ? "E" : "W";
}
}
public JsInterface(LocationControlBuffered locationControlBuffered,
JsInterfaceHelper jsInterfaceHelper) {
mHelper = jsInterfaceHelper;
mLocationControlBuffered = locationControlBuffered;
}
public int atlasQuestOrGroundspeak(int ix) {
final Location location = mLocationControlBuffered.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
mHelper.launch(String.format(Locale.US, uriTemplate, location.getLatitude(), location
.getLongitude()));
return 0;
}
public int openCaching(int ix) {
final Location location = mLocationControlBuffered.getLocation();
final String uriTemplate = mHelper.getTemplate(ix);
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
final String NS = mHelper.getNS(latitude);
final String EW = mHelper.getEW(longitude);
final double abs_latitude = Math.abs(latitude);
final double abs_longitude = Math.abs(longitude);
final int lat_h = (int)abs_latitude;
final double lat_m = 60 * (abs_latitude - lat_h);
final int lon_h = (int)abs_longitude;
final double lon_m = 60 * (abs_longitude - lon_h);
mHelper.launch(String.format(Locale.US, uriTemplate, NS, lat_h, lat_m, EW, lon_h, lon_m));
return 0;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.searchonline;
import com.google.code.geobeagle.Refresher;
public class NullRefresher implements Refresher {
public void refresh() {
}
}
| Java |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
/*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.google.code.geobeagle.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Paint.Align;
import android.graphics.Paint.Style;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.SensorListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
@SuppressWarnings("deprecation")
public class RadarView extends View implements SensorListener, LocationListener {
private static final long RETAIN_GPS_MILLIS = 10000L;
private Paint mGridPaint;
private Paint mErasePaint;
private float mOrientation;
private double mTargetLat;
private double mTargetLon;
private double mMyLocationLat;
private double mMyLocationLon;
private int mLastScale = -1;
private static float KM_PER_METERS = 0.001f;
private static float METERS_PER_KM = 1000f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using metric units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mMetricScaleChoices[] = {
100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100,
200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This
* array is for metric measurements.)
*/
private static float mMetricDisplayUnitsPerKm[] = {
METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for metric measurements.)
*/
private static String mMetricDisplayFormats[] = {
"%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm",
"%.0fkm", "%.0fkm"
};
private static float KM_PER_YARDS = 0.0009144f;
private static float KM_PER_MILES = 1.609344f;
private static float YARDS_PER_KM = 1093.6133f;
private static float MILES_PER_KM = 0.621371192f;
/**
* These are the list of choices for the radius of the outer circle on the
* screen when using standard units. All items are in kilometers. This array
* is used to choose the scale of the radar display.
*/
private static double mEnglishScaleChoices[] = {
100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS,
1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES,
20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES,
400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES,
10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES
};
/**
* Once the scale is chosen, this array is used to convert the number of
* kilometers on the screen to an integer. (Note that for short distances we
* use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This
* array is for standard measurements.)
*/
private static float mEnglishDisplayUnitsPerKm[] = {
YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM,
MILES_PER_KM, MILES_PER_KM
};
/**
* This array holds the formatting string used to display the distance to
* the target. (This array is for standard measurements.)
*/
private static String mEnglishDisplayFormats[] = {
"%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi",
"%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi"
};
private boolean mHaveLocation = false; // True when we have our location
private TextView mDistanceView;
private double mDistance; // Distance to target, in KM
private double mBearing; // Bearing to target, in degrees
// Ratio of the distance to the target to the radius of the outermost ring
// on the radar screen
private float mDistanceRatio;
private Bitmap mBlip; // The bitmap used to draw the target
// True if the display should use metric units; false if the display should
// use standard units
private boolean mUseMetric;
// Time in millis for the last time GPS reported a location
private long mLastGpsFixTime = 0L;
// The last location reported by the network provider. Use this if we can't
// get a location from GPS
private Location mNetworkLocation;
private boolean mGpsAvailable; // True if GPS is reporting a location
// True if the network provider is reporting a location
private boolean mNetworkAvailable;
private TextView mBearingView;
private float mMyLocationAccuracy;
private TextView mAccuracyView;
private final String mDegreesSymbol;
private Path mCompassPath;
private final Paint mCompassPaint;
private final Paint mArrowPaint;
private final Path mArrowPath;
public RadarView(Context context) {
this(context, null);
}
public RadarView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RadarView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mDegreesSymbol = context.getString(R.string.degrees_symbol);
// Paint used for the rings and ring text
mGridPaint = new Paint();
mGridPaint.setColor(0xFF00FF00);
mGridPaint.setAntiAlias(true);
mGridPaint.setStyle(Style.STROKE);
mGridPaint.setStrokeWidth(1.0f);
mGridPaint.setTextSize(10.0f);
mGridPaint.setTextAlign(Align.CENTER);
mCompassPaint = new Paint();
mCompassPaint.setColor(0xFF00FF00);
mCompassPaint.setAntiAlias(true);
mCompassPaint.setStyle(Style.STROKE);
mCompassPaint.setStrokeWidth(1.0f);
mCompassPaint.setTextSize(10.0f);
mCompassPaint.setTextAlign(Align.CENTER);
// Paint used to erase the rectangle behind the ring text
mErasePaint = new Paint();
mErasePaint.setColor(0xFF191919);
mErasePaint.setStyle(Style.FILL);
// Paint used for the arrow
mArrowPaint = new Paint();
mArrowPaint.setColor(Color.WHITE);
mArrowPaint.setAntiAlias(true);
mArrowPaint.setStyle(Style.STROKE);
mArrowPaint.setStrokeWidth(16);
mArrowPaint.setAlpha(228);
mArrowPath = new Path();
mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap();
mCompassPath = new Path();
}
/**
* Sets the target to track on the radar
*
* @param latE6 Latitude of the target, multiplied by 1,000,000
* @param lonE6 Longitude of the target, multiplied by 1,000,000
*/
public void setTarget(int latE6, int lonE6) {
mTargetLat = latE6 / (double)GeoUtils.MILLION;
mTargetLon = lonE6 / (double)GeoUtils.MILLION;
}
/**
* Sets the view that we will use to report distance
*
* @param t The text view used to report distance
*/
public void setDistanceView(TextView d, TextView b, TextView a) {
mDistanceView = d;
mBearingView = b;
mAccuracyView = a;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int center = Math.min(getHeight(), getWidth()) / 2;
int radius = center - 8;
// Draw the rings
final Paint gridPaint = mGridPaint;
gridPaint.setAlpha(100);
canvas.drawCircle(center, center, radius, gridPaint);
canvas.drawCircle(center, center, radius * 3 / 4, gridPaint);
canvas.drawCircle(center, center, radius >> 1, gridPaint);
canvas.drawCircle(center, center, radius >> 2, gridPaint);
int blipRadius = (int)(mDistanceRatio * radius);
// Draw horizontal and vertical lines
canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint);
canvas.drawLine(center, center + (radius >> 2) - 6, center, center + radius + 6, gridPaint);
canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint);
canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint);
if (mHaveLocation) {
double northAngle = Math.toRadians(-mOrientation) - (Math.PI / 2);
float northX = (float)Math.cos(northAngle);
float northY = (float)Math.sin(northAngle);
final int compassLength = radius >> 2;
float tipX = northX * compassLength, tipY = northY * compassLength;
float baseX = northY * 8, baseY = -northX * 8;
double bearingToTarget = mBearing - mOrientation;
double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2);
float cos = (float)Math.cos(drawingAngle);
float sin = (float)Math.sin(drawingAngle);
mArrowPath.reset();
mArrowPath.moveTo(center - cos * radius, center - sin * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
final double arrowRight = drawingAngle + Math.PI / 2;
final double arrowLeft = drawingAngle - Math.PI / 2;
mArrowPath.moveTo(center + (float)Math.cos(arrowRight) * radius, center
+ (float)Math.sin(arrowRight) * radius);
mArrowPath.lineTo(center + cos * radius, center + sin * radius);
mArrowPath.lineTo(center + (float)Math.cos(arrowLeft) * radius, center
+ (float)Math.sin(arrowLeft) * radius);
canvas.drawPath(mArrowPath, mArrowPaint);
drawCompassArrow(canvas, center, mCompassPaint, tipX, tipY, baseX, baseY, Color.RED);
drawCompassArrow(canvas, center, mCompassPaint, -tipX, -tipY, baseX, baseY, Color.GRAY);
gridPaint.setAlpha(255);
canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8, center + (sin * blipRadius)
- 8, gridPaint);
}
}
private void drawCompassArrow(Canvas canvas, int center, final Paint gridPaint, float tipX,
float tipY, float baseX, float baseY, int color) {
gridPaint.setStyle(Paint.Style.FILL_AND_STROKE);
gridPaint.setColor(color);
gridPaint.setAlpha(255);
mCompassPath.reset();
mCompassPath.moveTo(center + baseX, center + baseY);
mCompassPath.lineTo(center + tipX, center + tipY);
mCompassPath.lineTo(center - baseX, center - baseY);
mCompassPath.close();
canvas.drawPath(mCompassPath, gridPaint);
gridPaint.setStyle(Paint.Style.STROKE);
}
public void onAccuracyChanged(int sensor, int accuracy) {
}
/**
* Called when we get a new value from the compass
*
* @see android.hardware.SensorListener#onSensorChanged(int, float[])
*/
public void onSensorChanged(int sensor, float[] values) {
mOrientation = values[0];
double bearingToTarget = mBearing - mOrientation;
updateBearing(bearingToTarget);
postInvalidate();
}
/**
* Called when a location provider has a new location to report
*
* @see android.location.LocationListener#onLocationChanged(android.location.Location)
*/
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "radarview::onLocationChanged");
if (!mHaveLocation) {
mHaveLocation = true;
}
final long now = SystemClock.uptimeMillis();
boolean useLocation = false;
final String provider = location.getProvider();
if (LocationManager.GPS_PROVIDER.equals(provider)) {
// Use GPS if available
mLastGpsFixTime = SystemClock.uptimeMillis();
useLocation = true;
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
// Use network provider if GPS is getting stale
useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS;
if (mNetworkLocation == null) {
mNetworkLocation = new Location(location);
} else {
mNetworkLocation.set(location);
}
mLastGpsFixTime = 0L;
}
if (useLocation) {
mMyLocationLat = location.getLatitude();
mMyLocationLon = location.getLongitude();
mMyLocationAccuracy = location.getAccuracy();
mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon);
mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon);
updateDistance(mDistance);
double bearingToTarget = mBearing - mOrientation;
updateBearing(bearingToTarget);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
/**
* Called when a location provider has changed its availability.
*
* @see android.location.LocationListener#onStatusChanged(java.lang.String,
* int, android.os.Bundle)
*/
public void onStatusChanged(String provider, int status, Bundle extras) {
//Log.d("GeoBeagle", "onStatusChanged " + provider + ", " + status);
if (LocationManager.GPS_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mGpsAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mGpsAvailable = false;
if (mNetworkLocation != null && mNetworkAvailable) {
// Fallback to network location
mLastGpsFixTime = 0L;
onLocationChanged(mNetworkLocation);
} else {
handleUnknownLocation();
}
break;
}
} else if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
switch (status) {
case LocationProvider.AVAILABLE:
mNetworkAvailable = true;
break;
case LocationProvider.OUT_OF_SERVICE:
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mNetworkAvailable = false;
if (!mGpsAvailable) {
handleUnknownLocation();
}
break;
}
}
}
/**
* Called when we no longer have a valid location.
*/
public void handleUnknownLocation() {
mHaveLocation = false;
mDistanceView.setText("");
mAccuracyView.setText("");
mBearingView.setText("");
}
/**
* Update state to reflect whether we are using metric or standard units.
*
* @param useMetric True if the display should use metric units
*/
public void setUseImperial(boolean useImperial) {
mUseMetric = !useImperial;
mLastScale = -1;
if (mHaveLocation) {
updateDistance(mDistance);
}
invalidate();
}
private void updateBearing(double bearing) {
bearing = (bearing + 720) % 360;
if (mHaveLocation) {
final String sBearing = ((int)bearing / 5) * 5 + mDegreesSymbol;
mBearingView.setText(sBearing);
}
}
/**
* Update our state to reflect a new distance to the target. This may
* require choosing a new scale for the radar rings.
*
* @param distanceKm The new distance to the target
* @param bearing
*/
private void updateDistance(double distanceKm) {
final double[] scaleChoices;
final float[] displayUnitsPerKm;
final String[] displayFormats;
String distanceStr = null;
String accuracyStr = null;
if (mUseMetric) {
scaleChoices = mMetricScaleChoices;
displayUnitsPerKm = mMetricDisplayUnitsPerKm;
displayFormats = mMetricDisplayFormats;
} else {
scaleChoices = mEnglishScaleChoices;
displayUnitsPerKm = mEnglishDisplayUnitsPerKm;
displayFormats = mEnglishDisplayFormats;
}
final int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
if (distanceKm < scaleChoices[i] || i == (count - 1)) {
String format = displayFormats[i];
double distanceDisplay = distanceKm * displayUnitsPerKm[i];
if (mLastScale != i) {
mLastScale = i;
}
mDistanceRatio = (float)(mDistance / scaleChoices[mLastScale]);
distanceStr = String.format(format, distanceDisplay);
break;
}
}
if (mMyLocationAccuracy != 0.0)
accuracyStr = formatDistance(scaleChoices, displayUnitsPerKm, displayFormats);
mDistanceView.setText(distanceStr);
mAccuracyView.setText("+/-" + accuracyStr);
}
private String formatDistance(final double[] scaleChoices, final float[] displayUnitsPerKm,
final String[] displayFormats) {
int count = scaleChoices.length;
for (int i = 0; i < count; i++) {
final float myLocationAccuracyKm = mMyLocationAccuracy / 1000;
if (myLocationAccuracyKm < scaleChoices[i] || i == (count - 1)) {
final String format = displayFormats[i];
return String.format(format, myLocationAccuracyKm * displayUnitsPerKm[i]);
}
}
return "";
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.database.LocationSaver;
import android.content.Intent;
public class IncomingIntentHandler {
private GeocacheFactory mGeocacheFactory;
private GeocacheFromIntentFactory mGeocacheFromIntentFactory;
IncomingIntentHandler(GeocacheFactory geocacheFactory,
GeocacheFromIntentFactory geocacheFromIntentFactory) {
mGeocacheFactory = geocacheFactory;
mGeocacheFromIntentFactory = geocacheFromIntentFactory;
}
Geocache maybeGetGeocacheFromIntent(Intent intent, Geocache defaultGeocache,
LocationSaver locationSaver) {
if (intent != null) {
final String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_VIEW) && intent.getType() == null) {
return mGeocacheFromIntentFactory
.viewCacheFromMapsIntent(intent, locationSaver);
} else if (action.equals(GeocacheListController.SELECT_CACHE)) {
Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
if (geocache == null)
geocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
return geocache;
}
}
}
return defaultGeocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.net.UrlQuerySanitizer;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
public static final String[] geocachingQueryParam = new String[] {
"q"
};
// #Wildwood Park, Saratoga, CA(The Nut Case #89882)
private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)");
private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)");
private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.]+)[^\\d]*");
private static final Pattern PAT_LATLON = Pattern
.compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)");
private static final Pattern PAT_LATLONDEC = Pattern.compile("([\\d.]+)\\s+([\\d.]+)");
private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]");
private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*");
private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]");
public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) {
final double fAbsDegrees = Math.abs(fDegrees);
final int dAbsDegrees = (int)fAbsDegrees;
return String.format(Locale.US, (fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees,
60.0 * (fAbsDegrees - dAbsDegrees));
}
public static double parseCoordinate(CharSequence string) {
int sign = 1;
final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string);
if (negsignMatcher.find()) {
sign = -1;
}
final Matcher signMatcher = PAT_SIGN.matcher(string);
string = signMatcher.replaceAll("");
final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string);
double degrees = 0.0;
for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) {
degrees += Double.parseDouble(dmsMatcher.group(1)) / scale;
}
return sign * degrees;
}
public static CharSequence[] parseDescription(CharSequence string) {
Matcher matcher = PAT_ATLASQUEST.matcher(string);
if (matcher.matches())
return new CharSequence[] {
"LB" + matcher.group(2).trim(), matcher.group(1).trim()
};
return new CharSequence[] {
string, ""
};
}
public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer,
ValueSanitizer valueSanitizer) {
sanitizer.registerParameters(geocachingQueryParam, valueSanitizer);
sanitizer.parseQuery(query);
return sanitizer.getValue("q");
}
public static CharSequence[] splitCoordsAndDescription(CharSequence location) {
Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(2).trim(), matcher.group(1).trim()
};
}
matcher = PAT_PAREN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
}
// No description.
return new CharSequence[] {
location, ""
};
}
public static CharSequence[] splitLatLon(CharSequence string) {
Matcher matcherDecimal = PAT_LATLONDEC.matcher(string);
if (matcherDecimal.matches()) {
return new String[] {
matcherDecimal.group(1).trim(), matcherDecimal.group(2).trim()
};
}
Matcher matcher = PAT_LATLON.matcher(string);
if (matcher.matches())
return new String[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
return null;
}
public static CharSequence[] splitLatLonDescription(CharSequence location) {
CharSequence coordsAndDescription[] = splitCoordsAndDescription(location);
CharSequence latLon[] = splitLatLon(coordsAndDescription[0]);
CharSequence[] parseDescription = parseDescription(coordsAndDescription[1]);
return new CharSequence[] {
latLon[0], latLon[1], parseDescription[0], parseDescription[1]
};
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.net.Uri;
public class UriParser {
public Uri parse(String uriString) {
return Uri.parse(uriString);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.activity.main.intents.IntentStarter;
import android.app.Activity;
public class OnCacheButtonClickListenerBuilder {
private final Activity mActivity;
private final ErrorDisplayer mErrorDisplayer;
public OnCacheButtonClickListenerBuilder(Activity activity, ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mActivity = activity;
}
public void set(int id, IntentStarter intentStarter, String errorString) {
mActivity.findViewById(id).setOnClickListener(new CacheButtonOnClickListener(
intentStarter, errorString, mErrorDisplayer));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Provider;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.view.View;
public class WebPageAndDetailsButtonEnabler {
interface CheckButton {
public void check(Geocache geocache);
}
public static class CheckButtons {
private final CheckButton[] mCheckButtons;
public CheckButtons(CheckButton[] checkButtons) {
mCheckButtons = checkButtons;
}
public void check(Geocache geocache) {
for (CheckButton checkButton : mCheckButtons) {
checkButton.check(geocache);
}
}
}
public static class CheckDetailsButton implements CheckButton {
private final View mDetailsButton;
public CheckDetailsButton(View checkDetailsButton) {
mDetailsButton = checkDetailsButton;
}
public void check(Geocache geocache) {
mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX);
}
}
public static class CheckWebPageButton implements CheckButton {
private final View mWebPageButton;
public CheckWebPageButton(View webPageButton) {
mWebPageButton = webPageButton;
}
public void check(Geocache geocache) {
final Provider contentProvider = geocache.getContentProvider();
mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK
|| contentProvider == GeocacheFactory.Provider.ATLAS_QUEST
|| contentProvider == GeocacheFactory.Provider.OPENCACHING);
}
}
private final CheckButtons mCheckButtons;
private final GeoBeagle mGeoBeagle;
public WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, CheckButtons checkButtons) {
mGeoBeagle = geoBeagle;
mCheckButtons = checkButtons;
}
public void check() {
mCheckButtons.check(mGeoBeagle.getGeocache());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import com.google.code.geobeagle.cachedetails.CacheDetailsLoader;
import android.app.AlertDialog.Builder;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
public class CacheDetailsOnClickListener implements View.OnClickListener {
private final Builder mAlertDialogBuilder;
private final CacheDetailsLoader mCacheDetailsLoader;
private final LayoutInflater mEnv;
private final GeoBeagle mGeoBeagle;
public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder,
LayoutInflater env, CacheDetailsLoader cacheDetailsLoader) {
mAlertDialogBuilder = alertDialogBuilder;
mEnv = env;
mCacheDetailsLoader = cacheDetailsLoader;
mGeoBeagle = geoBeagle;
}
public void onClick(View v) {
View detailsView = mEnv.inflate(R.layout.cache_details, null);
CharSequence id = mGeoBeagle.getGeocache().getId();
mAlertDialogBuilder.setTitle(id);
mAlertDialogBuilder.setView(detailsView);
WebView webView = (WebView)detailsView.findViewById(R.id.webview);
webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(id), "text/html", "utf-8",
"about:blank");
mAlertDialogBuilder.create().show();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController;
import com.google.code.geobeagle.activity.main.Util;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class EditCacheActivityDelegate {
public static class CancelButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
public CancelButtonOnClickListener(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
// TODO: replace magic number.
mActivity.setResult(-1, null);
mActivity.finish();
}
}
public static class EditCache {
private final GeocacheFactory mGeocacheFactory;
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(GeocacheFactory geocacheFactory, EditText id, EditText name,
EditText latitude, EditText longitude) {
mGeocacheFactory = geocacheFactory;
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return mGeocacheFactory.create(mId.getText(), mName.getText(), Util
.parseCoordinate(mLatitude.getText()), Util.parseCoordinate(mLongitude
.getText()), mOriginalGeocache.getSourceType(), mOriginalGeocache
.getSourceName(), mOriginalGeocache.getCacheType(), mOriginalGeocache
.getDifficulty(), mOriginalGeocache.getTerrain(), mOriginalGeocache
.getContainer());
}
void set(Geocache geocache) {
mOriginalGeocache = geocache;
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mLatitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()));
mLongitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
mLatitude.requestFocus();
}
}
public static class SetButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
private final EditCache mGeocacheView;
private final LocationSaver mLocationSaver;
public SetButtonOnClickListener(Activity activity, EditCache editCache,
LocationSaver locationSaver) {
mActivity = activity;
mGeocacheView = editCache;
mLocationSaver = locationSaver;
}
public void onClick(View v) {
final Geocache geocache = mGeocacheView.get();
mLocationSaver.saveLocation(geocache);
final Intent i = new Intent();
i.setAction(GeocacheListController.SELECT_CACHE);
i.putExtra("geocache", geocache);
mActivity.setResult(0, i);
mActivity.finish();
}
}
private final CancelButtonOnClickListener mCancelButtonOnClickListener;
private final GeocacheFactory mGeocacheFactory;
private final Activity mParent;
private final LocationSaver mLocationSaver;
public EditCacheActivityDelegate(Activity parent,
CancelButtonOnClickListener cancelButtonOnClickListener,
GeocacheFactory geocacheFactory, LocationSaver locationSaver) {
mParent = parent;
mCancelButtonOnClickListener = cancelButtonOnClickListener;
mGeocacheFactory = geocacheFactory;
mLocationSaver = locationSaver;
}
public void onCreate() {
mParent.setContentView(R.layout.cache_edit);
}
public void onResume() {
final Intent intent = mParent.getIntent();
final Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
final EditCache editCache = new EditCache(mGeocacheFactory, (EditText)mParent
.findViewById(R.id.edit_id), (EditText)mParent.findViewById(R.id.edit_name),
(EditText)mParent.findViewById(R.id.edit_latitude), (EditText)mParent
.findViewById(R.id.edit_longitude));
editCache.set(geocache);
final SetButtonOnClickListener setButtonOnClickListener = new SetButtonOnClickListener(
mParent, editCache, mLocationSaver);
((Button)mParent.findViewById(R.id.edit_set)).setOnClickListener(setButtonOnClickListener);
((Button)mParent.findViewById(R.id.edit_cancel))
.setOnClickListener(mCancelButtonOnClickListener);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import android.location.Location;
public class MyLocationProvider {
private final ErrorDisplayer mErrorDisplayer;
private final LocationControlBuffered mLocationControlBuffered;
public MyLocationProvider(LocationControlBuffered locationControlBuffered,
ErrorDisplayer errorDisplayer) {
mLocationControlBuffered = locationControlBuffered;
mErrorDisplayer = errorDisplayer;
}
public Location getLocation() {
Location location = mLocationControlBuffered.getLocation();
if (null == location) {
mErrorDisplayer.displayError(R.string.error_cant_get_location);
}
return location;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.GeoUtils;
import com.google.code.geobeagle.activity.main.RadarView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
public class GeocacheViewer {
public interface AttributeViewer {
void setImage(int attributeValue);
}
public static class LabelledAttributeViewer implements AttributeViewer {
private final UnlabelledAttributeViewer mUnlabelledAttributeViewer;
private final TextView mLabel;
public LabelledAttributeViewer(int[] images, TextView label, ImageView imageView) {
mUnlabelledAttributeViewer = new UnlabelledAttributeViewer(images, imageView);
mLabel = label;
}
@Override
public void setImage(int attributeValue) {
mUnlabelledAttributeViewer.setImage(attributeValue);
mLabel.setVisibility(attributeValue == 0 ? View.GONE : View.VISIBLE);
}
}
public static class UnlabelledAttributeViewer implements AttributeViewer {
private final int[] mImages;
private final ImageView mImageView;
public UnlabelledAttributeViewer(int[] images, ImageView imageView) {
mImages = images;
mImageView = imageView;
}
public void setImage(int attributeValue) {
if (attributeValue == 0) {
mImageView.setVisibility(View.GONE);
return;
}
mImageView.setImageResource(mImages[attributeValue - 1]);
mImageView.setVisibility(View.VISIBLE);
}
}
public static class NameViewer {
private final TextView mName;
public NameViewer(TextView name) {
mName = name;
}
void set(CharSequence name) {
if (name.length() == 0) {
mName.setVisibility(View.GONE);
return;
}
mName.setText(name);
mName.setVisibility(View.VISIBLE);
}
}
public static final int CONTAINER_IMAGES[] = {
R.drawable.size_1, R.drawable.size_2, R.drawable.size_3, R.drawable.size_4
};
public static final int STAR_IMAGES[] = {
R.drawable.stars_1, R.drawable.stars_2, R.drawable.stars_3, R.drawable.stars_4,
R.drawable.stars_5, R.drawable.stars_6, R.drawable.stars_7, R.drawable.stars_8,
R.drawable.stars_9, R.drawable.stars_10
};
private final ImageView mCacheTypeImageView;
private final AttributeViewer mContainer;
private final AttributeViewer mDifficulty;
private final TextView mId;
private final NameViewer mName;
private final RadarView mRadarView;
private final AttributeViewer mTerrain;
public GeocacheViewer(RadarView radarView, TextView gcId, NameViewer gcName,
ImageView cacheTypeImageView, AttributeViewer gcDifficulty, AttributeViewer gcTerrain,
UnlabelledAttributeViewer gcContainer) {
mRadarView = radarView;
mId = gcId;
mName = gcName;
mCacheTypeImageView = cacheTypeImageView;
mDifficulty = gcDifficulty;
mTerrain = gcTerrain;
mContainer = gcContainer;
}
public void set(Geocache geocache) {
final double latitude = geocache.getLatitude();
final double longitude = geocache.getLongitude();
mRadarView.setTarget((int)(latitude * GeoUtils.MILLION),
(int)(longitude * GeoUtils.MILLION));
mId.setText(geocache.getId());
mCacheTypeImageView.setImageResource(geocache.getCacheType().iconBig());
mContainer.setImage(geocache.getContainer());
mDifficulty.setImage(geocache.getDifficulty());
mTerrain.setImage(geocache.getTerrain());
mName.set(geocache.getName());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.view;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.main.intents.IntentStarter;
import android.content.ActivityNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
public class CacheButtonOnClickListener implements OnClickListener {
private final IntentStarter mDestinationToIntentFactory;
private final ErrorDisplayer mErrorDisplayer;
private final String mActivityNotFoundErrorMessage;
public CacheButtonOnClickListener(IntentStarter intentStarter, String errorMessage,
ErrorDisplayer errorDisplayer) {
mDestinationToIntentFactory = intentStarter;
mErrorDisplayer = errorDisplayer;
mActivityNotFoundErrorMessage = errorMessage;
}
public void onClick(View view) {
try {
mDestinationToIntentFactory.startIntent();
} catch (final ActivityNotFoundException e) {
mErrorDisplayer.displayError(R.string.error2, e.getMessage(),
mActivityNotFoundErrorMessage);
} catch (final Exception e) {
mErrorDisplayer.displayError(R.string.error1, e.getMessage());
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.database.LocationSaver;
import android.content.Intent;
import android.net.UrlQuerySanitizer;
public class GeocacheFromIntentFactory {
private final GeocacheFactory mGeocacheFactory;
GeocacheFromIntentFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
Geocache viewCacheFromMapsIntent(Intent intent, LocationSaver locationSaver) {
final String query = intent.getData().getQuery();
final CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(),
UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal());
final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery);
final Geocache geocache = mGeocacheFactory.create(latlon[2], latlon[3], Util
.parseCoordinate(latlon[0]), Util.parseCoordinate(latlon[1]), Source.WEB_URL, null,
CacheType.NULL, 0, 0, 0);
locationSaver.saveLocation(geocache);
return geocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1);
final Source source = mGeocacheFactory.sourceFromInt(iSource);
final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0);
final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType);
return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences
.getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0),
preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString(
Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt(
Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0),
preferences.getInt(Geocache.CONTAINER, 0));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import android.os.Bundle;
import android.os.Parcel;
public class GeocacheFromParcelFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromParcelFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(Parcel in) {
return createFromBundle(in.readBundle());
}
public Geocache createFromBundle(Bundle bundle) {
return mGeocacheFactory.create(bundle.getCharSequence(Geocache.ID), bundle
.getCharSequence(Geocache.NAME), bundle.getDouble(Geocache.LATITUDE), bundle
.getDouble(Geocache.LONGITUDE), mGeocacheFactory.sourceFromInt(bundle
.getInt(Geocache.SOURCE_TYPE)), bundle.getString(Geocache.SOURCE_NAME),
mGeocacheFactory.cacheTypeFromInt(bundle.getInt(Geocache.CACHE_TYPE)), bundle
.getInt(Geocache.DIFFICULTY), bundle.getInt(Geocache.TERRAIN), bundle
.getInt(Geocache.CONTAINER));
}
}
| Java |
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
/**
* Library for some use useful latitude/longitude math
*/
public class GeoUtils {
private static int EARTH_RADIUS_KM = 6371;
public static int MILLION = 1000000;
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Distance between the two points in kilometers.
*/
public static double distanceKm(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad)
* Math.cos(lat2Rad) * Math.cos(deltaLonRad))
* EARTH_RADIUS_KM;
}
/**
* Computes the distance in kilometers between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Distance between the two points in kilometers.
*/
//
// public static double distanceKm(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double)MILLION;
// double lon1 = p1.getLongitudeE6() / (double)MILLION;
// double lat2 = p2.getLatitudeE6() / (double)MILLION;
// double lon2 = p2.getLongitudeE6() / (double)MILLION;
//
// return distanceKm(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param p1 First point
* @param p2 Second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
// public static double bearing(GeoPoint p1, GeoPoint p2) {
// double lat1 = p1.getLatitudeE6() / (double) MILLION;
// double lon1 = p1.getLongitudeE6() / (double) MILLION;
// double lat2 = p2.getLatitudeE6() / (double) MILLION;
// double lon2 = p2.getLongitudeE6() / (double) MILLION;
//
// return bearing(lat1, lon1, lat2, lon2);
// }
/**
* Computes the bearing in degrees between two points on Earth.
*
* @param lat1 Latitude of the first point
* @param lon1 Longitude of the first point
* @param lat2 Latitude of the second point
* @param lon2 Longitude of the second point
* @return Bearing between the two points in degrees. A value of 0 means due
* north.
*/
public static double bearing(double lat1, double lon1, double lat2, double lon2) {
double lat1Rad = Math.toRadians(lat1);
double lat2Rad = Math.toRadians(lat2);
double deltaLonRad = Math.toRadians(lon2 - lon1);
double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad);
double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad)
* Math.cos(deltaLonRad);
return radToBearing(Math.atan2(y, x));
}
/**
* Converts an angle in radians to degrees
*/
public static double radToBearing(double rad) {
return (Math.toDegrees(rad) + 360) % 360;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.ActivityType;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender.FieldNoteResources;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.LocationSaver;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import java.io.File;
public class GeoBeagleDelegate {
public static class LogFindClickListener implements OnClickListener {
private final GeoBeagle mGeoBeagle;
private final int mIdDialog;
LogFindClickListener(GeoBeagle geoBeagle, int idDialog) {
mGeoBeagle = geoBeagle;
mIdDialog = idDialog;
}
public void onClick(View v) {
mGeoBeagle.showDialog(mIdDialog);
}
}
static int ACTIVITY_REQUEST_TAKE_PICTURE = 1;
private final ActivitySaver mActivitySaver;
private final AppLifecycleManager mAppLifecycleManager;
private final CompassListener mCompassListener;
private final FieldNoteSender mFieldNoteSender;
private Geocache mGeocache;
private final GeocacheFactory mGeocacheFactory;
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory;
private final GeocacheViewer mGeocacheViewer;
private final IncomingIntentHandler mIncomingIntentHandler;
private final DbFrontend mDbFrontend;
private final MenuActions mMenuActions;
private final GeoBeagle mParent;
private final RadarView mRadarView;
private final Resources mResources;
private final SensorManager mSensorManager;
private final SharedPreferences mSharedPreferences;
private final WebPageAndDetailsButtonEnabler mWebPageButtonEnabler;
public GeoBeagleDelegate(ActivitySaver activitySaver, AppLifecycleManager appLifecycleManager,
CompassListener compassListener, FieldNoteSender fieldNoteSender, GeoBeagle parent,
GeocacheFactory geocacheFactory, GeocacheViewer geocacheViewer,
IncomingIntentHandler incomingIntentHandler, MenuActions menuActions,
GeocacheFromParcelFactory geocacheFromParcelFactory,
DbFrontend dbFrontend, RadarView radarView, Resources resources,
SensorManager sensorManager, SharedPreferences sharedPreferences,
WebPageAndDetailsButtonEnabler webPageButtonEnabler) {
mParent = parent;
mActivitySaver = activitySaver;
mAppLifecycleManager = appLifecycleManager;
mFieldNoteSender = fieldNoteSender;
mMenuActions = menuActions;
mResources = resources;
mSharedPreferences = sharedPreferences;
mRadarView = radarView;
mCompassListener = compassListener;
mSensorManager = sensorManager;
mGeocacheViewer = geocacheViewer;
mWebPageButtonEnabler = webPageButtonEnabler;
mGeocacheFactory = geocacheFactory;
mIncomingIntentHandler = incomingIntentHandler;
mDbFrontend = dbFrontend;
mGeocacheFromParcelFactory = geocacheFromParcelFactory;
}
public Geocache getGeocache() {
return mGeocache;
}
private void onCameraStart() {
String filename = "/sdcard/GeoBeagle/" + mGeocache.getId()
+ DateFormat.format(" yyyy-MM-dd kk.mm.ss.jpg", System.currentTimeMillis());
Log.d("GeoBeagle", "capturing image to " + filename);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(filename)));
mParent.startActivityForResult(intent, GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE);
}
public Dialog onCreateDialog(int idMenu) {
final FieldNoteResources fieldNoteResources = new FieldNoteResources(mResources, idMenu);
return mFieldNoteSender.createDialog(mGeocache.getId(), fieldNoteResources, mParent);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_CAMERA && event.getRepeatCount() == 0) {
onCameraStart();
return true;
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return mMenuActions.act(item.getItemId());
}
public void onPause() {
mAppLifecycleManager.onPause();
mActivitySaver.save(ActivityType.VIEW_CACHE, mGeocache);
mSensorManager.unregisterListener(mRadarView);
mSensorManager.unregisterListener(mCompassListener);
mDbFrontend.closeDatabase();
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
mGeocache = mGeocacheFromParcelFactory.createFromBundle(savedInstanceState);
// Is this really needed???
// mWritableDatabase =
// mGeoBeagleSqliteOpenHelper.getWritableSqliteWrapper();
}
public void onResume() {
mRadarView.handleUnknownLocation();
mRadarView.setUseImperial(mSharedPreferences.getBoolean("imperial", false));
mAppLifecycleManager.onResume();
mSensorManager.registerListener(mRadarView, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mSensorManager.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
mGeocache = mIncomingIntentHandler.maybeGetGeocacheFromIntent(mParent.getIntent(),
mGeocache, new LocationSaver(mDbFrontend));
// Possible fix for issue 53.
if (mGeocache == null) {
mGeocache = mGeocacheFactory.create("", "", 0, 0, Source.MY_LOCATION, "",
CacheType.NULL, 0, 0, 0);
}
mGeocacheViewer.set(mGeocache);
mWebPageButtonEnabler.check();
}
public void onSaveInstanceState(Bundle outState) {
// apparently there are cases where getGeocache returns null, causing
// crashes with 0.7.7/0.7.8.
if (mGeocache != null)
mGeocache.saveToBundle(outState);
}
public void setGeocache(Geocache geocache) {
mGeocache = geocache;
}
public boolean onCreateOptionsMenu(Menu menu) {
return mMenuActions.onCreateOptionsMenu(menu);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
interface GeocacheToUri {
public String convert(Geocache geocache);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Intent;
public class IntentStarterViewUri implements IntentStarter {
private final GeoBeagle mGeoBeagle;
private final GeocacheToUri mGeocacheToUri;
private final IntentFactory mIntentFactory;
public IntentStarterViewUri(GeoBeagle geoBeagle, IntentFactory intentFactory,
GeocacheToUri geocacheToUri) {
mGeoBeagle = geoBeagle;
mGeocacheToUri = geocacheToUri;
mIntentFactory = intentFactory;
}
public void startIntent() {
mGeoBeagle.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, mGeocacheToUri
.convert(mGeoBeagle.getGeocache())));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.Context;
import java.net.URLEncoder;
import java.util.Locale;
public class GeocacheToGoogleMap implements GeocacheToUri {
private final Context mContext;
public GeocacheToGoogleMap(Context context) {
mContext = context;
}
/*
* (non-Javadoc)
* @see
* com.google.code.geobeagle.activity.main.intents.GeocacheToUri#convert
* (com.google.code.geobeagle.Geocache)
*/
public String convert(Geocache geocache) {
// "geo:%1$.5f,%2$.5f?name=cachename"
String idAndName = (String)geocache.getIdAndName();
idAndName = idAndName.replace("(", "[");
idAndName = idAndName.replace(")", "]");
idAndName = URLEncoder.encode(idAndName);
final String format = String.format(Locale.US, mContext
.getString(R.string.map_intent), geocache.getLatitude(), geocache.getLongitude(),
idAndName);
return format;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.activity.main.GeoBeagle;
import android.content.Intent;
public class IntentStarterGeo implements IntentStarter {
private final GeoBeagle mGeoBeagle;
private final Intent mIntent;
public IntentStarterGeo(GeoBeagle geoBeagle, Intent intent) {
mGeoBeagle = geoBeagle;
mIntent = intent;
}
public void startIntent() {
final Geocache geocache = mGeoBeagle.getGeocache();
mIntent.putExtra("latitude", (float)geocache.getLatitude());
mIntent.putExtra("longitude", (float)geocache.getLongitude());
mGeoBeagle.startActivity(mIntent);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import android.content.res.Resources;
/*
* Convert a Geocache to the cache page url.
*/
public class GeocacheToCachePage implements GeocacheToUri {
private final Resources mResources;
public GeocacheToCachePage(Resources resources) {
mResources = resources;
}
// TODO: move strings into Provider enum.
public String convert(Geocache geocache) {
return String.format(mResources.getStringArray(R.array.cache_page_url)[geocache
.getContentProvider().toInt()], geocache.getShortId());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
import com.google.code.geobeagle.activity.main.UriParser;
import android.content.Intent;
public class IntentFactory {
private final UriParser mUriParser;
public IntentFactory(UriParser uriParser) {
mUriParser = uriParser;
}
public Intent createIntent(String action, String uri) {
return new Intent(action, mUriParser.parse(uri));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.intents;
public interface IntentStarter {
public abstract void startIntent();
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.fieldnotes;
import com.google.code.geobeagle.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.text.InputFilter;
import android.text.util.Linkify;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Date;
public class FieldNoteSender {
static class DialogHelper {
Dialog createDialog(Builder mDialogBuilder, View fieldNoteDialogView, OnClickOk onClickOk,
OnClickCancel onClickCancel) {
mDialogBuilder.setTitle(R.string.field_note_title);
mDialogBuilder.setView(fieldNoteDialogView);
mDialogBuilder.setPositiveButton(R.string.send_sms, onClickOk);
mDialogBuilder.setNegativeButton(R.string.cancel, onClickCancel);
return mDialogBuilder.create();
}
EditText createEditor(View fieldNoteDialogView, CharSequence prefix,
FieldNoteResources fieldNoteResources) {
final EditText editText = (EditText)fieldNoteDialogView.findViewById(R.id.fieldnote);
final DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.MEDIUM);
final String timestamp = "(" + dateFormat.format(new Date()) + "/"
+ fieldNoteResources.getString(R.array.geobeagle_sig) + ") ";
final String defaultMessage = fieldNoteResources.getString(R.array.default_msg);
final String msg = timestamp + defaultMessage;
editText.setText(msg);
final InputFilter.LengthFilter lengthFilter = new InputFilter.LengthFilter(
160 - (fieldNoteResources.getString(R.array.fieldnote_code) + prefix).length());
editText.setFilters(new InputFilter[] {
lengthFilter
});
final int len = msg.length();
editText.setSelection(len - defaultMessage.length(), len);
return editText;
}
}
static class OnClickCancel implements OnClickListener {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
static class OnClickOk implements OnClickListener {
private final EditText mEditText;
private final CharSequence mPrefix;
private final FieldNoteResources mFieldNoteResources;
private final Context mContext;
public OnClickOk(FieldNoteResources fieldNoteResources, EditText editText,
CharSequence prefix, Context context) {
mEditText = editText;
mPrefix = prefix;
mFieldNoteResources = fieldNoteResources;
mContext = context;
}
public void onClick(DialogInterface dialog, int whichButton) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("address", "41411");
sendIntent.putExtra("sms_body",
mFieldNoteResources.getString(R.array.fieldnote_code) + mPrefix + mEditText.getText());
sendIntent.setType("vnd.android-dir/mms-sms");
mContext.startActivity(sendIntent);
dialog.dismiss();
}
}
private final Builder mDialogBuilder;
private final DialogHelper mDialogHelper;
private final LayoutInflater mLayoutInflater;
public static class FieldNoteResources {
private final Resources mResources;
private final boolean mDnf;
public FieldNoteResources(Resources resources, int id) {
mResources = resources;
mDnf = (id == R.id.menu_log_dnf);
}
String getString(int id) {
return mResources.getStringArray(id)[mDnf ? 0 : 1];
}
}
FieldNoteSender(LayoutInflater layoutInflater, AlertDialog.Builder builder,
DialogHelper dialogHelper) {
mLayoutInflater = layoutInflater;
mDialogBuilder = builder;
mDialogHelper = dialogHelper;
}
public Dialog createDialog(CharSequence geocacheId, FieldNoteResources fieldNoteResources,
Context context) {
View fieldNoteDialogView = mLayoutInflater.inflate(R.layout.fieldnote, null);
Linkify.addLinks((TextView)fieldNoteDialogView.findViewById(R.id.fieldnote_caveat),
Linkify.WEB_URLS);
CharSequence prefix = geocacheId + " ";
EditText editText = mDialogHelper.createEditor(fieldNoteDialogView, prefix,
fieldNoteResources);
OnClickOk onClickOk = new OnClickOk(fieldNoteResources, editText, prefix, context);
OnClickCancel onClickCancel = new OnClickCancel();
return mDialogHelper.createDialog(mDialogBuilder, fieldNoteDialogView, onClickOk,
onClickCancel);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.ErrorDisplayerDi;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.LocationControlDi;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.R.id;
import com.google.code.geobeagle.actions.MenuAction;
import com.google.code.geobeagle.actions.MenuActionCacheList;
import com.google.code.geobeagle.actions.MenuActionEditGeocache;
import com.google.code.geobeagle.actions.MenuActionSearchOnline;
import com.google.code.geobeagle.actions.MenuActionSettings;
import com.google.code.geobeagle.actions.MenuActions;
import com.google.code.geobeagle.activity.ActivityDI;
import com.google.code.geobeagle.activity.ActivitySaver;
import com.google.code.geobeagle.activity.main.GeoBeagleDelegate.LogFindClickListener;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSender;
import com.google.code.geobeagle.activity.main.fieldnotes.FieldNoteSenderDI;
import com.google.code.geobeagle.activity.main.intents.GeocacheToCachePage;
import com.google.code.geobeagle.activity.main.intents.GeocacheToGoogleMap;
import com.google.code.geobeagle.activity.main.intents.IntentFactory;
import com.google.code.geobeagle.activity.main.intents.IntentStarterGeo;
import com.google.code.geobeagle.activity.main.intents.IntentStarterViewUri;
import com.google.code.geobeagle.activity.main.menuactions.MenuActionGoogleMaps;
import com.google.code.geobeagle.activity.main.view.CacheButtonOnClickListener;
import com.google.code.geobeagle.activity.main.view.CacheDetailsOnClickListener;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer;
import com.google.code.geobeagle.activity.main.view.Misc;
import com.google.code.geobeagle.activity.main.view.OnCacheButtonClickListenerBuilder;
import com.google.code.geobeagle.activity.main.view.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.AttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.LabelledAttributeViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.NameViewer;
import com.google.code.geobeagle.activity.main.view.GeocacheViewer.UnlabelledAttributeViewer;
import com.google.code.geobeagle.activity.map.GeoMapActivity;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.location.LocationLifecycleManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
/*
* Main Activity for GeoBeagle.
*/
public class GeoBeagle extends Activity {
private GeoBeagleDelegate mGeoBeagleDelegate;
private DbFrontend mDbFrontend;
public Geocache getGeocache() {
return mGeoBeagleDelegate.getGeocache();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GeoBeagleDelegate.ACTIVITY_REQUEST_TAKE_PICTURE) {
Log.d("GeoBeagle", "camera intent has returned.");
} else if (resultCode == 0)
setIntent(data);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("GeoBeagle", "GeoBeagle onCreate");
setContentView(R.layout.main);
final ErrorDisplayer errorDisplayer = ErrorDisplayerDi.createErrorDisplayer(this);
final WebPageAndDetailsButtonEnabler webPageButtonEnabler = Misc.create(this,
findViewById(R.id.cache_page), findViewById(R.id.cache_details));
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationControlBuffered locationControlBuffered = LocationControlDi
.create(locationManager);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
final TextView gcid = (TextView)findViewById(R.id.gcid);
final AttributeViewer gcDifficulty = new LabelledAttributeViewer(
GeocacheViewer.STAR_IMAGES, (TextView)findViewById(R.id.gc_text_difficulty),
(ImageView)findViewById(R.id.gc_difficulty));
final AttributeViewer gcTerrain = new LabelledAttributeViewer(GeocacheViewer.STAR_IMAGES,
(TextView)findViewById(R.id.gc_text_terrain),
(ImageView)findViewById(R.id.gc_terrain));
final UnlabelledAttributeViewer gcContainer = new UnlabelledAttributeViewer(
GeocacheViewer.CONTAINER_IMAGES, (ImageView)findViewById(R.id.gccontainer));
final NameViewer gcName = new NameViewer(((TextView)findViewById(R.id.gcname)));
final RadarView radar = (RadarView)findViewById(R.id.radarview);
radar.setUseImperial(false);
radar.setDistanceView((TextView)findViewById(R.id.radar_distance),
(TextView)findViewById(R.id.radar_bearing),
(TextView)findViewById(R.id.radar_accuracy));
final GeocacheViewer geocacheViewer = new GeocacheViewer(radar, gcid, gcName,
(ImageView)findViewById(R.id.gcicon),
gcDifficulty, gcTerrain, gcContainer);
locationControlBuffered.onLocationChanged(null);
final IntentFactory intentFactory = new IntentFactory(new UriParser());
// Register for location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, radar);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, radar);
final AppLifecycleManager appLifecycleManager = new AppLifecycleManager(
getPreferences(MODE_PRIVATE), new LifecycleManager[] {
new LocationLifecycleManager(locationControlBuffered, locationManager),
new LocationLifecycleManager(radar, locationManager)
});
final IntentStarterViewUri intentStarterViewUri = new IntentStarterViewUri(this,
intentFactory, new GeocacheToGoogleMap(this));
final SensorManager sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
final CompassListener compassListener = new CompassListener(new NullRefresher(),
locationControlBuffered, -1440f);
final LayoutInflater layoutInflater = LayoutInflater.from(this);
final FieldNoteSender fieldNoteSender = FieldNoteSenderDI.build(this, layoutInflater);
final ActivitySaver activitySaver = ActivityDI.createActivitySaver(this);
final MenuAction[] menuActionArray = {
new MenuActionCacheList(this), new MenuActionEditGeocache(this),
// new MenuActionLogDnf(this), new MenuActionLogFind(this),
new MenuActionSearchOnline(this), new MenuActionSettings(this),
new MenuActionGoogleMaps(intentStarterViewUri)
};
final MenuActions menuActions = new MenuActions(getResources(), menuActionArray);
final Resources resources = this.getResources();
final SharedPreferences defaultSharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
final GeocacheFromIntentFactory geocacheFromIntentFactory = new GeocacheFromIntentFactory(
geocacheFactory);
final IncomingIntentHandler incomingIntentHandler = new IncomingIntentHandler(
geocacheFactory, geocacheFromIntentFactory);
final GeocacheFromParcelFactory geocacheFromParcelFactory = new GeocacheFromParcelFactory(
geocacheFactory);
mDbFrontend = new DbFrontend(this);
mGeoBeagleDelegate = new GeoBeagleDelegate(activitySaver, appLifecycleManager,
compassListener, fieldNoteSender, this, geocacheFactory, geocacheViewer,
incomingIntentHandler, menuActions, geocacheFromParcelFactory,
mDbFrontend, radar, resources, sensorManager, defaultSharedPreferences,
webPageButtonEnabler);
// see http://www.androidguys.com/2008/11/07/rotational-forces-part-two/
if (getLastNonConfigurationInstance() != null) {
setIntent((Intent)getLastNonConfigurationInstance());
}
final Intent geoMapActivityIntent = new Intent(this, GeoMapActivity.class);
final IntentStarterGeo intentStarterMapActivity = new IntentStarterGeo(this,
geoMapActivityIntent);
final CacheButtonOnClickListener mapsButtonOnClickListener = new CacheButtonOnClickListener(
intentStarterMapActivity, "Map error", errorDisplayer);
findViewById(id.maps).setOnClickListener(mapsButtonOnClickListener);
final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(this);
final CacheDetailsOnClickListener cacheDetailsOnClickListener = Misc
.createCacheDetailsOnClickListener(this, cacheDetailsBuilder, layoutInflater);
findViewById(R.id.cache_details).setOnClickListener(cacheDetailsOnClickListener);
final GeocacheToCachePage geocacheToCachePage = new GeocacheToCachePage(getResources());
final IntentStarterViewUri cachePageIntentStarter = new IntentStarterViewUri(this,
intentFactory, geocacheToCachePage);
final CacheButtonOnClickListener cacheButtonOnClickListener = new CacheButtonOnClickListener(
cachePageIntentStarter, "", errorDisplayer);
findViewById(id.cache_page).setOnClickListener(cacheButtonOnClickListener);
final OnCacheButtonClickListenerBuilder cacheClickListenerSetter = new OnCacheButtonClickListenerBuilder(
this, errorDisplayer);
cacheClickListenerSetter.set(id.radarview, new IntentStarterGeo(this, new Intent(
"com.google.android.radar.SHOW_RADAR")),
"Please install the Radar application to use Radar.");
findViewById(id.menu_log_find).setOnClickListener(
new LogFindClickListener(this, id.menu_log_find));
findViewById(id.menu_log_dnf).setOnClickListener(
new LogFindClickListener(this, id.menu_log_dnf));
}
@Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
return mGeoBeagleDelegate.onCreateDialog(id);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return mGeoBeagleDelegate.onCreateOptionsMenu(menu);
//getMenuInflater().inflate(R.menu.main_menu, menu);
//return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGeoBeagleDelegate.onKeyDown(keyCode, event))
return true;
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mGeoBeagleDelegate.onOptionsItemSelected(item);
}
@Override
public void onPause() {
super.onPause();
Log.d("GeoBeagle", "GeoBeagle onPause");
mGeoBeagleDelegate.onPause();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRestoreInstanceState(android.os.Bundle)
*/
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mGeoBeagleDelegate.onRestoreInstanceState(savedInstanceState);
}
@Override
protected void onResume() {
super.onResume();
Log.d("GeoBeagle", "GeoBeagle onResume");
mGeoBeagleDelegate.onResume();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onRetainNonConfigurationInstance()
*/
@Override
public Object onRetainNonConfigurationInstance() {
return getIntent();
}
/*
* (non-Javadoc)
* @see android.app.Activity#onSaveInstanceState(android.os.Bundle)
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mGeoBeagleDelegate.onSaveInstanceState(outState);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import android.content.SharedPreferences;
public class AppLifecycleManager {
private final LifecycleManager[] mLifecycleManagers;
private final SharedPreferences mPreferences;
public AppLifecycleManager(SharedPreferences preferences, LifecycleManager[] lifecycleManagers) {
mLifecycleManagers = lifecycleManagers;
mPreferences = preferences;
}
public void onPause() {
final SharedPreferences.Editor editor = mPreferences.edit();
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onPause(editor);
}
editor.commit();
}
public void onResume() {
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onResume(mPreferences);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main;
import com.google.code.geobeagle.Refresher;
class NullRefresher implements Refresher {
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.main;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public interface LifecycleManager {
public abstract void onPause(Editor editor);
public abstract void onResume(SharedPreferences preferences);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import android.app.Activity;
public class MenuActionLogFind extends MenuActionBase {
private final Activity mActivity;
public MenuActionLogFind(Activity activity) {
super(R.string.menu_log_find);
mActivity = activity;
}
@Override
public void act() {
mActivity.showDialog(R.id.menu_log_find);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import android.app.Activity;
public class MenuActionLogDnf extends MenuActionBase {
private final Activity mActivity;
public MenuActionLogDnf(Activity activity) {
super(R.string.menu_log_dnf);
mActivity = activity;
}
@Override
public void act() {
mActivity.showDialog(R.id.menu_log_dnf);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.main.menuactions;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.actions.MenuActionBase;
import com.google.code.geobeagle.activity.main.intents.IntentStarterViewUri;
public class MenuActionGoogleMaps extends MenuActionBase {
private final IntentStarterViewUri mIntentStarterViewUri;
public MenuActionGoogleMaps(IntentStarterViewUri intentStarterViewUri) {
super(R.string.menu_google_maps);
mIntentStarterViewUri = intentStarterViewUri;
}
@Override
public void act() {
mIntentStarterViewUri.startIntent();
}
}
| Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
public class AbsoluteBearingFormatter implements BearingFormatter {
private static final String[] LETTERS = {
"N", "NE", "E", "SE", "S", "SW", "W", "NW"
};
public String formatBearing(float absBearing, float myHeading) {
return LETTERS[((((int)(absBearing) + 22 + 720) % 360) / 45)];
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.Refresher;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI;
import android.util.Log;
public class CacheListRefresh implements Refresher {
public static class ActionManager {
private final ActionAndTolerance mActionAndTolerances[];
public ActionManager(ActionAndTolerance actionAndTolerances[]) {
mActionAndTolerances = actionAndTolerances;
}
public int getMinActionExceedingTolerance(IGpsLocation here, float azimuth, long now) {
int i;
for (i = 0; i < mActionAndTolerances.length; i++) {
if (mActionAndTolerances[i].exceedsTolerance(here, azimuth, now))
break;
}
return i;
}
public void performActions(IGpsLocation here, float azimuth, int startingAction, long now) {
for (int i = startingAction; i < mActionAndTolerances.length; i++) {
mActionAndTolerances[i].refresh();
mActionAndTolerances[i].updateLastRefreshed(here, azimuth, now);
}
}
}
public static class UpdateFlag {
private boolean mUpdateFlag = true;
public void setUpdatesEnabled(boolean enabled) {
Log.d("GeoBeagle", "Update enabled: " + enabled);
mUpdateFlag = enabled;
}
boolean updatesEnabled() {
return mUpdateFlag;
}
}
private final ActionManager mActionManager;
private final LocationControlBuffered mLocationControlBuffered;
private final CacheListDelegateDI.Timing mTiming;
private final UpdateFlag mUpdateFlag;
public CacheListRefresh(ActionManager actionManager, CacheListDelegateDI.Timing timing,
LocationControlBuffered locationControlBuffered, UpdateFlag updateFlag) {
mLocationControlBuffered = locationControlBuffered;
mTiming = timing;
mActionManager = actionManager;
mUpdateFlag = updateFlag;
}
public void forceRefresh() {
mTiming.start();
final long now = mTiming.getTime();
mActionManager.performActions(mLocationControlBuffered.getGpsLocation(),
mLocationControlBuffered.getAzimuth(), 0, now);
}
public void refresh() {
// TODO: Is this check still necessary?
/*
* if (!mSqliteWrapper.isOpen()) { Log.d("GeoBeagle",
* "Refresh: database is closed, punting."); return; }
*/
if (!mUpdateFlag.updatesEnabled())
return;
Log.d("GeoBeagle", "CacheListRefresh.refresh");
mTiming.start();
final long now = mTiming.getTime();
final IGpsLocation here = mLocationControlBuffered.getGpsLocation();
final float azimuth = mLocationControlBuffered.getAzimuth();
final int minActionExceedingTolerance = mActionManager.getMinActionExceedingTolerance(here,
azimuth, now);
mActionManager.performActions(here, azimuth, minActionExceedingTolerance, now);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class GeocacheListAdapter extends BaseAdapter {
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final GeocacheVectors mGeocacheVectors;
public GeocacheListAdapter(GeocacheVectors geocacheVectors,
GeocacheSummaryRowInflater geocacheSummaryRowInflater) {
mGeocacheVectors = geocacheVectors;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
}
public int getCount() {
return mGeocacheVectors.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = mGeocacheSummaryRowInflater.inflate(convertView);
mGeocacheSummaryRowInflater.setData(view, position);
return view;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.CompassListener;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.cachelist.CacheListView;
import com.google.code.geobeagle.activity.cachelist.CompassListenerFactory;
import com.google.code.geobeagle.activity.cachelist.CacheListView.ScrollListener;
import com.google.code.geobeagle.activity.cachelist.GeocacheListController.CacheListOnCreateContextMenuListener;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVectors;
import com.google.code.geobeagle.activity.cachelist.view.GeocacheSummaryRowInflater;
import com.google.code.geobeagle.gpsstatuswidget.UpdateGpsWidgetRunnable;
import com.google.code.geobeagle.location.CombinedLocationManager;
import android.app.ListActivity;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ListView;
public class GeocacheListPresenter {
public static class CacheListRefreshLocationListener implements LocationListener {
private final CacheListRefresh mCacheListRefresh;
public CacheListRefreshLocationListener(CacheListRefresh cacheListRefresh) {
mCacheListRefresh = cacheListRefresh;
}
public void onLocationChanged(Location location) {
// Log.d("GeoBeagle", "location changed");
mCacheListRefresh.refresh();
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
static final int UPDATE_DELAY = 1000;
private final LocationListener mCombinedLocationListener;
private final CombinedLocationManager mCombinedLocationManager;
// private final SensorEventListener mCompassListener;
// private final SensorListener mCompassListener;
private final CompassListenerFactory mCompassListenerFactory;
private final DistanceFormatterManager mDistanceFormatterManager;
private final GeocacheListAdapter mGeocacheListAdapter;
private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater;
private final GeocacheVectors mGeocacheVectors;
private final View mGpsStatusWidget;
private final ListActivity mListActivity;
private final LocationControlBuffered mLocationControlBuffered;
private final SensorManagerWrapper mSensorManagerWrapper;
private final UpdateGpsWidgetRunnable mUpdateGpsWidgetRunnable;
private final CacheListView.ScrollListener mScrollListener;
public GeocacheListPresenter(LocationListener combinedLocationListener,
CombinedLocationManager combinedLocationManager,
CompassListenerFactory compassListenerFactory,
DistanceFormatterManager distanceFormatterManager,
GeocacheListAdapter geocacheListAdapter,
GeocacheSummaryRowInflater geocacheSummaryRowInflater, GeocacheVectors geocacheVectors,
View gpsStatusWidget, ListActivity listActivity,
LocationControlBuffered locationControlBuffered,
SensorManagerWrapper sensorManagerWrapper,
UpdateGpsWidgetRunnable updateGpsWidgetRunnable, ScrollListener scrollListener) {
mCombinedLocationListener = combinedLocationListener;
mCombinedLocationManager = combinedLocationManager;
mCompassListenerFactory = compassListenerFactory;
mDistanceFormatterManager = distanceFormatterManager;
mGeocacheListAdapter = geocacheListAdapter;
mGeocacheSummaryRowInflater = geocacheSummaryRowInflater;
mGeocacheVectors = geocacheVectors;
mGpsStatusWidget = gpsStatusWidget;
mListActivity = listActivity;
mLocationControlBuffered = locationControlBuffered;
mUpdateGpsWidgetRunnable = updateGpsWidgetRunnable;
mSensorManagerWrapper = sensorManagerWrapper;
mScrollListener = scrollListener;
}
public void onCreate() {
mListActivity.setContentView(R.layout.cache_list);
final ListView listView = mListActivity.getListView();
listView.addHeaderView(mGpsStatusWidget);
mListActivity.setListAdapter(mGeocacheListAdapter);
listView.setOnCreateContextMenuListener(new CacheListOnCreateContextMenuListener(
mGeocacheVectors));
listView.setOnScrollListener(mScrollListener);
mUpdateGpsWidgetRunnable.run();
// final List<Sensor> sensorList =
// mSensorManager.getSensorList(Sensor.TYPE_ORIENTATION);
// mCompassSensor = sensorList.get(0);
}
public void onPause() {
mCombinedLocationManager.removeUpdates();
mSensorManagerWrapper.unregisterListener();
}
public void onResume(CacheListRefresh cacheListRefresh) {
final CacheListRefreshLocationListener cacheListRefreshLocationListener = new CacheListRefreshLocationListener(
cacheListRefresh);
final CompassListener mCompassListener = mCompassListenerFactory.create(cacheListRefresh);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, mLocationControlBuffered);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0, mCombinedLocationListener);
mCombinedLocationManager.requestLocationUpdates(UPDATE_DELAY, 0,
cacheListRefreshLocationListener);
mDistanceFormatterManager.setFormatter();
// mSensorManager.registerListener(mCompassListener, mCompassSensor,
// SensorManager.SENSOR_DELAY_UI);
mSensorManagerWrapper.registerListener(mCompassListener, SensorManager.SENSOR_ORIENTATION,
SensorManager.SENSOR_DELAY_UI);
final boolean absoluteBearing = PreferenceManager
.getDefaultSharedPreferences(mListActivity).getBoolean("absolute-bearing", false);
mGeocacheSummaryRowInflater.setBearingFormatter(absoluteBearing);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.CacheListDelegateDI;
import com.google.code.geobeagle.database.FilterNearestCaches;
import android.app.ListActivity;
import android.widget.TextView;
public class TitleUpdater {
private final FilterNearestCaches mFilterNearestCaches;
private final ListActivity mListActivity;
private final ListTitleFormatter mListTitleFormatter;
private final CacheListDelegateDI.Timing mTiming;
public TitleUpdater(ListActivity listActivity, FilterNearestCaches filterNearestCaches,
ListTitleFormatter listTitleFormatter, CacheListDelegateDI.Timing timing) {
mListActivity = listActivity;
mFilterNearestCaches = filterNearestCaches;
mListTitleFormatter = listTitleFormatter;
mTiming = timing;
}
public void update(int sqlCount, int nearestCachesCount) {
mListActivity.setTitle(mListActivity.getString(mFilterNearestCaches.getTitleText(),
nearestCachesCount, sqlCount));
if (0 == nearestCachesCount) {
TextView textView = (TextView)mListActivity.findViewById(android.R.id.empty);
textView.setText(mListTitleFormatter.getBodyText(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.Geocache;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.activity.cachelist.CacheListDelegateDI.Timing;
import com.google.code.geobeagle.activity.cachelist.model.CacheListData;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.FilterNearestCaches;
import android.location.Location;
import java.util.ArrayList;
public class SqlCacheLoader implements RefreshAction {
private final CacheListData mCacheListData;
private final FilterNearestCaches mFilterNearestCaches;
private final DbFrontend mDbFrontend;
private final LocationControlBuffered mLocationControlBuffered;
private final Timing mTiming;
private final TitleUpdater mTitleUpdater;
public SqlCacheLoader(DbFrontend dbFrontend, FilterNearestCaches filterNearestCaches,
CacheListData cacheListData, LocationControlBuffered locationControlBuffered,
TitleUpdater titleUpdater, Timing timing) {
mDbFrontend = dbFrontend;
mFilterNearestCaches = filterNearestCaches;
mCacheListData = cacheListData;
mLocationControlBuffered = locationControlBuffered;
mTiming = timing;
mTitleUpdater = titleUpdater;
}
public void refresh() {
final Location location = mLocationControlBuffered.getLocation();
double latitude = 0;
double longitude = 0;
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
// Log.d("GeoBeagle", "Location: " + location);
ArrayList<Geocache> geocaches =
mDbFrontend.loadCaches(latitude, longitude, mFilterNearestCaches.getWhereFactory());
mTiming.lap("SQL time");
mCacheListData.add(geocaches, mLocationControlBuffered);
mTiming.lap("add to list time");
final int sqlCount = geocaches.size();
final int nearestCachesCount = mCacheListData.size();
mTitleUpdater.update(sqlCount, 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 java.util.ArrayList;
import java.util.Collections;
public class DistanceSortStrategy implements SortStrategy {
private final LocationComparator mLocationComparator;
public DistanceSortStrategy(LocationComparator locationComparator) {
mLocationComparator = locationComparator;
}
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.formatting.DistanceFormatter;
public interface HasDistanceFormatter {
public abstract void setDistanceFormatter(DistanceFormatter distanceFormatter);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
public class RelativeBearingFormatter implements BearingFormatter {
private static final String[] ARROWS = {
"^", ">", "v", "<",
};
public String formatBearing(float absBearing, float myHeading) {
return ARROWS[((((int)(absBearing - myHeading) + 45 + 720) % 360) / 90)];
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import android.content.SharedPreferences;
import java.util.ArrayList;
public class DistanceFormatterManager {
private ArrayList<HasDistanceFormatter> mHasDistanceFormatters;
private final DistanceFormatterMetric mDistanceFormatterMetric;
private final DistanceFormatterImperial mDistanceFormatterImperial;
private final SharedPreferences mDefaultSharedPreferences;
DistanceFormatterManager(SharedPreferences defaultSharedPreferences,
DistanceFormatterImperial distanceFormatterImperial,
DistanceFormatterMetric distanceFormatterMetric) {
mDistanceFormatterImperial = distanceFormatterImperial;
mDistanceFormatterMetric = distanceFormatterMetric;
mDefaultSharedPreferences = defaultSharedPreferences;
mHasDistanceFormatters = new ArrayList<HasDistanceFormatter>(2);
}
public void addHasDistanceFormatter(HasDistanceFormatter hasDistanceFormatter) {
mHasDistanceFormatters.add(hasDistanceFormatter);
}
public DistanceFormatter getFormatter() {
final boolean imperial = mDefaultSharedPreferences.getBoolean("imperial", false);
return imperial ? mDistanceFormatterImperial : mDistanceFormatterMetric;
}
public void setFormatter() {
final DistanceFormatter formatter = getFormatter();
for (HasDistanceFormatter hasDistanceFormatter : mHasDistanceFormatters) {
hasDistanceFormatter.setDistanceFormatter(formatter);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.LocationControlBuffered.IGpsLocation;
public interface ToleranceStrategy {
public boolean exceedsTolerance(IGpsLocation here, float azimuth, long now);
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now);
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.CompassListener;
import android.hardware.SensorManager;
public class SensorManagerWrapper {
private CompassListener mCompassListener;
private final SensorManager mSensorManager;
public SensorManagerWrapper(SensorManager sensorManager) {
mSensorManager = sensorManager;
}
public void unregisterListener() {
mSensorManager.unregisterListener(mCompassListener);
}
public void registerListener(CompassListener compassListener, int sensorOrientation,
int sensorDelayUi) {
mCompassListener = compassListener;
mSensorManager.registerListener(compassListener, sensorOrientation, sensorDelayUi);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.LocationControlBuffered.IGpsLocation;
public class LocationAndAzimuthTolerance implements ToleranceStrategy {
private float mLastAzimuth;
LocationTolerance mLocationTolerance;
public LocationAndAzimuthTolerance(LocationTolerance locationTolerance, float lastAzimuth) {
mLocationTolerance = locationTolerance;
mLastAzimuth = lastAzimuth;
}
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);
}
public void updateLastRefreshed(IGpsLocation here, float azimuth, long now) {
mLocationTolerance.updateLastRefreshed(here, azimuth, now);
mLastAzimuth = azimuth;
}
} | Java |
package com.google.code.geobeagle.activity.cachelist.presenter;
public interface BearingFormatter {
public abstract String formatBearing(float absBearing, float myHeading);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.presenter;
import com.google.code.geobeagle.activity.cachelist.model.GeocacheVector;
import java.util.ArrayList;
public class NullSortStrategy implements SortStrategy {
public void sort(ArrayList<GeocacheVector> arrayList) {
return;
}
} | Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.