code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.google.code.geobeagle; import android.os.Handler; import java.util.ArrayList; //Doesn't have support for faking azimuth at the moment /** Change LocationControlDi.create() to return an instance of this class * to use fake locations everywhere but in the Map view. */ public class GeoFixProviderFake implements GeoFixProvider { public static class FakeDataset { /** How often to report a new position */ public final int mReportPeriodMillisec; /** The fake positions will be interpreted to be * given relative to this location */ private final double mLatStart; private final double mLonStart; /** The period of the fix list loop, in millisec */ private final long mLoopTime; /** A number of GeoFixes with values relative some starting point. * The first fix must have relative time 0 */ private GeoFix[] mFixes; public FakeDataset(int reportPeriodMillisec, double latStart, double lonStart, long loopTime, GeoFix[] fixes) { mReportPeriodMillisec = reportPeriodMillisec; mLatStart = latStart; mLonStart = lonStart; mLoopTime = loopTime; mFixes = fixes; } /** @param time in millisec */ public GeoFix getGeoFixAtTime(long time) { long relTime = time % mLoopTime; //Initialize to avoid compiler warning GeoFix lastFix = mFixes[0]; GeoFix nextFix = mFixes[0]; float ratio = 0; //Between 0 and 1 if (relTime > mFixes[mFixes.length - 1].getTime()) { lastFix = mFixes[mFixes.length - 1]; nextFix = mFixes[0]; ratio = ((relTime-lastFix.getTime()) / (mLoopTime-lastFix.getTime())); } else { for (int i = 1; i < mFixes.length; i++) { if (mFixes[i].getTime() == relTime) { lastFix = mFixes[i]; nextFix = mFixes[i]; ratio = 0; break; } else if (mFixes[i].getTime() > relTime) { lastFix = mFixes[i-1]; nextFix = mFixes[i]; //Must convert to float to avoid integer division: ratio = (((float)relTime-lastFix.getTime()) / (nextFix.getTime()-lastFix.getTime())); break; } } } //float accuracy, double altitude, //double latitude, double longitude, long time, String provider return new GeoFix(lastFix.getAccuracy(), lastFix.getAltitude() + (nextFix.getAltitude()-lastFix.getAltitude())*ratio, mLatStart + lastFix.getLatitude() + (nextFix.getLatitude()-lastFix.getLatitude())*ratio, mLonStart + lastFix.getLongitude() + (nextFix.getLongitude()-lastFix.getLongitude())*ratio, time, (String)lastFix.getProvider()); } } /** Move slowly between three locations */ public static FakeDataset YOKOHAMA = new FakeDataset(2000, 35.4583162355423, 139.62289574623108, 10000, new GeoFix[] { new GeoFix(192, 40, 0, 0, 0, "gps"), new GeoFix(128, 40, 0.001, -0.0001, 5000, "gps"), new GeoFix(8, 40, 0.002, -0.0001, 7000, "gps"), }); /** A single location */ public static FakeDataset TOKYO = new FakeDataset(10000, 35.690448, 139.756225, 10000, new GeoFix[] { new GeoFix(16, 10, 0, 0, 0, "gps"), }); /** Another single location */ public static FakeDataset LINKOPING = new FakeDataset(10000, 58.398050, 15.612208, 10000, new GeoFix[] { new GeoFix(8, 20, 0, 0, 0, "gps"), }); /** Simulate moving at highway speeds and report location every second */ public static FakeDataset CAR_JOURNEY = new FakeDataset(1000, 58.398050, 15.612208, 70*60*1000, new GeoFix[] { new GeoFix(8, 20, 0, 0, 0, "gps"), new GeoFix(16, 30, 58.432729-58.398050, 15.669937-15.612208, 5*60*1000, "gps"), new GeoFix(32, 40, 58.591698-58.398050, 16.12896-15.612208, 35*60*1000, "gps"), new GeoFix(24, 30, 58.432729-58.398050, 15.669937-15.612208,65*60*1000, "gps"), }); private final FakeDataset mFakeDataset; private GeoFix mCurrentGeoFix; private boolean mUpdatesEnabled = false; private final Handler mHandler; private ArrayList<Refresher> mObservers = new ArrayList<Refresher>(); private class FixTimer extends Thread { @Override public void run() { while (mUpdatesEnabled) { try { if (mUpdatesEnabled) { mCurrentGeoFix = mFakeDataset.getGeoFixAtTime(System.currentTimeMillis()); mHandler.post(mObserverNotifier); } Thread.sleep(mFakeDataset.mReportPeriodMillisec); } catch (InterruptedException e) { return; } } } } private FixTimer mFixTimer; public GeoFixProviderFake(FakeDataset fakeDataset) { //Create here to assure that main thread gets to execute notifications: mHandler = new Handler(); mFakeDataset = fakeDataset; } public void addObserver(Refresher refresher) { if (!mObservers.contains(refresher)) mObservers.add(refresher); } private void notifyObservers() { for (Refresher refresher : mObservers) { refresher.refresh(); } } private final Runnable mObserverNotifier = new Runnable() { @Override public void run() { notifyObservers(); } }; @Override public float getAzimuth() { //Reports a new azimuth once a second int degreesPerSecond = 10; long time = System.currentTimeMillis(); return (time/1000 * degreesPerSecond) % 360; } @Override public GeoFix getLocation() { return mCurrentGeoFix; } @Override public boolean isProviderEnabled() { return true; } @Override public void onPause() { mUpdatesEnabled = false; } @Override public void onResume() { mUpdatesEnabled = true; mFixTimer = new FixTimer(); mFixTimer.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.xmlimport.CachePersisterFacade.TextHandler; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; import java.util.HashMap; public class EventHandlerGpx implements EventHandler { public static final String XPATH_CACHE_CONTAINER = "/gpx/wpt/groundspeak:cache/groundspeak:container"; public static final String XPATH_CACHE_DIFFICULTY = "/gpx/wpt/groundspeak:cache/groundspeak:difficulty"; public static final String XPATH_CACHE_TERRAIN = "/gpx/wpt/groundspeak:cache/groundspeak:terrain"; public static final String XPATH_CACHE_TYPE = "/gpx/wpt/groundspeak:cache/groundspeak:type"; public static final String XPATH_GEOCACHE_CONTAINER = "/gpx/wpt/geocache/container"; public static final String XPATH_GEOCACHE_DIFFICULTY = "/gpx/wpt/geocache/difficulty"; public static final String XPATH_GEOCACHE_TERRAIN = "/gpx/wpt/geocache/terrain"; public static final String XPATH_GEOCACHE_TYPE = "/gpx/wpt/geocache/type"; public static final String XPATH_GEOCACHEHINT = "/gpx/wpt/geocache/hints"; public static final String XPATH_GEOCACHELOGDATE = "/gpx/wpt/geocache/logs/log/time"; public static final String XPATH_GEOCACHENAME = "/gpx/wpt/geocache/name"; static final String XPATH_GPXNAME = "/gpx/name"; static final String XPATH_GPXTIME = "/gpx/time"; public static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name"; public static final String XPATH_PLACEDBY = "/gpx/wpt/groundspeak:cache/groundspeak:placed_by"; public static final String XPATH_HINT = "/gpx/wpt/groundspeak:cache/groundspeak:encoded_hints"; public static final String XPATH_LOGDATE = "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:date"; static final String[] XPATH_PLAINLINES = { "/gpx/wpt/cmt", "/gpx/wpt/desc", "/gpx/wpt/groundspeak:cache/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:container", "/gpx/wpt/groundspeak:cache/groundspeak:short_description", "/gpx/wpt/groundspeak:cache/groundspeak:long_description", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:type", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:finder", "/gpx/wpt/groundspeak:cache/groundspeak:logs/groundspeak:log/groundspeak:text", /* here are the geocaching.com.au entries */ "/gpx/wpt/geocache/owner", "/gpx/wpt/geocache/type", "/gpx/wpt/geocache/summary", "/gpx/wpt/geocache/description", "/gpx/wpt/geocache/logs/log/geocacher", "/gpx/wpt/geocache/logs/log/type", "/gpx/wpt/geocache/logs/log/text" }; static final String XPATH_SYM = "/gpx/wpt/sym"; static final String XPATH_CACHE = "/gpx/wpt/groundspeak:cache"; static final String XPATH_WPT = "/gpx/wpt"; public static final String XPATH_WPTDESC = "/gpx/wpt/desc"; public static final String XPATH_WPTNAME = "/gpx/wpt/name"; public static final String XPATH_WAYPOINT_TYPE = "/gpx/wpt/type"; private final CachePersisterFacade mCachePersisterFacade; private final HashMap<String, TextHandler> mTextHandlers; public EventHandlerGpx(CachePersisterFacade cachePersisterFacade, HashMap<String, TextHandler> textHandlers) { mCachePersisterFacade = cachePersisterFacade; mTextHandlers = textHandlers; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endCache(Source.GPX); } } public void startTag(String fullPath, XmlPullParserWrapper xmlPullParser) { if (fullPath.equals(XPATH_WPT)) { mCachePersisterFacade.startCache(); mCachePersisterFacade.wpt(xmlPullParser.getAttributeValue(null, "lat"), xmlPullParser .getAttributeValue(null, "lon")); } else if (fullPath.equals(XPATH_CACHE)) { boolean available = xmlPullParser.getAttributeValue(null, "available").equalsIgnoreCase("true"); boolean archived = xmlPullParser.getAttributeValue(null, "archived").equalsIgnoreCase("true"); mCachePersisterFacade.setTag(Tags.UNAVAILABLE, !available); mCachePersisterFacade.setTag(Tags.ARCHIVED, archived); } } public boolean text(String fullPath, String text) throws IOException { text = text.trim(); if (mTextHandlers.containsKey(fullPath)) mTextHandlers.get(fullPath).text(text); //Log.d("GeoBeagle", "fullPath " + fullPath + ", text " + text); if (fullPath.equals(XPATH_GPXTIME)) { return mCachePersisterFacade.gpxTime(text); } else if (fullPath.equals(XPATH_SYM)) { if (text.equals("Geocache Found")) mCachePersisterFacade.setTag(Tags.FOUND, true); } for (String writeLineMatch : XPATH_PLAINLINES) { if (fullPath.equals(writeLineMatch)) { mCachePersisterFacade.line(text); return true; } } return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; public class GpxFileOpener { public class GpxFileIter implements IGpxReaderIter { public boolean hasNext() { if (mAborter.isAborted()) return false; return mFilename != null; } public IGpxReader next() { final IGpxReader gpxReader = new GpxReader(mFilename); mFilename = null; return gpxReader; } } private Aborter mAborter; private String mFilename; public GpxFileOpener(String filename, Aborter aborter) { mFilename = filename; mAborter = aborter; } public GpxFileIter iterator() { return new GpxFileIter(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.gpx; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String mFilename; public GpxReader(String filename) { mFilename = filename; } public String getFilename() { return mFilename; } public Reader open() throws FileNotFoundException { return new BufferedReader(new FileReader(mFilename)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.IOException; public interface IGpxReaderIter { public boolean hasNext() throws IOException; public IGpxReader next() throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.gpx.GpxFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener; import com.google.code.geobeagle.xmlimport.gpx.zip.ZipFileOpener.ZipInputFileTester; import java.io.IOException; /** * @author sng Takes a filename and returns an IGpxReaderIter based on the * extension: zip: ZipFileIter gpx/loc: GpxFileIter */ public class GpxFileIterAndZipFileIterFactory { private final Aborter mAborter; private final ZipInputFileTester mZipInputFileTester; public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester, Aborter aborter) { mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public IGpxReaderIter fromFile(String filename) throws IOException { if (filename.endsWith(".zip")) { return new ZipFileOpener(GpxAndZipFiles.GPX_DIR + filename, new ZipInputStreamFactory(), mZipInputFileTester, mAborter).iterator(); } return new GpxFileOpener(GpxAndZipFiles.GPX_DIR + filename, mAborter).iterator(); } public void resetAborter() { mAborter.reset(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.File; import java.io.FilenameFilter; import java.io.IOException; public class GpxAndZipFiles { public static class GpxAndZipFilenameFilter implements FilenameFilter { private final GpxFilenameFilter mGpxFilenameFilter; public GpxAndZipFilenameFilter(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean accept(File dir, String name) { name = name.toLowerCase(); if (!name.startsWith(".") && name.endsWith(".zip")) return true; return mGpxFilenameFilter.accept(name); } } public static class GpxFilenameFilter { public boolean accept(String name) { name = name.toLowerCase(); return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".loc")); } } public static class GpxFilesAndZipFilesIter { private final String[] mFileList; private final GpxFileIterAndZipFileIterFactory mGpxAndZipFileIterFactory; private int mIxFileList; private IGpxReaderIter mSubIter; GpxFilesAndZipFilesIter(String[] fileList, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFileList = fileList; mGpxAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; mIxFileList = 0; } public boolean hasNext() throws IOException { // Iterate through actual zip and gpx files on the filesystem. if (mSubIter != null && mSubIter.hasNext()) return true; while (mIxFileList < mFileList.length) { mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]); if (mSubIter.hasNext()) return true; } return false; } public IGpxReader next() throws IOException { return mSubIter.next(); } } public static final String GPX_DIR = "/sdcard/download/"; private final FilenameFilter mFilenameFilter; private final GpxFileIterAndZipFileIterFactory mGpxFileIterAndZipFileIterFactory; public GpxAndZipFiles(FilenameFilter filenameFilter, GpxFileIterAndZipFileIterFactory gpxFileIterAndZipFileIterFactory) { mFilenameFilter = filenameFilter; mGpxFileIterAndZipFileIterFactory = gpxFileIterAndZipFileIterFactory; } public GpxFilesAndZipFilesIter iterator() { String[] fileList = new File(GPX_DIR).list(mFilenameFilter); if (fileList == null) return null; mGpxFileIterAndZipFileIterFactory.resetAborter(); return new GpxFilesAndZipFilesIter(fileList, mGpxFileIterAndZipFileIterFactory); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx; import java.io.FileNotFoundException; import java.io.Reader; public interface IGpxReader { String getFilename(); Reader open() throws FileNotFoundException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import java.io.IOException; import java.io.InputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class GpxZipInputStream { private ZipEntry mNextEntry; private final ZipInputStream mZipInputStream; public GpxZipInputStream(ZipInputStream zipInputStream) { mZipInputStream = zipInputStream; } ZipEntry getNextEntry() throws IOException { mNextEntry = mZipInputStream.getNextEntry(); return mNextEntry; } InputStream getStream() { return mZipInputStream; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import java.io.Reader; class GpxReader implements IGpxReader { private final String mFilename; private final Reader mReader; GpxReader(String filename, Reader reader) { mFilename = filename; mReader = reader; } public String getFilename() { return mFilename; } public Reader open() { return mReader; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport.gpx.zip; import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory; import com.google.code.geobeagle.xmlimport.GpxToCache.Aborter; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.IGpxReaderIter; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilenameFilter; import java.io.IOException; import java.io.InputStreamReader; import java.util.zip.ZipEntry; public class ZipFileOpener { public static class ZipFileIter implements IGpxReaderIter { private final Aborter mAborter; private ZipEntry mNextZipEntry; private final ZipInputFileTester mZipInputFileTester; private final GpxZipInputStream mZipInputStream; ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter, ZipInputFileTester zipInputFileTester, ZipEntry nextZipEntry) { mZipInputStream = zipInputStream; mNextZipEntry = nextZipEntry; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } ZipFileIter(GpxZipInputStream zipInputStream, Aborter aborter, ZipInputFileTester zipInputFileTester) { mZipInputStream = zipInputStream; mNextZipEntry = null; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public boolean hasNext() throws IOException { // Iterate through zip file entries. if (mNextZipEntry == null) { do { if (mAborter.isAborted()) break; mNextZipEntry = mZipInputStream.getNextEntry(); } while (mNextZipEntry != null && !mZipInputFileTester.isValid(mNextZipEntry)); } return mNextZipEntry != null; } public IGpxReader next() throws IOException { final String name = mNextZipEntry.getName(); mNextZipEntry = null; return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream())); } } public static class ZipInputFileTester { private final GpxFilenameFilter mGpxFilenameFilter; public ZipInputFileTester(GpxFilenameFilter gpxFilenameFilter) { mGpxFilenameFilter = gpxFilenameFilter; } public boolean isValid(ZipEntry zipEntry) { return (!zipEntry.isDirectory() && mGpxFilenameFilter.accept(zipEntry.getName())); } } private final Aborter mAborter; private final String mFilename; private final ZipInputFileTester mZipInputFileTester; private final ZipInputStreamFactory mZipInputStreamFactory; public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory, ZipInputFileTester zipInputFileTester, Aborter aborter) { mFilename = filename; mZipInputStreamFactory = zipInputStreamFactory; mAborter = aborter; mZipInputFileTester = zipInputFileTester; } public ZipFileIter iterator() throws IOException { return new ZipFileIter(mZipInputStreamFactory.create(mFilename), mAborter, mZipInputFileTester); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.GpxToCache.CancelException; import org.xmlpull.v1.XmlPullParserException; import android.database.sqlite.SQLiteException; import android.os.PowerManager.WakeLock; import java.io.FileNotFoundException; import java.io.IOException; import java.io.Reader; public class GpxLoader { private final CachePersisterFacade mCachePersisterFacade; private final ErrorDisplayer mErrorDisplayer; private final GpxToCache mGpxToCache; private final WakeLock mWakeLock; public static final int WAKELOCK_DURATION = 15000; GpxLoader(CachePersisterFacade cachePersisterFacade, ErrorDisplayer errorDisplayer, GpxToCache gpxToCache, WakeLock wakeLock) { mGpxToCache = gpxToCache; mCachePersisterFacade = cachePersisterFacade; mErrorDisplayer = errorDisplayer; mWakeLock = wakeLock; } public void abort() { mGpxToCache.abort(); } public void end() { mCachePersisterFacade.end(); } /** * @return true if we should continue loading more files, false if we should * terminate. */ public boolean load(EventHelper eventHelper) { boolean markLoadAsComplete = false; boolean continueLoading = false; try { mWakeLock.acquire(WAKELOCK_DURATION); boolean alreadyLoaded = mGpxToCache.load(eventHelper); markLoadAsComplete = !alreadyLoaded; continueLoading = true; } catch (final SQLiteException e) { mErrorDisplayer.displayError(R.string.error_writing_cache, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (XmlPullParserException e) { mErrorDisplayer.displayError(R.string.error_parsing_file, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (FileNotFoundException e) { mErrorDisplayer.displayError(R.string.file_not_found, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (IOException e) { mErrorDisplayer.displayError(R.string.error_reading_file, mGpxToCache.getSource() + ": " + e.getMessage()); } catch (CancelException e) { } mCachePersisterFacade.close(markLoadAsComplete); return continueLoading; } public void open(String path, Reader reader) throws XmlPullParserException { mGpxToCache.open(path, reader); mCachePersisterFacade.open(path); } public void start() { mCachePersisterFacade.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.actions.Abortable; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.xmlimport.GpxImporterDI.ImportThreadWrapper; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.GpxImporterDI.ToastFactory; import android.app.ListActivity; import android.widget.Toast; public class GpxImporter implements Abortable { private final ErrorDisplayer mErrorDisplayer; private final EventHandlers mEventHandlers; private final GpxLoader mGpxLoader; private final ImportThreadWrapper mImportThreadWrapper; private final ListActivity mListActivity; private final MessageHandler mMessageHandler; private final ToastFactory mToastFactory; private final GeocacheFactory mGeocacheFactory; GeoFixProvider mGeoFixProvider; GpxImporter(GeoFixProvider geoFixProvider, GpxLoader gpxLoader, ListActivity listActivity, ImportThreadWrapper importThreadWrapper, MessageHandler messageHandler, ToastFactory toastFactory, EventHandlers eventHandlers, ErrorDisplayer errorDisplayer, GeocacheFactory geocacheFactory) { mListActivity = listActivity; mGpxLoader = gpxLoader; mEventHandlers = eventHandlers; mImportThreadWrapper = importThreadWrapper; mMessageHandler = messageHandler; mErrorDisplayer = errorDisplayer; mToastFactory = toastFactory; mGeoFixProvider = geoFixProvider; mGeocacheFactory = geocacheFactory; } public void abort() { mMessageHandler.abortLoad(); mGpxLoader.abort(); if (mImportThreadWrapper.isAlive()) { mImportThreadWrapper.join(); mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT); } //TODO: Resume list updates? } public void importGpxs(CacheListAdapter cacheList) { mGeoFixProvider.onPause(); mImportThreadWrapper.open(cacheList, mGpxLoader, mEventHandlers, mErrorDisplayer, mGeocacheFactory); mImportThreadWrapper.start(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.cachedetails.CacheDetailsWriter; import com.google.code.geobeagle.xmlimport.FileFactory; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import android.os.PowerManager.WakeLock; import java.io.File; import java.io.IOException; public class CachePersisterFacade { private final CacheDetailsWriter mCacheDetailsWriter; private String mCacheName = ""; private final CacheTagSqlWriter mCacheTagWriter; private final FileFactory mFileFactory; private final MessageHandler mMessageHandler; private final WakeLock mWakeLock; private final String mUsername; static interface TextHandler { public void text(String fullpath) throws IOException; } TextHandler wptName = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheDetailsWriter.open(fullpath); mCacheDetailsWriter.writeWptName(fullpath); mCacheTagWriter.id(fullpath); mMessageHandler.updateWaypointId(fullpath); mWakeLock.acquire(GpxLoader.WAKELOCK_DURATION); } }; TextHandler wptDesc = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheName = fullpath; mCacheTagWriter.cacheName(fullpath); } }; TextHandler logDate = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheDetailsWriter.writeLogDate(fullpath); } }; TextHandler hint = new TextHandler() { @Override public void text(String fullpath) throws IOException { if (!fullpath.equals("")) mCacheDetailsWriter.writeHint(fullpath); } }; TextHandler cacheType = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.cacheType(fullpath); } }; TextHandler difficulty = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.difficulty(fullpath); } }; TextHandler container = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.container(fullpath); } }; TextHandler terrain = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.terrain(fullpath); } }; TextHandler groundspeakName = new TextHandler() { @Override public void text(String fullpath) throws IOException { mCacheTagWriter.cacheName(fullpath); } }; TextHandler placedBy = new TextHandler() { @Override public void text(String fullpath) throws IOException { boolean isMine = (!mUsername.equals("") && mUsername .equalsIgnoreCase(fullpath)); mCacheTagWriter.setTag(Tags.MINE, isMine); } }; CachePersisterFacade(CacheTagSqlWriter cacheTagSqlWriter, FileFactory fileFactory, CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock, String username) { mCacheDetailsWriter = cacheDetailsWriter; mCacheTagWriter = cacheTagSqlWriter; mFileFactory = fileFactory; mMessageHandler = messageHandler; mWakeLock = wakeLock; mUsername = username; } void close(boolean success) { mCacheTagWriter.stopWriting(success); } void end() { mCacheTagWriter.end(); } void endCache(Source source) throws IOException { mMessageHandler.updateName(mCacheName); mCacheDetailsWriter.close(); mCacheTagWriter.write(source); } boolean gpxTime(String gpxTime) { return mCacheTagWriter.gpxTime(gpxTime); } void line(String text) throws IOException { mCacheDetailsWriter.writeLine(text); } void open(String path) { mMessageHandler.updateSource(path); mCacheTagWriter.startWriting(); mCacheTagWriter.gpxName(path); } void start() { File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR); file.mkdirs(); } void startCache() { mCacheName = ""; mCacheTagWriter.clear(); } public void setTag(int tag, boolean set) { mCacheTagWriter.setTag(tag, set); } void wpt(String latitude, String longitude) { mCacheTagWriter.latitudeLongitude(latitude, longitude); mCacheDetailsWriter.latitudeLongitude(latitude, 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.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import java.io.IOException; public class EventHelper { public static class XmlPathBuilder { private String mPath = ""; public void endTag(String currentTag) { mPath = mPath.substring(0, mPath.length() - (currentTag.length() + 1)); } public String getPath() { return mPath; } public void startTag(String mCurrentTag) { mPath += "/" + mCurrentTag; } } private final EventHandler mEventHandler; private final XmlPathBuilder mXmlPathBuilder; private final XmlPullParserWrapper mXmlPullParser; EventHelper(XmlPathBuilder xmlPathBuilder, EventHandler eventHandler, XmlPullParserWrapper xmlPullParser) { mXmlPathBuilder = xmlPathBuilder; mXmlPullParser = xmlPullParser; mEventHandler = eventHandler; } /** @return false if this file has already been loaded */ public boolean handleEvent(int eventType) throws IOException { switch (eventType) { case XmlPullParser.START_TAG: mXmlPathBuilder.startTag(mXmlPullParser.getName()); mEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser); break; case XmlPullParser.END_TAG: mEventHandler.endTag(mXmlPathBuilder.getPath()); mXmlPathBuilder.endTag(mXmlPullParser.getName()); break; case XmlPullParser.TEXT: return mEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText()); } return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; interface EventHandler { void endTag(String previousFullPath) throws IOException; void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException; boolean text(String mFullPath, String text) throws IOException; }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.Reader; public class GpxToCache { public static class Aborter { private static boolean mAborted = false; public Aborter() { mAborted = false; } public void abort() { mAborted = true; } public boolean isAborted() { return mAborted; } public void reset() { mAborted = false; } } @SuppressWarnings("serial") public static class CancelException extends Exception { } private final Aborter mAborter; private final XmlPullParserWrapper mXmlPullParserWrapper; GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, Aborter aborter) { mXmlPullParserWrapper = xmlPullParserWrapper; mAborter = aborter; } public void abort() { mAborter.abort(); } public String getSource() { return mXmlPullParserWrapper.getSource(); } /** * @param eventHelper * @return true if this file has already been loaded. * @throws XmlPullParserException * @throws IOException * @throws CancelException */ public boolean load(EventHelper eventHelper) throws XmlPullParserException, IOException, CancelException { int eventType; for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper .next()) { if (mAborter.isAborted()) throw new CancelException(); // File already loaded. if (!eventHelper.handleEvent(eventType)) return true; } // Pick up END_DOCUMENT event as well. eventHelper.handleEvent(eventType); return false; } public void open(String source, Reader reader) throws XmlPullParserException { mXmlPullParserWrapper.open(source, reader); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.ErrorDisplayer; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.R; import com.google.code.geobeagle.xmlimport.EventHelperDI.EventHelperFactory; import com.google.code.geobeagle.xmlimport.GpxImporterDI.MessageHandler; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles; import com.google.code.geobeagle.xmlimport.gpx.IGpxReader; import com.google.code.geobeagle.xmlimport.gpx.GpxAndZipFiles.GpxFilesAndZipFilesIter; import org.xmlpull.v1.XmlPullParserException; import java.io.FileNotFoundException; import java.io.IOException; public class ImportThreadDelegate { public static class ImportThreadHelper { private final ErrorDisplayer mErrorDisplayer; private final EventHandlers mEventHandlers; private final EventHelperFactory mEventHelperFactory; private final GpxLoader mGpxLoader; private boolean mHasFiles; private final MessageHandler mMessageHandler; private final GeocacheFactory mGeocacheFactory; public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler, EventHelperFactory eventHelperFactory, EventHandlers eventHandlers, ErrorDisplayer errorDisplayer, GeocacheFactory geocacheFactory) { mErrorDisplayer = errorDisplayer; mGpxLoader = gpxLoader; mMessageHandler = messageHandler; mEventHelperFactory = eventHelperFactory; mEventHandlers = eventHandlers; mHasFiles = false; mGeocacheFactory = geocacheFactory; } public void cleanup() { mMessageHandler.loadComplete(); } public void end() { mGpxLoader.end(); if (!mHasFiles) mErrorDisplayer.displayError(R.string.error_no_gpx_files); mGeocacheFactory.flushCacheIcons(); } /** @return true if we should continue to load files */ public boolean processFile(IGpxReader gpxReader) throws XmlPullParserException, IOException { String filename = gpxReader.getFilename(); mHasFiles = true; mGpxLoader.open(filename, gpxReader.open()); return mGpxLoader.load(mEventHelperFactory.create(mEventHandlers.get(filename))); } public void start() { mGpxLoader.start(); } } private final ErrorDisplayer mErrorDisplayer; private final GpxAndZipFiles mGpxAndZipFiles; private final ImportThreadHelper mImportThreadHelper; public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles, ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) { mGpxAndZipFiles = gpxAndZipFiles; mImportThreadHelper = importThreadHelper; mErrorDisplayer = errorDisplayer; } public void run() { try { tryRun(); } catch (final FileNotFoundException e) { mErrorDisplayer.displayError(R.string.error_opening_file, e.getMessage()); } catch (IOException e) { mErrorDisplayer.displayError(R.string.error_reading_file, e.getMessage()); } catch (XmlPullParserException e) { mErrorDisplayer.displayError(R.string.error_parsing_file, e.getMessage()); } finally { mImportThreadHelper.cleanup(); } } protected void tryRun() throws IOException, XmlPullParserException { GpxFilesAndZipFilesIter gpxFilesAndZipFilesIter = mGpxAndZipFiles.iterator(); if (gpxFilesAndZipFilesIter == null) { mErrorDisplayer.displayError(R.string.error_cant_read_sd); return; } mImportThreadHelper.start(); while (gpxFilesAndZipFilesIter.hasNext()) { if (!mImportThreadHelper.processFile(gpxFilesAndZipFilesIter.next())) return; } mImportThreadHelper.end(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.xmlimport.GpxToCacheDI.XmlPullParserWrapper; import java.io.IOException; class EventHandlerLoc implements EventHandler { static final String XPATH_COORD = "/loc/waypoint/coord"; static final String XPATH_GROUNDSPEAKNAME = "/loc/waypoint/name"; static final String XPATH_LOC = "/loc"; static final String XPATH_WPT = "/loc/waypoint"; static final String XPATH_WPTNAME = "/loc/waypoint/name"; private final CachePersisterFacade mCachePersisterFacade; EventHandlerLoc(CachePersisterFacade cachePersisterFacade) { mCachePersisterFacade = cachePersisterFacade; } public void endTag(String previousFullPath) throws IOException { if (previousFullPath.equals(XPATH_WPT)) { mCachePersisterFacade.endCache(Source.LOC); } } public void startTag(String mFullPath, XmlPullParserWrapper mXmlPullParser) throws IOException { if (mFullPath.equals(XPATH_COORD)) { mCachePersisterFacade.wpt(mXmlPullParser.getAttributeValue(null, "lat"), mXmlPullParser .getAttributeValue(null, "lon")); } else if (mFullPath.equals(XPATH_WPTNAME)) { mCachePersisterFacade.startCache(); mCachePersisterFacade.wptName.text(mXmlPullParser.getAttributeValue(null, "id")); } } public boolean text(String mFullPath, String text) throws IOException { if (mFullPath.equals(XPATH_WPTNAME)) mCachePersisterFacade.groundspeakName.text(text.trim()); return true; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.xmlimport; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.CacheTypeFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.database.CacheWriter; import android.util.Log; import java.util.Hashtable; /** * @author sng */ public class CacheTagSqlWriter { private final CacheTypeFactory mCacheTypeFactory; private CacheType mCacheType; private final CacheWriter mCacheWriter; private int mContainer; private int mDifficulty; private String mGpxName; private CharSequence mId; private double mLatitude; private double mLongitude; private CharSequence mName; private String mSqlDate; /** An entry here means that the tag is to be removed or added. * Other tags are left as they are. */ private Hashtable<Integer, Boolean> mTags = new Hashtable<Integer, Boolean>(); private int mTerrain; public CacheTagSqlWriter(CacheWriter cacheWriter, CacheTypeFactory cacheTypeFactory) { mCacheWriter = cacheWriter; mCacheTypeFactory = cacheTypeFactory; } public void cacheName(String name) { mName = name; } public void cacheType(String type) { mCacheType = mCacheTypeFactory.fromTag(type); } public void clear() { // TODO: ensure source is not reset mId = mName = null; mLatitude = mLongitude = 0; mCacheType = CacheType.NULL; mDifficulty = 0; mTerrain = 0; mTags.clear(); } public void container(String container) { mContainer = mCacheTypeFactory.container(container); } public void difficulty(String difficulty) { mDifficulty = mCacheTypeFactory.stars(difficulty); } public void end() { mCacheWriter.clearEarlierLoads(); } public void gpxName(String gpxName) { mGpxName = gpxName; } /** * @param gpxTime * @return true if we should load this gpx; false if the gpx is already * loaded. */ public boolean gpxTime(String gpxTime) { mSqlDate = isoTimeToSql(gpxTime); if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) { return false; } mCacheWriter.clearCaches(mGpxName); return true; } public void id(CharSequence id) { mId = id; } public String isoTimeToSql(String gpxTime) { return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = Double.parseDouble(latitude); mLongitude = Double.parseDouble(longitude); } public void startWriting() { mSqlDate = "2000-01-01T12:00:00"; mCacheWriter.startWriting(); } public void stopWriting(boolean successfulGpxImport) { mCacheWriter.stopWriting(); if (successfulGpxImport) mCacheWriter.writeGpx(mGpxName, mSqlDate); } public void setTag(int tag, boolean set) { mTags.put(tag, set); } public void terrain(String terrain) { mTerrain = mCacheTypeFactory.stars(terrain); } public void write(Source source) { if (mCacheWriter.isLockedFromUpdating(mId)) { Log.i("GeoBeagle", "Not updating " + mId + " because it is locked"); return; } for (Integer tag : mTags.keySet()) mCacheWriter.updateTag(mId, tag, mTags.get(tag)); boolean changed = mCacheWriter.conditionallyWriteCache(mId, mName, mLatitude, mLongitude, source, mGpxName, mCacheType, mDifficulty, mTerrain, mContainer); if (changed) mCacheWriter.updateTag(mId, Tags.NEW, true); } }
Java
package com.google.code.geobeagle.xmlimport; import java.util.HashMap; public class EventHandlers { private final HashMap<String, EventHandler> mEventHandlers = new HashMap<String, EventHandler>(); public void add(String extension, EventHandler eventHandler) { mEventHandlers.put(extension.toLowerCase(), eventHandler); } public EventHandler get(String filename) { int len = filename.length(); String extension = filename.substring(Math.max(0, len - 4), len); return mEventHandlers.get(extension.toLowerCase()); } }
Java
package com.google.code.geobeagle; public interface GeoFixProvider extends IPausable { //From IPausableAndResumable: public void onResume(); public void onPause(); public GeoFix getLocation(); public void addObserver(Refresher refresher); //TODO: Rename to "areUpdatesEnabled" or something public boolean isProviderEnabled(); /* Returns the direction the device is pointing, measured in degrees. */ public float getAzimuth(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; public interface Refresher { public void refresh(); public void forceRefresh(); }
Java
package com.google.code.geobeagle; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; /** An ordered list of geocache objects, with support for * comparing with another such list. * * A future implementation can fetch * the geocaches from the database when first needed */ public class GeocacheListPrecomputed extends AbstractList<Geocache> { private final ArrayList<Geocache> mList; public static GeocacheListPrecomputed EMPTY = new GeocacheListPrecomputed(); public GeocacheListPrecomputed() { mList = new ArrayList<Geocache>(); } public GeocacheListPrecomputed(ArrayList<Geocache> list) { mList = list; } /** 'Special' constructor used by ProximityPainter */ public GeocacheListPrecomputed(AbstractList<Geocache> list, Geocache extra) { mList = new ArrayList<Geocache>(list); mList.add(extra); } @Override public Iterator<Geocache> iterator() { return mList.iterator(); } @Override public int size() { return mList.size(); } @Override public Geocache get(int position) { return mList.get(position); } }
Java
package com.google.code.geobeagle; import android.location.Location; /** Wrapper for the class android.location.Location that can't be instantiated directly */ public class GeoFix { public static final GeoFix NO_FIX = new GeoFix(0f, 0f, 0d, 0d, 0L, ""); private final float mAccuracy; private final double mAltitude; private final double mLatitude; private final double mLongitude; private final long mTime; private final String mProvider; public GeoFix(Location location) { mAccuracy = location.getAccuracy(); mAltitude = location.getAltitude(); mLatitude = location.getLatitude(); mLongitude = location.getLongitude(); mTime = location.getTime(); mProvider = location.getProvider(); } public GeoFix(float accuracy, double altitude, double latitude, double longitude, long time, String provider) { mAccuracy = accuracy; mAltitude = altitude; mLatitude = latitude; mLongitude = longitude; mTime = time; mProvider = provider; } public float getAccuracy() { return mAccuracy; } public double getAltitude() { return mAltitude; } public double getLatitude() { return mLatitude; } public double getLongitude() { return mLongitude; } public long getTime() { return mTime; } /** Returns a String with the lag given that systemTime is the current time. */ public String getLagString(long systemTime) { if (this == NO_FIX) return ""; float lagSec = (systemTime - mTime) / 1000f; if (lagSec > 3600 * 10) { // > 10 hour int lagHours = (int)(lagSec/3600); return lagHours + "h"; } else if (lagSec > 3600) { // > 1 hour int lagHours = (int)(lagSec/3600); int lagMin = (int)(lagSec/60 - lagHours*60); if (lagMin > 0) return lagHours + "h " + lagMin + "m"; else return lagHours + "h"; } else if (lagSec > 60) { int lagMin = (int)(lagSec/60); lagSec = lagSec - lagMin*60; //lagSec = ((int)(lagSec*10)) / 10f; //round if ((int)lagSec > 0) return lagMin + "m " + ((int)lagSec) + "s"; else return lagMin + "m"; } else if (lagSec >= 2) { return ((int)lagSec) + "s"; } else { //Not enough lag to be worth showing return ""; } } /** @result Approximate distance in meters */ public float distanceTo(GeoFix fix) { float results[] = { 0 }; Location.distanceBetween(mLatitude, mLongitude, fix.getLatitude(), fix.getLongitude(), results); return results[0]; } public CharSequence getProvider() { return mProvider; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.content.Context; import android.content.Intent; import android.content.res.Resources; public class CacheActionView extends ActionStaticLabel implements CacheAction { private final Context mContext; public CacheActionView(Context context, Resources resources) { super(resources, R.string.menu_view_geocache); mContext = context; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mContext, GeoBeagle.class); intent.setAction(GeocacheListController.SELECT_CACHE); intent.putExtra("geocacheId", cache.getId()); mContext.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; public class CacheActionDelete extends ActionStaticLabel implements CacheAction { private final CacheListAdapter mCacheListAdapter; private final DbFrontend mDbFrontend; private final TitleUpdater mTitleUpdater; private final CachesProviderDb mCachesToFlush; public CacheActionDelete(CacheListAdapter cacheListAdapter, TitleUpdater titleUpdater, DbFrontend dbFrontend, CachesProviderDb cachesToFlush, Resources resources) { super(resources, R.string.menu_delete_cache); mCacheListAdapter = cacheListAdapter; mTitleUpdater = titleUpdater; mDbFrontend = dbFrontend; mCachesToFlush = cachesToFlush; } @Override public void act(Geocache cache) { mDbFrontend.getCacheWriter().deleteCache(cache.getId()); mCachesToFlush.notifyOfDbChange(); //Reload the cache list from the database mTitleUpdater.refresh(); mCacheListAdapter.forceRefresh(); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** Adds a confirm dialog before carrying out the nested CacheAction */ public class CacheActionConfirm implements CacheAction { private final Activity mActivity; private final CacheAction mCacheAction; //May Builder only be used once? private final AlertDialog.Builder mBuilder; private final String mTitle; private final String mBody; public CacheActionConfirm(Activity activity, AlertDialog.Builder builder, CacheAction cacheAction, String title, String body) { mActivity = activity; mBuilder = builder; mCacheAction = cacheAction; mTitle = title; mBody = body; } private AlertDialog buildAlertDialog(final Geocache cache) { final String title = String.format(mTitle, cache.getId()); final String message = String.format(mBody, cache.getId(), cache.getName()); mBuilder.setTitle(title); mBuilder.setMessage(message) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); mCacheAction.act(cache); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = mBuilder.create(); alertDialog.setOwnerActivity(mActivity); return alertDialog; } @Override public void act(Geocache cache) { AlertDialog alertDialog = buildAlertDialog(cache); alertDialog.show(); } @Override public String getLabel(Geocache geocache) { return mCacheAction.getLabel(geocache); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionRadar extends ActionStaticLabel implements CacheAction { Activity mActivity; public CacheActionRadar(Activity activity, Resources resources) { super(resources, R.string.radar); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent("com.google.android.radar.SHOW_RADAR"); intent.putExtra("latitude", (float)cache.getLatitude()); intent.putExtra("longitude", (float)cache.getLongitude()); mActivity.startActivity(intent); } @Override public String getLabel(Geocache geocache) { return mActivity.getResources().getString(R.string.radar); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; public interface CacheAction { public void act(Geocache cache); /** Returns the text to show to the user for this action. * The text is allowed to change depending on runtime circumstances. * @param geocache */ public String getLabel(Geocache geocache); }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.database.ICachesProvider; import android.util.Log; import android.view.ContextMenu; import android.view.MenuItem; import android.view.View; import android.view.ContextMenu.ContextMenuInfo; import android.view.View.OnCreateContextMenuListener; import android.widget.AdapterView.AdapterContextMenuInfo; public class CacheContextMenu implements OnCreateContextMenuListener { private final ICachesProvider mCachesProvider; private final CacheAction mCacheActions[]; /** The geocache for which the menu was launched */ private Geocache mGeocache = null; public CacheContextMenu(ICachesProvider cachesProvider, CacheAction cacheActions[]) { mCachesProvider = cachesProvider; mCacheActions = cacheActions; } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo; if (acmi.position > 0) { mGeocache = mCachesProvider.getCaches().get(acmi.position - 1); menu.setHeaderTitle(mGeocache.getId()); for (int ix = 0; ix < mCacheActions.length; ix++) { menu.add(0, ix, ix, mCacheActions[ix].getLabel(mGeocache)); } } } public boolean onContextItemSelected(MenuItem menuItem) { Log.d("GeoBeagle", "Context menu doing action " + menuItem.getItemId() + " = " + mCacheActions[menuItem.getItemId()].getClass().toString()); mCacheActions[menuItem.getItemId()].act(mGeocache); return true; } public Geocache getGeocache() { return mGeocache; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.filterlist.FilterListActivity; import android.content.Context; import android.content.Intent; import android.content.res.Resources; public class MenuActionFilterList extends ActionStaticLabel implements MenuAction { private final Context mContext; public MenuActionFilterList(Context context, Resources resources) { super(resources, R.string.menu_filterlist); mContext = context; } @Override public void act() { final Intent intent = new Intent(mContext, FilterListActivity.class); mContext.startActivity(intent); } @Override public String getLabel() { return mContext.getString(R.string.menu_filterlist); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.prox.ProximityActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionProximity extends ActionStaticLabel implements MenuAction { Activity mActivity; public MenuActionProximity(Activity activity, Resources resources) { super(resources, R.string.menu_proximity); mActivity = activity; } @Override public void act() { final Intent intent = new Intent(mActivity, ProximityActivity.class); mActivity.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import android.content.res.Resources; public class ActionStaticLabel { private final Resources mResources; private final int mLabelId; public ActionStaticLabel(Resources resources, int labelId) { super(); mResources = resources; mLabelId = labelId; } public String getLabel() { return mResources.getString(mLabelId); } public String getLabel(Geocache geocache) { return getLabel(); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; public class MenuActionClearTagNew implements MenuAction { private final DbFrontend mDbFrontend; private final GeocacheFactory mGeocacheFactory; private final CacheListAdapter mCacheListAdapter; public MenuActionClearTagNew(DbFrontend dbFrontend, GeocacheFactory geocacheFactory, CacheListAdapter cacheListAdapter) { mDbFrontend = dbFrontend; mGeocacheFactory = geocacheFactory; mCacheListAdapter = cacheListAdapter; } @Override public void act() { mDbFrontend.clearTagForAllCaches(Tags.NEW); mGeocacheFactory.flushCacheIcons(); mCacheListAdapter.notifyDataSetChanged(); } @Override public String getLabel() { return "Clear all 'new'"; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.activity.cachelist.presenter.TitleUpdater; import com.google.code.geobeagle.database.CachesProviderDb; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; /** Deletes all caches in the database */ public class MenuActionDeleteAll extends ActionStaticLabel implements MenuAction { private final DbFrontend mDbFrontend; private final CachesProviderDb mCachesToFlush; private final TitleUpdater mTitleUpdater; private final CacheListAdapter mCacheListAdapter; public MenuActionDeleteAll(DbFrontend dbFrontend, Resources resources, CachesProviderDb cachesToFlush, CacheListAdapter cacheListAdapter, TitleUpdater titleUpdater, int labelId) { super(resources, labelId); mDbFrontend = dbFrontend; mCachesToFlush = cachesToFlush; mCacheListAdapter = cacheListAdapter; mTitleUpdater = titleUpdater; } @Override public void act() { mDbFrontend.deleteAll(); mCachesToFlush.notifyOfDbChange(); //Reload the cache list from the database mTitleUpdater.refresh(); mCacheListAdapter.forceRefresh(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.map.GeoMapActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionMap extends ActionStaticLabel implements CacheAction { Activity mActivity; public CacheActionMap(Activity activity, Resources resources) { super(resources, R.string.menu_cache_map); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mActivity, GeoMapActivity.class); intent.putExtra("latitude", (float)cache.getLatitude()); intent.putExtra("longitude", (float)cache.getLongitude()); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; public class CacheActionToggleFavorite implements CacheAction { private final DbFrontend mDbFrontend; private final CacheListAdapter mCacheList; private final CacheFilterUpdater mCacheFilterUpdater; public CacheActionToggleFavorite(DbFrontend dbFrontend, CacheListAdapter cacheList, CacheFilterUpdater cacheFilterUpdater) { mDbFrontend = dbFrontend; mCacheList = cacheList; mCacheFilterUpdater = cacheFilterUpdater; } @Override public void act(Geocache geocache) { boolean isFavorite = mDbFrontend.geocacheHasTag(geocache.getId(), Tags.FAVORITES); mDbFrontend.setGeocacheTag(geocache.getId(), Tags.FAVORITES, !isFavorite); mCacheFilterUpdater.loadActiveFilter(); mCacheList.forceRefresh(); } @Override public String getLabel(Geocache geocache) { boolean isFavorite = mDbFrontend.geocacheHasTag(geocache.getId(), Tags.FAVORITES); return isFavorite ? "Remove from Favorites" : "Add to Favorites"; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import android.app.Activity; import android.app.Dialog; import android.content.res.Resources; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.RadioGroup; /** Show a popup dialog to let the user choose what filter to use */ public class MenuActionFilterListPopup extends ActionStaticLabel implements MenuAction { private final Activity mActivity; private final FilterTypeCollection mFilterTypeCollection; private final CacheFilterUpdater mCacheFilterUpdater; private final Refresher mRefresher; public MenuActionFilterListPopup(Activity activity, CacheFilterUpdater cacheFilterUpdater, Refresher refresher, FilterTypeCollection filterTypeCollection, Resources resources) { super(resources, R.string.menu_choose_filter); mActivity = activity; mCacheFilterUpdater = cacheFilterUpdater; mRefresher = refresher; mFilterTypeCollection = filterTypeCollection; } @Override public void act() { final Dialog dialog = new Dialog(mActivity); final RadioGroup radioGroup = new RadioGroup(mActivity); LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams( RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT); final OnClickListener mOnSelect = new OnClickListener() { @Override public void onClick(View v) { int ix = radioGroup.getCheckedRadioButtonId(); CacheFilter cacheFilter = mFilterTypeCollection.get(ix); Log.d("GeoBeagle", "Setting active filter to " + cacheFilter.getName() + " with id " + cacheFilter.mId); mFilterTypeCollection.setActiveFilter(cacheFilter); dialog.dismiss(); mCacheFilterUpdater.loadActiveFilter(); mRefresher.forceRefresh(); } }; radioGroup.setOnClickListener(mOnSelect); for (int i = 0; i < mFilterTypeCollection.getCount(); i++) { CacheFilter cacheFilter = mFilterTypeCollection.get(i); RadioButton newRadioButton = new RadioButton(mActivity); newRadioButton.setOnClickListener(mOnSelect); newRadioButton.setText(cacheFilter.getName()); newRadioButton.setId(i); radioGroup.addView(newRadioButton, layoutParams); } int selected = mFilterTypeCollection.getIndexOf(mFilterTypeCollection. getActiveFilter()); radioGroup.check(selected); //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setTitle("Choose filter"); //dialog.setContentView(R.layout.filterlist); dialog.setContentView(radioGroup); //TextView title = (TextView)dialog.findViewById(R.id.TextFilterTitle); //title.setText(getLabel()); dialog.show(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.EditCacheActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionEdit extends ActionStaticLabel implements CacheAction { private final Activity mActivity; public CacheActionEdit(Activity activity, Resources resources) { super(resources, R.string.menu_edit_geocache); mActivity = activity; } @Override public void act(Geocache cache) { Intent intent = new Intent(mActivity, EditCacheActivity.class); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivityForResult(intent, 0); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.prox.ProximityActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class CacheActionProximity extends ActionStaticLabel implements CacheAction { private Activity mActivity; public CacheActionProximity(Activity activity, Resources resources) { super(resources, R.string.menu_proximity); mActivity = activity; } @Override public void act(Geocache cache) { final Intent intent = new Intent(mActivity, ProximityActivity.class); intent.putExtra("geocacheId", cache.getId()); mActivity.startActivity(intent); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import com.google.code.geobeagle.database.CachesProviderDb; import java.util.List; //TODO: Rename class CacheFilterUpdater.. "reload cache list from cachefilter" public class CacheFilterUpdater { private final FilterTypeCollection mFilterTypeCollection; private final List<CachesProviderDb> mCachesProviderDb; public CacheFilterUpdater(FilterTypeCollection filterTypeCollection, List<CachesProviderDb> cachesProviderDb) { mCachesProviderDb = cachesProviderDb; mFilterTypeCollection = filterTypeCollection; } public void loadActiveFilter() { CacheFilter filter = mFilterTypeCollection.getActiveFilter(); //Log.d("GeoBeagle", "CacheFilterUpdater loading " + filter.mId); for (CachesProviderDb provider : mCachesProviderDb) { provider.setFilter(filter); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import android.content.res.Resources; public class CacheActionGoogleMaps extends ActionStaticLabel implements CacheAction { private final CacheActionViewUri mCacheActionViewUri; public CacheActionGoogleMaps(CacheActionViewUri cacheActionViewUri, Resources resources) { super(resources, R.string.menu_google_maps); mCacheActionViewUri = cacheActionViewUri; } @Override public void act(Geocache cache) { mCacheActionViewUri.act(cache); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.activity.cachelist.presenter.CacheListAdapter; import com.google.code.geobeagle.database.DbFrontend; import android.app.Activity; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnDismissListener; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.LinearLayout; import android.widget.LinearLayout.LayoutParams; import java.util.Map; public class CacheActionAssignTags implements CacheAction { private final Activity mActivity; private final DbFrontend mDbFrontend; private final CacheListAdapter mCacheListAdapter; public CacheActionAssignTags(Activity activity, DbFrontend dbFrontend, CacheListAdapter cacheListAdapter) { mActivity = activity; mDbFrontend = dbFrontend; mCacheListAdapter = cacheListAdapter; } private boolean hasChanged = false; @Override public void act(final Geocache cache) { final Dialog dialog = new Dialog(mActivity); View rootView = mActivity.getLayoutInflater().inflate(R.layout.assign_tags, null); LinearLayout linearLayout = (LinearLayout)rootView.findViewById(R.id.AssignTagsLinearLayout); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); final OnClickListener mOnSelect = new OnClickListener() { @Override public void onClick(View v) { CheckBox checkbox = (CheckBox)v; int tagId = v.getId(); boolean checked = checkbox.isChecked(); Log.d("GeoBeagle", "Setting tag " + tagId + " to " + (checked?"true":"false")); mDbFrontend.setGeocacheTag(cache.getId(), tagId, checked); hasChanged = true; cache.flushIcons(); } }; final OnDismissListener onDismiss = new OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { if (hasChanged) mCacheListAdapter.notifyDataSetChanged(); } }; dialog.setOnDismissListener(onDismiss); Map<Integer, String> allTags = Tags.GetAllTags(); for (Integer i : allTags.keySet()) { String tagName = allTags.get(i); boolean hasTag = mDbFrontend.geocacheHasTag(cache.getId(), i); CheckBox checkbox = new CheckBox(mActivity); checkbox.setChecked(hasTag); checkbox.setOnClickListener(mOnSelect); checkbox.setText(tagName); checkbox.setId(i); linearLayout.addView(checkbox, layoutParams); } //dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setTitle("Assign tags to " + cache.getId()); dialog.setContentView(linearLayout); dialog.show(); } @Override public String getLabel(Geocache geocache) { return mActivity.getResources().getString(R.string.assign_tags); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.searchonline.SearchOnlineActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionSearchOnline extends ActionStaticLabel implements MenuAction { private final Activity mActivity; public MenuActionSearchOnline(Activity activity, Resources resources) { super(resources, R.string.menu_search_online); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, SearchOnlineActivity.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.main.GeoBeagle; import com.google.code.geobeagle.activity.main.intents.GeocacheToUri; import com.google.code.geobeagle.activity.main.intents.IntentFactory; import android.content.Intent; import android.content.res.Resources; public class CacheActionViewUri extends ActionStaticLabel implements CacheAction { private final GeoBeagle mGeoBeagle; private final GeocacheToUri mGeocacheToUri; private final IntentFactory mIntentFactory; public CacheActionViewUri(GeoBeagle geoBeagle, IntentFactory intentFactory, GeocacheToUri geocacheToUri, Resources resources) { super(resources, R.string.cache_page); mGeoBeagle = geoBeagle; mGeocacheToUri = geocacheToUri; mIntentFactory = intentFactory; } @Override public void act(Geocache cache) { mGeoBeagle.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, mGeocacheToUri.convert(cache))); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.cachelist.CacheListActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionCacheList extends ActionStaticLabel implements MenuAction { private Activity mActivity; public MenuActionCacheList(Activity activity, Resources resources) { super(resources, R.string.menu_cache_list); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, CacheListActivity.class)); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.preferences.EditPreferences; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; public class MenuActionSettings extends ActionStaticLabel implements MenuAction { private final Activity mActivity; public MenuActionSettings(Activity activity, Resources resources) { super(resources, R.string.menu_settings); mActivity = activity; } @Override public void act() { mActivity.startActivity(new Intent(mActivity, EditPreferences.class)); } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.R; import com.google.code.geobeagle.activity.map.GeoMapActivity; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; /** Show the map, centered around the current location */ public class MenuActionMap extends ActionStaticLabel implements MenuAction { private final GeoFixProvider mLocationControl; private final Activity mActivity; public MenuActionMap(Activity activity, GeoFixProvider locationControl, Resources resources) { super(resources, R.string.menu_map); mActivity = activity; mLocationControl = locationControl; } @Override public void act() { GeoFix location = mLocationControl.getLocation(); final Intent intent = new Intent(mActivity, GeoMapActivity.class); intent.putExtra("latitude", (float)location.getLatitude()); intent.putExtra("longitude", (float)location.getLongitude()); mActivity.startActivity(intent); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; public interface MenuAction { public void act(); /** Returns the text to show to the user for this action. May change. */ public String getLabel(); }
Java
package com.google.code.geobeagle.actions; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; /** Adds a confirm dialog before carrying out the nested MenuAction */ public class MenuActionConfirm implements MenuAction { private final Activity mActivity; private final MenuAction mMenuAction; //May Builder only be used once? private final AlertDialog.Builder mBuilder; private final String mTitle; private final String mBody; public MenuActionConfirm(Activity activity, AlertDialog.Builder builder, MenuAction menuAction, String title, String body) { mActivity = activity; mBuilder = builder; mMenuAction = menuAction; mTitle = title; mBody = body; } private AlertDialog buildAlertDialog() { mBuilder.setTitle(mTitle); mBuilder.setMessage(mBody) .setPositiveButton("Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); mMenuAction.act(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alertDialog = mBuilder.create(); alertDialog.setOwnerActivity(mActivity); return alertDialog; } @Override public void act() { AlertDialog alertDialog = buildAlertDialog(); alertDialog.show(); } @Override public String getLabel() { return mMenuAction.getLabel(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import com.google.code.geobeagle.Geocache; public class MenuActionFromCacheAction implements MenuAction { private CacheAction mCacheAction; private Geocache mTarget; public MenuActionFromCacheAction(CacheAction cacheAction, Geocache target) { mCacheAction = cacheAction; mTarget = target; } @Override public void act() { mCacheAction.act(mTarget); } public String getLabel() { return mCacheAction.getLabel(mTarget); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.actions; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import java.util.ArrayList; public class MenuActions { private ArrayList<MenuAction> mMenuActions = new ArrayList<MenuAction>(); public MenuActions() { } public MenuActions(MenuAction[] menuActions) { for (int ix = 0; ix < menuActions.length; ix++) { add(menuActions[ix]); } } public boolean act(int itemId) { if (itemId < 0 || itemId >= mMenuActions.size()) return false; mMenuActions.get(itemId).act(); return true; } public void add(MenuAction action) { mMenuActions.add(action); } /** Creates an Options Menu from the items in this MenuActions */ public boolean onCreateOptionsMenu(Menu menu) { if (mMenuActions.isEmpty()) { Log.w("GeoBeagle", "MenuActions.onCreateOptionsMenu: menu is empty, will not be shown"); return false; } menu.clear(); int ix = 0; for (MenuAction action : mMenuActions) { menu.add(0, ix, ix, action.getLabel()); ix++; } return true; } /** Give the menu items a chance to update the text */ public boolean onMenuOpened(Menu menu) { int ix = 0; for (MenuAction action : mMenuActions) { MenuItem item = menu.getItem(ix); String label = action.getLabel(); if (!item.getTitle().equals(label)) item.setTitle(label); ix++; } return true; } }
Java
package com.google.code.geobeagle.actions; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.filterlist.FilterTypeCollection; import android.app.Activity; import android.app.Dialog; import android.content.res.Resources; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.TextView; /** Show a dialog to let the user edit the current filter * for which geocaches to display */ public class MenuActionEditFilter extends ActionStaticLabel implements MenuAction { private final Activity mActivity; private final FilterTypeCollection mFilterTypeCollection; private final CacheFilterUpdater mCacheFilterUpdater; private final Refresher mRefresher; private CacheFilter mFilter; public MenuActionEditFilter(Activity activity, CacheFilterUpdater cacheFilterUpdater, Refresher refresher, FilterTypeCollection filterTypeCollection, Resources resources) { super(resources, R.string.menu_edit_filter); mActivity = activity; mCacheFilterUpdater = cacheFilterUpdater; mRefresher = refresher; mFilterTypeCollection = filterTypeCollection; } @Override public String getLabel() { return mActivity.getResources().getString(R.string.menu_edit_filter); } private class DialogFilterGui implements CacheFilter.FilterGui { private Dialog mDialog; public DialogFilterGui(Dialog dialog) { mDialog = dialog; } @Override public boolean getBoolean(int id) { return ((CompoundButton)mDialog.findViewById(id)).isChecked(); } @Override public String getString(int id) { return ((EditText)mDialog.findViewById(id)).getText().toString(); } @Override public void setBoolean(int id, boolean value) { ((CompoundButton)mDialog.findViewById(id)).setChecked(value); } @Override public void setString(int id, String value) { ((EditText)mDialog.findViewById(id)).setText(value); } }; @Override public void act() { final Dialog dialog = new Dialog(mActivity); final DialogFilterGui gui = new DialogFilterGui(dialog); final OnClickListener mOnApply = new OnClickListener() { @Override public void onClick(View v) { mFilter.loadFromGui(gui); mFilter.saveToPreferences(); dialog.dismiss(); mCacheFilterUpdater.loadActiveFilter(); mRefresher.forceRefresh(); } }; dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.setContentView(R.layout.filter); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireFavorites, R.id.CheckBoxForbidFavorites); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireFound, R.id.CheckBoxForbidFound); SetOpposingCheckBoxes(dialog, R.id.CheckBoxRequireDNF, R.id.CheckBoxForbidDNF); mFilter = mFilterTypeCollection.getActiveFilter(); TextView title = (TextView)dialog.findViewById(R.id.TextFilterTitle); title.setText("Editing filter \"" + mFilter.getName() + "\""); mFilter.pushToGui(gui); Button apply = (Button) dialog.findViewById(R.id.ButtonApplyFilter); apply.setOnClickListener(mOnApply); dialog.show(); } private static final OnClickListener OnCheck = new OnClickListener() { @Override public void onClick(View v) { final CheckBox checkBox = (CheckBox)v; if (checkBox.isChecked()) ((CheckBox)checkBox.getTag()).setChecked(false); } }; /** Registers two checkboxes to be opposing -- * selecting one will unselect the other */ private static void SetOpposingCheckBoxes(Dialog dialog, int id1, int id2) { CheckBox checkBox1 = (CheckBox)dialog.findViewById(id1); CheckBox checkBox2 = (CheckBox)dialog.findViewById(id2); checkBox1.setTag(checkBox2); checkBox1.setOnClickListener(OnCheck); checkBox2.setTag(checkBox1); checkBox2.setOnClickListener(OnCheck); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import android.content.SharedPreferences; import android.hardware.SensorListener; import android.hardware.SensorManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; import java.util.ArrayList; /** Responsible for providing an up-to-date location and compass direction */ @SuppressWarnings("deprecation") public class GeoFixProviderLive implements LocationListener, SensorListener, GeoFixProvider { private GeoFix mLocation; private final LocationManager mLocationManager; private float mAzimuth; /** A refresh is sent whenever a sensor changes */ private final ArrayList<Refresher> mObservers = new ArrayList<Refresher>(); private final SensorManager mSensorManager; private boolean mUseNetwork = true; private final SharedPreferences mSharedPreferences; public GeoFixProviderLive(LocationManager locationManager, SensorManager sensorManager, SharedPreferences sharedPreferences) { mLocationManager = locationManager; mSensorManager = sensorManager; mSharedPreferences = sharedPreferences; // mLocation = getLastKnownLocation(); //work in constructor.. } public GeoFix getLocation() { if (mLocation == null) { Location lastKnownLocation = getLastKnownLocation(); if (lastKnownLocation != null) mLocation = new GeoFix(lastKnownLocation); else mLocation = GeoFix.NO_FIX; } return mLocation; } public void addObserver(Refresher refresher) { if (!mObservers.contains(refresher)) mObservers.add(refresher); } private void notifyObservers() { for (Refresher refresher : mObservers) { refresher.refresh(); } } /** * Choose the better of two locations: If one location is newer and more * accurate, choose that. (This favors the gps). Otherwise, if one location * is newer, less accurate, but farther away than the sum of the two * accuracies, choose that. (This favors the network locator if you've * driven a distance and haven't been able to get a gps fix yet.) */ private static GeoFix choose(GeoFix oldLocation, GeoFix newLocation) { if (oldLocation == null) return newLocation; if (newLocation == null) return oldLocation; if (newLocation.getTime() > oldLocation.getTime()) { float distance = newLocation.distanceTo(oldLocation); // Log.d("GeoBeagle", "onLocationChanged distance="+distance + // " provider=" + newLocation.getProvider()); if (distance < 1) // doesn't take changing accuracy into account return oldLocation; // TODO: Handle network and gps different return newLocation; /* * if (newLocation.getAccuracy() <= oldLocation.getAccuracy()) * return newLocation; else if (oldLocation.distanceTo(newLocation) * >= oldLocation.getAccuracy() + newLocation.getAccuracy()) { * return newLocation; } */ } return oldLocation; } @Override public void onLocationChanged(Location location) { if (location == null) return; GeoFix chosen = choose(mLocation, new GeoFix(location)); if (chosen != mLocation) { mLocation = chosen; notifyObservers(); } } @Override public void onProviderDisabled(String provider) { Log.d("GeoBeagle", "onProviderDisabled(" + provider + ")"); } @Override public void onProviderEnabled(String provider) { Log.d("GeoBeagle", "onProviderEnabled(" + provider + ")"); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onAccuracyChanged(int sensor, int accuracy) { // Log.d("GeoBeagle", "onAccuracyChanged " + sensor + " accuracy " + // accuracy); } @Override public void onSensorChanged(int sensor, float[] values) { final float currentAzimuth = values[0]; if (Math.abs(currentAzimuth - mAzimuth) > 5) { // Log.d("GeoBeagle", "azimuth now " + sensor +", " + // currentAzimuth); mAzimuth = currentAzimuth; notifyObservers(); } } public void onResume() { mUseNetwork = mSharedPreferences.getBoolean("use-network-location", true); mSensorManager.registerListener(this, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_UI); long minTime = 1000; // ms float minDistance = 1; // meters mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, this); if (mUseNetwork) mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, minTime, minDistance, this); onLocationChanged(getLastKnownLocation()); } public void onPause() { mSensorManager.unregisterListener(this); mLocationManager.removeUpdates(this); } public boolean isProviderEnabled() { return mLocationManager.isProviderEnabled("gps") || (mUseNetwork && mLocationManager .isProviderEnabled("network")); } private Location getLastKnownLocation() { Location gpsLocation = mLocationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (gpsLocation != null) return gpsLocation; if (mUseNetwork) return mLocationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); return null; } public float getAzimuth() { return mAzimuth; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.Clock; import android.view.View; class MeterFader { private long mLastUpdateTime; private final MeterBars mMeterView; private final View mParent; private final Clock mTime; MeterFader(View parent, MeterBars meterBars, Clock 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; /* * 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.GeoFix; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.R; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.activity.cachelist.presenter.HasDistanceFormatter; import com.google.code.geobeagle.formatting.DistanceFormatter; import android.content.Context; import android.location.LocationProvider; import android.os.Bundle; import android.widget.TextView; public class GpsStatusWidgetDelegate implements HasDistanceFormatter, Refresher { private final Context mContext; private DistanceFormatter mDistanceFormatter; private final GeoFixProvider mGeoFixProvider; private final MeterFader mMeterFader; private final Meter mMeter; private final TextView mProvider; private final TextView mStatus; private final TextView mLagTextView; private GeoFix mGeoFix; private final TimeProvider mTimeProvider; public static interface TimeProvider { long getTime(); } public GpsStatusWidgetDelegate(GeoFixProvider geoFixProvider, DistanceFormatter distanceFormatter, Meter meter, MeterFader meterFader, TextView provider, Context context, TextView status, TextView lagTextView, GeoFix initialGeoFix, TimeProvider timeProvider) { mGeoFixProvider = geoFixProvider; mDistanceFormatter = distanceFormatter; mMeterFader = meterFader; mMeter = meter; mProvider = provider; mContext = context; mStatus = status; mLagTextView = lagTextView; mGeoFix = initialGeoFix; mTimeProvider = timeProvider; } 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(); } /** Called when the location changed */ public void refresh() { mGeoFix = mGeoFixProvider.getLocation(); //Log.d("GeoBeagle", "GpsStatusWidget onLocationChanged " + mGeoFix); /* if (!mGeoFixProvider.isProviderEnabled()) { mMeter.setDisabled(); mTextLagUpdater.setDisabled(); return; } */ mProvider.setText(mGeoFix.getProvider()); mMeter.setAccuracy(mGeoFix.getAccuracy(), mDistanceFormatter); mMeterFader.reset(); mLagTextView.setText(mGeoFix.getLagString(mTimeProvider.getTime())); } public void setDistanceFormatter(DistanceFormatter distanceFormatter) { mDistanceFormatter = distanceFormatter; } public void updateLagText(long systemTime) { mLagTextView.setText(mGeoFix.getLagString(systemTime)); } @Override public void forceRefresh() { refresh(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.gpsstatuswidget; import com.google.code.geobeagle.GeoFixProvider; import com.google.code.geobeagle.gpsstatuswidget.GpsStatusWidgetDelegate.TimeProvider; import android.os.Handler; /** Updates the Gps widget two times a second */ public class UpdateGpsWidgetRunnable implements Runnable { private final Handler mHandler; private final GeoFixProvider mGeoFixProvider; private final Meter mMeter; private final GpsStatusWidgetDelegate mGpsStatusWidgetDelegate; private final TimeProvider mTimeProvider; UpdateGpsWidgetRunnable(Handler handler, GeoFixProvider geoFixProvider, Meter meter, GpsStatusWidgetDelegate gpsStatusWidgetDelegate, TimeProvider timeProvider) { mMeter = meter; mGeoFixProvider = geoFixProvider; mHandler = handler; mGpsStatusWidgetDelegate = gpsStatusWidgetDelegate; mTimeProvider = timeProvider; } public void run() { // Update the lag time and the orientation. long systemTime = mTimeProvider.getTime(); mGpsStatusWidgetDelegate.updateLagText(systemTime); mMeter.setAzimuth(mGeoFixProvider.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; 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.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.IToaster; import android.util.Log; import java.util.AbstractList; public class PeggedCacheProvider { /** True if the last getCaches() was capped because too high cache count */ private boolean mTooManyCaches = false; private final IToaster mOneTimeToaster; public PeggedCacheProvider(IToaster toaster) { mOneTimeToaster = toaster; } AbstractList<Geocache> pegCaches(int maxCount, AbstractList<Geocache> caches) { mTooManyCaches = (caches.size() > maxCount); if (mTooManyCaches) { return GeocacheListPrecomputed.EMPTY; } return caches; } private void logStack() { StackTraceElement[] stackTrace = new Exception().getStackTrace(); for (StackTraceElement e : stackTrace) { Log.d("GeoBeagle", "stack: " + " " + e.getClassName() + ":" + e.getMethodName() + "[" + e.getLineNumber() + "]"); } } void showToastIfTooManyCaches() { mOneTimeToaster.showToast(mTooManyCaches); } public boolean isTooManyCaches() { return mTooManyCaches; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import android.database.Cursor; public interface ISQLiteDatabase { void beginTransaction(); void close(); int countResults(String table, String sql, String... args); void endTransaction(); void execSQL(String s, Object... bindArg1); Cursor query(String table, String[] columns, String selection, String groupBy, String having, String orderBy, String limit, String... selectionArgs); Cursor rawQuery(String string, String[] object); void setTransactionSuccessful(); boolean isOpen(); }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.CacheFilter; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.main.Util; import java.util.AbstractList; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; /** Uses a DB to fetch the caches within a defined region, or all caches if no * bounds were specified */ public class CachesProviderDb implements ICachesProviderArea { private DbFrontend mDbFrontend; private double mLatLow; private double mLonLow; private double mLatHigh; private double mLonHigh; /** The complete SQL query for the current coordinates and settings, * except from 'SELECT x'. If null, mSql needs to be re-calculated. */ private String mSql = null; private AbstractList<Geocache> mCaches; private boolean mHasChanged = true; private boolean mHasLimits = false; /** The 'where' part of the SQL clause that comes from the active CacheFilter */ private String mFilter = ""; /** The tag used for filtering. Tags.NULL means any tag allowed. */ private Set<Integer> mRequiredTags = new HashSet<Integer>(); private Set<Integer> mForbiddenTags = new HashSet<Integer>(); /** If greater than zero, this is the max number that mCaches * was allowed to contain when loaded. (This limit can change on subsequent loads) */ private int mCachesCappedToCount = 0; public CachesProviderDb(DbFrontend dbFrontend) { mDbFrontend = dbFrontend; } /** @param start is prepended if there are any parts */ /* private static String BuildConjunction(String start, List<String> parts) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (String part : parts) { if (first) { buffer.append(start); first = false; } else { buffer.append(" AND "); } buffer.append(part); } return buffer.toString(); } */ /** Returns a complete SQL query except from 'SELECT x' */ private String getSql() { if (mSql != null) return mSql; ArrayList<String> where = new ArrayList<String>(4); if (mHasLimits) { where.add("Latitude >= " + mLatLow + " AND Latitude < " + mLatHigh + " AND Longitude >= " + mLonLow + " AND Longitude < " + mLonHigh); } if (!mFilter.equals("")) where.add(mFilter); String join = ""; if (mForbiddenTags.size() > 0) { StringBuffer forbidden = new StringBuffer(); boolean first = true; for (Integer tagId : mForbiddenTags) { if (first) { first = false; } else { forbidden.append(" or "); } forbidden.append("TagId=" + tagId); } join = " left outer join (select CacheId from cachetags where " + forbidden + ") as FoundTags on caches.Id = FoundTags.CacheId"; where.add("FoundTags.CacheId is NULL"); } StringBuffer tables = new StringBuffer("FROM CACHES"); int ix = 1; for (Integer tagId : mRequiredTags) { String table = "tags" + ix; tables.append(", CACHETAGS " + table); where.add(table+".TagId=" + tagId + " AND " + table + ".CacheId=Id"); ix++; } StringBuffer completeSql = tables; //new StringBuffer(tables); completeSql.append(join); boolean first = true; for (String part : where) { if (first) { completeSql.append(" WHERE "); first = false; } else { completeSql.append(" AND "); } completeSql.append(part); } mSql = completeSql.toString(); //Log.d("GeoBeagle", "CachesProviderDb created sql " + mSql); return mSql; } @Override public AbstractList<Geocache> getCaches() { if (mCaches == null || mCachesCappedToCount > 0) { mCaches = mDbFrontend.loadCachesRaw("SELECT Id " + getSql()); } return mCaches; } @Override public AbstractList<Geocache> getCaches(int maxResults) { if (mCaches == null || (mCachesCappedToCount > 0 && mCachesCappedToCount < maxResults)) { mCaches = mDbFrontend.loadCachesRaw("SELECT Id " + getSql() + " LIMIT 0, " + maxResults); if (mCaches.size() == maxResults) mCachesCappedToCount = maxResults; else //The cap didn't limit the search result mCachesCappedToCount = 0; } return mCaches; } @Override public int getCount() { if (mCaches == null || mCachesCappedToCount > 0) { return mDbFrontend.countRaw("SELECT COUNT(*) " + getSql()); } return mCaches.size(); } @Override public void clearBounds() { if (!mHasLimits) return; mHasLimits = false; mCaches = null; //Flush old caches mSql = null; mHasChanged = true; } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { if (Util.approxEquals(latLow, mLatLow) && Util.approxEquals(latHigh, mLatHigh) && Util.approxEquals(lonLow, mLonLow) && Util.approxEquals(lonHigh, mLonHigh)) { return; } mLatLow = latLow; mLatHigh = latHigh; mLonLow = lonLow; mLonHigh = lonHigh; mCaches = null; //Flush old caches mSql = null; mHasChanged = true; mHasLimits = true; } @Override public boolean hasChanged() { return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } /** Tells this class that the contents in the database have changed. * The cached list isn't reliable any more. */ public void notifyOfDbChange() { mCaches = null; mHasChanged = true; } public void setFilter(CacheFilter cacheFilter) { String newFilter = cacheFilter.getSqlWhereClause(); Set<Integer> newTags = cacheFilter.getRequiredTags(); Set<Integer> newForbiddenTags = cacheFilter.getForbiddenTags(); if (newFilter.equals(mFilter) && newTags.equals(mRequiredTags) && newForbiddenTags.equals(mForbiddenTags)) return; mHasChanged = true; mFilter = newFilter; mRequiredTags = newTags; mForbiddenTags = newForbiddenTags; mSql = null; //Flush mCaches = null; //Flush old caches } public int getTotalCount() { return mDbFrontend.count(mFilter); } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.IPausable; import com.google.code.geobeagle.Refresher; import android.os.Handler; import android.util.Log; import java.util.AbstractList; /** Runs the decorated ICachesProviderCenter asynchronously. * setCenter() therefore takes an extra parameter. * * getCaches() and getCount() only returns pre-calculated data, * ensuring quick execution. * * hasChanged() will only return true when the thread has completed calculating * new (and differing) data. * * If a new center is set before the geocache list for the previous one finished * calculating, the calculation is finished and then the latest center is used * for a new calculation. */ public class CachesProviderCenterThread implements ICachesProvider, IPausable { private final ICachesProviderCenter mProvider; /** Only replaced from the extra thread */ private AbstractList<Geocache> mGeocaches = GeocacheListPrecomputed.EMPTY; private boolean mHasChanged = true; /** The coordinates for which mGeocaches is currently valid */ private double mCalculatedLatitude; private double mCalculatedLongitude; /** When current calculation is done, continue with these center coordinates */ private double mNextLatitude; private double mNextLongitude; private boolean mIsCalculating = false; private Thread mThread; /** Used to execute listener notification on the main thread */ private final Handler mHandler; private Refresher mObserver; private class CalculationThread extends Thread { private final double mLatitude; private final double mLongitude; public CalculationThread(double latitude, double longitude) { mLatitude = latitude; mLongitude = longitude; } @Override public void run() { Log.d("GeoBeagle", "Thread starting to calculate"); /* try { sleep(2000); } catch (InterruptedException e) { } Log.d("GeoBeagle", "Thread has slept for 2 sec"); */ mProvider.setCenter(mLatitude, mLongitude); AbstractList<Geocache> result = mProvider.getCaches(); if (result.equals(mGeocaches)) { Log.d("GeoBeagle", "Thread finished calculating: the list didn't change"); registerResult(mLatitude, mLongitude, mGeocaches, false); } else { Log.d("GeoBeagle", "Thread finished calculating: the list did change"); registerResult(mLatitude, mLongitude, result, true); } startCalculation(); } } /** Called by the extra thread to atomically update the state */ private synchronized void registerResult(double latitude, double longitude, AbstractList<Geocache> geocacheList, boolean changed) { mCalculatedLatitude = latitude; mCalculatedLongitude = longitude; mGeocaches = geocacheList; mIsCalculating = false; //Thread will die soon mThread = null; if (changed) { mHasChanged = true; mHandler.post(mObserverNotifier); } } public CachesProviderCenterThread(ICachesProviderCenter provider) { mProvider = provider; //Create here to assure that main thread gets to execute notifications: mHandler = new Handler(); } /** Start an asynchronous calculation and notify a refresher when the * list has changed (if it does change) */ public synchronized void setCenter(double latitude, double longitude, Refresher notifyAfter) { mNextLatitude = latitude; mNextLongitude = longitude; mObserver = notifyAfter; startCalculation(); } private synchronized void startCalculation() { if (mIsCalculating) return; //Will be started when current calculation finishes if (mIsPaused) return; if (mCalculatedLatitude == mNextLatitude && mCalculatedLongitude == mNextLongitude) { return; //No need to calculate again } Log.d("GeoBeagle", "startCalculation starts thread for coordinate diff latitude="+ (mNextLatitude-mCalculatedLatitude) + " longitude=" + (mNextLongitude-mCalculatedLongitude)); mIsCalculating = true; mThread = new CalculationThread(mNextLatitude, mNextLongitude); if (true) { //mThread.setPriority(); mThread.start(); } else { Log.d("GeoBeagle", "Running thread inline instead!"); mThread.run(); } } @Override public AbstractList<Geocache> getCaches() { //Don't calculate anything here -- just present previous results return mGeocaches; } @Override public int getCount() { //Don't calculate anything here -- just present previous results return mGeocaches.size(); } @Override public boolean hasChanged() { return mHasChanged; } @Override public synchronized void resetChanged() { mHasChanged = false; } //Run this on the main thread private final Runnable mObserverNotifier = new Runnable() { @Override public void run() { if (mObserver != null) mObserver.refresh(); } }; private boolean mIsPaused = false; public synchronized void onResume() { mIsPaused = false; startCalculation(); //There might be a pending update } public void onPause() { synchronized (this) { mIsPaused = true; mObserver = null; //Don't report any pending result } try { if (mThread != null) mThread.join(); } catch (InterruptedException e) { } } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import java.util.AbstractList; public class CachesProviderWaitForInit implements ICachesProviderCenter { private final ICachesProviderCenter mProvider; private boolean mInited = false; public CachesProviderWaitForInit(ICachesProviderCenter provider) { mProvider = provider; } @Override public void setCenter(double latitude, double longitude) { mInited = true; mProvider.setCenter(latitude, longitude); } @Override public AbstractList<Geocache> getCaches() { if (!mInited) return GeocacheListPrecomputed.EMPTY; return mProvider.getCaches(); } @Override public int getCount() { if (!mInited) { return 0; } return mProvider.getCount(); } //Could cause a bug if the first setCenter() doesn't make mProvider report hasChanged() @Override public boolean hasChanged() { if (!mInited) return false; return mProvider.hasChanged(); } @Override public void resetChanged() { if (mInited) { mProvider.resetChanged(); } } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.CacheType; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.main.Util; /** * @author sng */ public class CacheWriter { public static final String SQLS_CLEAR_EARLIER_LOADS[] = { Database.SQL_DELETE_OLD_CACHES, Database.SQL_DELETE_OLD_GPX, Database.SQL_RESET_DELETE_ME_CACHES, Database.SQL_RESET_DELETE_ME_GPX }; private final SourceNameTranslator mDbToGeocacheAdapter; private final ISQLiteDatabase mSqlite; private final GeocacheFactory mGeocacheFactory; private final DbFrontend mDbFrontend; CacheWriter(ISQLiteDatabase sqlite, DbFrontend dbFrontend, SourceNameTranslator dbToGeocacheAdapter, GeocacheFactory geocacheFactory) { mSqlite = sqlite; mDbToGeocacheAdapter = dbToGeocacheAdapter; mGeocacheFactory = geocacheFactory; mDbFrontend = dbFrontend; } public void clearCaches(String source) { mGeocacheFactory.flushCache(); mDbFrontend.flushTotalCount(); mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source); } /** * Deletes any cache/gpx entries marked delete_me, then marks all remaining * gpx-based caches, and gpx entries with delete_me = 1. */ public void clearEarlierLoads() { for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) { mSqlite.execSQL(sql); } } public void deleteCache(CharSequence id) { mGeocacheFactory.flushGeocache(id); mDbFrontend.flushTotalCount(); mSqlite.execSQL(Database.SQL_DELETE_CACHE, id); } /** Checks if the geocache is different from the previously existing one. * @return True if the geocache was updated in the database. */ public boolean conditionallyWriteCache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container) { Geocache geocache = mDbFrontend.loadCacheFromId(id.toString()); if (geocache != null && geocache.getName().equals(name) && Util.approxEquals(geocache.getLatitude(), latitude) && Util.approxEquals(geocache.getLongitude(), longitude) && geocache.getSourceType().equals(sourceType) && geocache.getSourceName().equals(sourceName) && geocache.getCacheType() == cacheType && geocache.getDifficulty() == difficulty && geocache.getTerrain() == terrain && geocache.getContainer() == container) return false; /* if (geocache != null) { if (!geocache.getName().equals(name)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of name"); if (!Util.approxEquals(geocache.getLatitude(), latitude)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of lat"); if (!Util.approxEquals(geocache.getLongitude(), longitude)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of long"); if (!geocache.getSourceType().equals(sourceType)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of sourceType"); if (!geocache.getSourceName().equals(sourceName)) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of sourceName"); if (geocache.getCacheType() != cacheType) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of type"); if (geocache.getDifficulty() != difficulty) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of diff"); if (geocache.getTerrain() != terrain) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of terrain"); if (geocache.getContainer() != container) Log.d("GeoBeagle", "CacheWriter updating "+id+" because of container"); } else { Log.d("GeoBeagle", "CacheWriter creating cache "+id); } */ insertAndUpdateCache(id, name, latitude, longitude, sourceType, sourceName, cacheType, difficulty, terrain, container); return true; } /** Unconditionally update the geocache in the database */ public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container) { mGeocacheFactory.flushGeocache(id); mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double( longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName), cacheType.toInt(), difficulty, terrain, container); } public void updateTag(CharSequence id, int tag, boolean set) { mDbFrontend.setGeocacheTag(id, tag, set); } public boolean isLockedFromUpdating(CharSequence id) { return mDbFrontend.geocacheHasTag(id, Tags.LOCKED_FROM_OVERWRITING); } /** * Return True if the gpx is already loaded. Mark this gpx and its caches in * the database to protect them from being nuked when the load is complete. * * @param gpxName * @param gpxTime * @return */ public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) { // TODO:countResults is slow; replace with a query, and moveToFirst. boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX, Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0; if (gpxAlreadyLoaded) { mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName); mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName); } return gpxAlreadyLoaded; } public void startWriting() { mSqlite.beginTransaction(); } public void stopWriting() { // TODO: abort if no writes--otherwise sqlite is unhappy. mSqlite.setTransactionSuccessful(); mSqlite.endTransaction(); } public void writeGpx(String gpxName, String pocketQueryExportTime) { mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime); } }
Java
package com.google.code.geobeagle.database; public interface ICachesProviderCenter extends ICachesProvider { public void setCenter(double latitude, double longitude); }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; public interface ICachesProviderArea extends ICachesProvider { void setBounds(double latLow, double lonLow, double latHigh, double lonHigh); /** @param maxResults If bigger than zero, the result may be limited to * this number if there is a performance gain. */ AbstractList<Geocache> getCaches(int maxResults); /** @return The number of caches returned if there aren't any bounds. */ int getTotalCount(); void clearBounds(); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; public class CachesProviderRadius implements ICachesProviderCenter { private ICachesProviderArea mCachesProviderArea; private double mLatitude; private double mLongitude; private double mDegrees; public CachesProviderRadius(ICachesProviderArea area) { mCachesProviderArea = area; } @Override public AbstractList<Geocache> getCaches() { return mCachesProviderArea.getCaches(); } @Override public int getCount() { return mCachesProviderArea.getCount(); } @Override public boolean hasChanged() { return mCachesProviderArea.hasChanged(); } @Override public void resetChanged() { mCachesProviderArea.resetChanged(); } public void setRadius(double radius) { mDegrees = radius; updateBounds(); } @Override public void setCenter(double latitude, double longitude) { mLatitude = latitude; mLongitude = longitude; updateBounds(); } private void updateBounds() { double latLow = mLatitude - mDegrees; double latHigh = mLatitude + mDegrees; double lonLow = mLongitude - mDegrees; double lonHigh = mLongitude + mDegrees; /* double lat_radians = Math.toRadians(mLatitude); double cos_lat = Math.cos(lat_radians); double lonLow = Math.max(-180, mLongitude - mDegrees / cos_lat); double lonHigh = Math.min(180, mLongitude + mDegrees / cos_lat); */ mCachesProviderArea.setBounds(latLow, lonLow, latHigh, lonHigh); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; public class DistanceAndBearing { public interface IDistanceAndBearingProvider { DistanceAndBearing getDistanceAndBearing(Geocache cache); } private Geocache mGeocache; private float mDistance; private float mBearing; public DistanceAndBearing(Geocache geocache, float distance, float bearing) { mGeocache = geocache; mDistance = distance; mBearing = bearing; } /** Which unit? */ public float getDistance() { return mDistance; } public float getBearing() { return mBearing; } public Geocache getGeocache() { return mGeocache; } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.main.GeoUtils; import java.util.AbstractList; /** Currently this class doesn't serve a purpose since the same functionality * is in GeoFixProviderLive. */ public class CachesProviderLazy implements ICachesProviderCenter { private final ICachesProviderCenter mProvider; /** The position mBufferedList reflects */ private double mBufferedLat; private double mBufferedLon; private AbstractList<Geocache> mBufferedList; /** The current center as asked for by the user of this object */ private double mLastLat; private double mLastLon; private long mLastUpdateTime; private boolean mHasChanged; private double mMinDistanceKm; private Clock mClock; private final long mMinTimeDiff; public CachesProviderLazy(ICachesProviderCenter provider, double minDistanceKm, long minTimeDiff, Clock clock) { mProvider = provider; mMinDistanceKm = minDistanceKm; mMinTimeDiff = minTimeDiff; mBufferedList = null; mClock = clock; } @Override public void setCenter(double latitude, double longitude) { mLastLat = latitude; mLastLon = longitude; if (mBufferedList == null) return; if (mClock.getCurrentTime() - mLastUpdateTime < mMinTimeDiff) return; if (GeoUtils.distanceKm(mBufferedLat, mBufferedLon, latitude, longitude) > mMinDistanceKm) { mProvider.setCenter(latitude, longitude); mBufferedList = null; } } @Override public AbstractList<Geocache> getCaches() { if (mBufferedList == null) { mBufferedList = mProvider.getCaches(); mProvider.resetChanged(); mLastUpdateTime = mClock.getCurrentTime(); } return mBufferedList; } @Override public int getCount() { return getCaches().size(); } @Override public boolean hasChanged() { if (mHasChanged) return true; //Update mHasChanged if (mClock.getCurrentTime() - mLastUpdateTime >= mMinTimeDiff) { if (GeoUtils.distanceKm(mBufferedLat, mBufferedLon, mLastLat, mLastLon) > mMinDistanceKm) mHasChanged = true; else mHasChanged = mProvider.hasChanged(); } return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.activity.main.Util; import com.google.code.geobeagle.database.DistanceAndBearing.IDistanceAndBearingProvider; import android.util.Log; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.WeakHashMap; /** Wraps another CachesProvider to make it sorted. Geocaches closer to * the provided center come first in the getCaches list. * Until setCenter has been called, the list will not be sorted. */ public class CachesProviderSorted implements ICachesProviderCenter, IDistanceAndBearingProvider { private final ICachesProvider mCachesProvider; private boolean mHasChanged = true; private double mLatitude; private double mLongitude; /** Value is null if the list needs to be re-sorted */ private AbstractList<Geocache> mSortedList = null; private DistanceComparator mDistanceComparator; private boolean isInitialized = false; private class DistanceComparator implements Comparator<Geocache> { public int compare(Geocache geocache1, Geocache geocache2) { final float d1 = getDistanceAndBearing(geocache1).getDistance(); final float d2 = getDistanceAndBearing(geocache2).getDistance(); if (d1 < d2) return -1; if (d1 > d2) return 1; return 0; } } public CachesProviderSorted(ICachesProvider cachesProvider) { mCachesProvider = cachesProvider; mDistanceComparator = new DistanceComparator(); isInitialized = false; } private WeakHashMap<Geocache, DistanceAndBearing> mDistances = new WeakHashMap<Geocache, DistanceAndBearing>(); public DistanceAndBearing getDistanceAndBearing(Geocache cache) { DistanceAndBearing d = mDistances.get(cache); if (d == null) { float distance = cache.getDistanceTo(mLatitude, mLongitude); float bearing = (float)GeoUtils.bearing(mLatitude, mLongitude, cache.getLatitude(), cache.getLongitude()); d = new DistanceAndBearing(cache, distance, bearing); mDistances.put(cache, d); } return d; } /** Updates mSortedList to a sorted version of the current underlying cache list*/ private void updateSortedList() { if (mSortedList != null && !mCachesProvider.hasChanged()) //No need to update return; final AbstractList<Geocache> unsortedList = mCachesProvider.getCaches(); ArrayList<Geocache> sortedList = new ArrayList<Geocache>(unsortedList); Collections.sort(sortedList, mDistanceComparator); mSortedList = new GeocacheListPrecomputed(sortedList); } @Override public AbstractList<Geocache> getCaches() { if (!isInitialized) { return mCachesProvider.getCaches(); } updateSortedList(); return mSortedList; } @Override public int getCount() { return mCachesProvider.getCount(); } @Override public boolean hasChanged() { return mHasChanged || mCachesProvider.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; if (mCachesProvider.hasChanged()) mSortedList = null; mCachesProvider.resetChanged(); } @Override public void setCenter(double latitude, double longitude) { if (isInitialized && Util.approxEquals(latitude, mLatitude) && Util.approxEquals(longitude, mLongitude)) return; //This only sets what position the caches are sorted against, //not which caches are selected for sorting! mLatitude = latitude; mLongitude = longitude; mHasChanged = true; isInitialized = true; mSortedList = null; mDistances.clear(); } public double getFurthestCacheDistance() { if (!isInitialized) { Log.e("GeoBeagle", "getFurthestCacheDistance called before setCenter"); return 0; } if (mSortedList == null || mCachesProvider.hasChanged()) { updateSortedList(); } if (mSortedList.size() == 0) return 0; return mSortedList.get(mSortedList.size()-1).getDistanceTo(mLatitude, mLongitude); } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; /** Interface to access a subset of the cache database. * Used to form a Decorator pattern. */ public interface ICachesProvider { /** Returns true if the result of getCaches() may have changed since the * last call to resetChanged() */ public boolean hasChanged(); /** Reset the change flag (never done from within the class) */ public void resetChanged(); public int getCount(); /** If the count is bigger than maxRelevantCount, the implementation may * return maxRelevantCount if that is more efficient. */ //public int getCount(int maxRelevantCount); /** The returned list is considered immutable */ public AbstractList<Geocache> getCaches(); }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; //TODO: Remove this class and replace by a mechanism to change CachesProvider in CacheListAdapter public class CachesProviderToggler implements ICachesProviderCenter { private ICachesProviderCenter mCachesProviderCenter; private ICachesProvider mCachesProviderAll; private boolean mNearest; private boolean mHasChanged; public CachesProviderToggler(ICachesProviderCenter cachesProviderCenter, ICachesProvider cachesProviderAll) { mCachesProviderCenter = cachesProviderCenter; mCachesProviderAll = cachesProviderAll; mNearest = true; mHasChanged = true; } public void toggle() { mNearest = !mNearest; mHasChanged = true; } public boolean isShowingNearest() { return mNearest; } @Override public AbstractList<Geocache> getCaches() { return (mNearest ? mCachesProviderCenter : mCachesProviderAll).getCaches(); } @Override public int getCount() { return (mNearest ? mCachesProviderCenter : mCachesProviderAll).getCount(); } @Override public void setCenter(double latitude, double longitude) { mCachesProviderCenter.setCenter(latitude, longitude); } @Override public boolean hasChanged() { return mHasChanged || (mNearest ? mCachesProviderCenter : mCachesProviderAll).hasChanged(); } @Override public void resetChanged() { mHasChanged = false; (mNearest ? mCachesProviderCenter : mCachesProviderAll).resetChanged(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Tags; import android.util.Log; public class OpenHelperDelegate { public void onCreate(ISQLiteDatabase db) { db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V11); db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10); db.execSQL(Database.SQL_CREATE_IDX_LATITUDE); db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE); db.execSQL(Database.SQL_CREATE_IDX_SOURCE); db.execSQL(Database.SQL_CREATE_CACHETAGS_TABLE_V12); db.execSQL(Database.SQL_CREATE_IDX_CACHETAGS); } public void onUpgrade(ISQLiteDatabase db, int oldVersion) { Log.i("GeoBeagle", "database onUpgrade oldVersion="+ oldVersion); if (oldVersion < 9) { db.execSQL(Database.SQL_DROP_CACHE_TABLE); db.execSQL(Database.SQL_CREATE_CACHE_TABLE_V08); db.execSQL(Database.SQL_CREATE_IDX_LATITUDE); db.execSQL(Database.SQL_CREATE_IDX_LONGITUDE); db.execSQL(Database.SQL_CREATE_IDX_SOURCE); } if (oldVersion < 10) { db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DELETE_ME); db.execSQL(Database.SQL_CREATE_GPX_TABLE_V10); } if (oldVersion < 11) { db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CACHE_TYPE); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_CONTAINER); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_DIFFICULTY); db.execSQL("ALTER TABLE CACHES ADD COLUMN " + Database.S0_COLUMN_TERRAIN); // This date has to precede 2000-01-01 (due to a bug in // CacheTagSqlWriter.java in v10). db.execSQL("UPDATE GPX SET ExportTime = \"1990-01-01\""); } if (oldVersion == 12) { db.execSQL("DROP TABLE IF EXISTS LABELS"); db.execSQL("DROP TABLE IF EXISTS CACHELABELS"); } if (oldVersion < 13) { Log.i("GeoBeagle", "Upgrading database to v13"); db.execSQL(Database.SQL_CREATE_TAGS_TABLE_V12); db.execSQL(Database.SQL_REPLACE_TAG, Tags.FOUND, "Found", true); db.execSQL(Database.SQL_REPLACE_TAG, Tags.DNF, "DNF", true); db.execSQL(Database.SQL_REPLACE_TAG, Tags.FAVORITES, "Favorites", true); db.execSQL(Database.SQL_CREATE_CACHETAGS_TABLE_V12); db.execSQL(Database.SQL_CREATE_IDX_CACHETAGS); } } }
Java
package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import android.util.Log; import java.util.AbstractList; /** * Finds the caches that are closest to a certain point. */ public class CachesProviderCount implements ICachesProviderCenter { private static final double MAX_RADIUS = 1; //180; /** Maximum number of times a search is allowed to call the underlying * CachesProvider before yielding a best-effort result */ public static final int MAX_ITERATIONS = 10; private static final float DISTANCE_MULTIPLIER = 1.8f; //1.414f; private ICachesProviderArea mCachesProviderArea; private CachesProviderRadius mCachesProviderRadius; /** The least acceptable number of caches */ private int mMinCount; /* The max acceptable number of caches */ private int mMaxCount; private double mRadius; private AbstractList<Geocache> mCaches; /** Number of caches within mRadius */ private int mCount; /** True if mCount has been calculated for the current values */ private boolean mIsCountValid; /** Used for hasChanged() / setChanged() */ private boolean mHasChanged = true; public CachesProviderCount(ICachesProviderArea area, int minCount, int maxCount) { mCachesProviderArea = area; mCachesProviderRadius = new CachesProviderRadius(area); mMinCount = minCount; mMaxCount = maxCount; mRadius = 0.04; mIsCountValid = false; } @Override public void setCenter(double latitude, double longitude) { mCachesProviderRadius.setCenter(latitude, longitude); } @Override public AbstractList<Geocache> getCaches() { if (mCachesProviderRadius.hasChanged()) { mCaches = null; mIsCountValid = false; //TODO: Is this test fast enough to be worth the effort? int total = mCachesProviderArea.getTotalCount(); if (total <= mMaxCount) { Log.d("GeoBeagle", "CachesProviderCount.getCaches: Total number is few enough"); mCachesProviderArea.clearBounds(); mCaches = mCachesProviderArea.getCaches(); mCount = total; mIsCountValid = true; mCachesProviderRadius.resetChanged(); return mCaches; } } if (mCaches != null) return mCaches; if (!mIsCountValid) { Clock clock = new Clock(); long start = clock.getCurrentTime(); findRadius(mRadius); Log.d("GeoBeagle", "CachesProviderCount calculated in " + (clock.getCurrentTime()-start) + " ms"); mIsCountValid = true; } mCachesProviderRadius.setRadius(mRadius); mCaches = mCachesProviderRadius.getCaches(); mCachesProviderRadius.resetChanged(); return mCaches; } @Override public int getCount() { if (!mIsCountValid || mCachesProviderRadius.hasChanged()) { findRadius(mRadius); mIsCountValid = true; mCachesProviderRadius.resetChanged(); } return mCount; } private int countHitsUsingRadius(double radius) { mCachesProviderRadius.setRadius(radius); return mCachesProviderRadius.getCount(); } /** * @param radiusToTry Starting radius (in degrees) in search * @return Radius setting that satisfy mMinCount <= count <= mMaxCount */ private void findRadius(double radiusToTry) { int count = countHitsUsingRadius(radiusToTry); int iterationsLeft = MAX_ITERATIONS - 1; Log.d("GeoBeagle", "CachesProviderCount first count = " + count); if (count > mMaxCount) { while (count > mMaxCount && iterationsLeft > 1) { radiusToTry /= DISTANCE_MULTIPLIER; count = countHitsUsingRadius(radiusToTry); iterationsLeft -= 1; Log.d("GeoBeagle", "CachesProviderCount search inward count = " + count); } } else if (count < mMinCount) { while (count < mMinCount && radiusToTry < MAX_RADIUS / DISTANCE_MULTIPLIER && iterationsLeft > 1) { radiusToTry *= DISTANCE_MULTIPLIER; count = countHitsUsingRadius(radiusToTry); iterationsLeft -= 1; Log.d("GeoBeagle", "CachesProviderCount search outward count = " + count); } } if (count < mMinCount && iterationsLeft > 0) { findWithinLimits(radiusToTry, radiusToTry * DISTANCE_MULTIPLIER, iterationsLeft); } else if (count > mMaxCount && iterationsLeft > 0) { findWithinLimits(radiusToTry / DISTANCE_MULTIPLIER, radiusToTry, iterationsLeft); } else { mCount = count; mRadius = radiusToTry; } } private void findWithinLimits(double minRadius, double maxRadius, int iterationsLeft) { double radiusToTry = (minRadius + maxRadius) / 2.0; int count = countHitsUsingRadius(radiusToTry); if (count <= mMaxCount && count >= mMinCount) { Log.d("GeoBeagle", "CachesProviderCount.findWithinLimits: Found count = " + count); mCount = count; mRadius = radiusToTry; return; } if (iterationsLeft <= 1) { Log.d("GeoBeagle", "CachesProviderCount.findWithinLimits: Giving up with count = " + count); mCount = count; mRadius = radiusToTry; return; } if (count > mMaxCount) { findWithinLimits(minRadius, radiusToTry, iterationsLeft - 1); return; } findWithinLimits(radiusToTry, maxRadius, iterationsLeft - 1); } @Override public boolean hasChanged() { return mHasChanged || mCachesProviderRadius.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; mCachesProviderRadius.resetChanged(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Geocache; import java.util.AbstractList; /** * Strategy to only invalidate/reload the list of caches when the bounds are * changed to outside the previous bounds. Also returns an empty list if the * count is greater than MAX_COUNT. */ public class CachesProviderLazyArea implements ICachesProviderArea { public static class CoordinateManager { private final double mExpandRatio; // The bounds of the loaded area private double mLatLow; private double mLatHigh; private double mLonLow; private double mLonHigh; public CoordinateManager(double expandRatio) { mExpandRatio = expandRatio; } boolean atLeastOneSideIsSmaller(double latLow, double lonLow, double latHigh, double lonHigh) { boolean fAtLeastOneSideIsSmaller = latLow < mLatLow || lonLow < mLonLow || latHigh > mLatHigh || lonHigh > mLonHigh; return fAtLeastOneSideIsSmaller; } boolean everySideIsBigger(double latLow, double lonLow, double latHigh, double lonHigh) { return latLow <= mLatLow && lonLow <= mLonLow && latHigh >= mLatHigh && lonHigh >= mLonHigh; } void expandCoordinates(double latLow, double lonLow, double latHigh, double lonHigh) { double latExpand = (latHigh - latLow) * mExpandRatio / 2.0; double lonExpand = (lonHigh - lonLow) * mExpandRatio / 2.0; mLatLow = latLow - latExpand; mLonLow = lonLow - lonExpand; mLatHigh = latHigh + latExpand; mLonHigh = lonHigh + lonExpand; } } /** Maximum number of caches to show */ public static final int MAX_COUNT = 1000; private final ICachesProviderArea mCachesProviderArea; private final CoordinateManager mCoordinateManager; /** If the user of this instance thinks the list has changed */ private boolean mHasChanged = true; private final PeggedCacheProvider mPeggedCacheProvider; public CachesProviderLazyArea(ICachesProviderArea cachesProviderArea, PeggedCacheProvider peggedCacheProvider, CoordinateManager coordinateManager) { mCachesProviderArea = cachesProviderArea; mPeggedCacheProvider = peggedCacheProvider; mCoordinateManager = coordinateManager; } @Override public void clearBounds() { mCachesProviderArea.clearBounds(); } @Override public AbstractList<Geocache> getCaches() { return getCaches(MAX_COUNT); } @Override public AbstractList<Geocache> getCaches(int maxCount) { // Reading one extra cache to see if there are too many AbstractList<Geocache> caches = mCachesProviderArea.getCaches(maxCount + 1); mCachesProviderArea.resetChanged(); return mPeggedCacheProvider.pegCaches(maxCount, caches); } public int getCount() { // Not perfectly efficient but it's not used anyway return getCaches().size(); } @Override public int getTotalCount() { return mCachesProviderArea.getTotalCount(); } @Override public boolean hasChanged() { return mHasChanged || mCachesProviderArea.hasChanged(); } @Override public void resetChanged() { mHasChanged = false; mCachesProviderArea.resetChanged(); } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { boolean tooManyCaches = mPeggedCacheProvider.isTooManyCaches(); if (tooManyCaches && mCoordinateManager.everySideIsBigger(latLow, lonLow, latHigh, lonHigh)) { // The new bounds are strictly bigger but the old ones // already contained too many caches return; } if (tooManyCaches || mCoordinateManager.atLeastOneSideIsSmaller(latLow, lonLow, latHigh, lonHigh)) { mCoordinateManager.expandCoordinates(latLow, lonLow, latHigh, lonHigh); mCachesProviderArea.setBounds(mCoordinateManager.mLatLow, mCoordinateManager.mLonLow, mCoordinateManager.mLatHigh, mCoordinateManager.mLonHigh); mHasChanged = true; } } public void showToastIfTooManyCaches() { mPeggedCacheProvider.showToastIfTooManyCaches(); } public boolean tooManyCaches() { return mPeggedCacheProvider.isTooManyCaches(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.GeocacheFactory.Source; public class SourceNameTranslator { public Source sourceNameToSourceType(String sourceName) { if (sourceName.equals("intent")) return Source.WEB_URL; else if (sourceName.equals("mylocation")) return Source.MY_LOCATION; else if (sourceName.toLowerCase().endsWith((".loc"))) return Source.LOC; return Source.GPX; } public String sourceTypeToSourceName(Source source, String sourceName) { if (source == Source.MY_LOCATION) return "mylocation"; else if (source == Source.WEB_URL) return "intent"; return sourceName; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.database; import com.google.code.geobeagle.Clock; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheFactory; import com.google.code.geobeagle.GeocacheListLazy; import com.google.code.geobeagle.GeocacheListPrecomputed; import com.google.code.geobeagle.Tags; import com.google.code.geobeagle.database.DatabaseDI.GeoBeagleSqliteOpenHelper; import com.google.code.geobeagle.database.DatabaseDI.SQLiteWrapper; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import java.util.AbstractList; import java.util.ArrayList; /** * Represents the front-end to access a database. It takes * responsibility to open and close the actual database connection without * involving the clients of this class. */ public class DbFrontend { private Context mContext; private GeoBeagleSqliteOpenHelper mOpenHelper; private boolean mIsDatabaseOpen; private CacheWriter mCacheWriter; private ISQLiteDatabase mDatabase; private final GeocacheFactory mGeocacheFactory; private final Clock mClock = new Clock(); /** The total number of geocaches and waypoints in the database. * -1 means not initialized */ private int mTotalCacheCount = -1; private SourceNameTranslator mSourceNameTranslator; private SQLiteWrapper mSqliteWrapper; private static final String[] READER_COLUMNS = new String[] { "Latitude", "Longitude", "Id", "Description", "Source", "CacheType", "Difficulty", "Terrain", "Container" }; public DbFrontend(Context context, GeocacheFactory geocacheFactory) { mContext = context; mIsDatabaseOpen = false; mGeocacheFactory = geocacheFactory; mSourceNameTranslator = new SourceNameTranslator(); } //TODO: Redesign the threads so synchronized isn't needed for database access public synchronized void openDatabase() { if (mIsDatabaseOpen) return; //Log.d("GeoBeagle", "DbFrontend.openDatabase()"); mIsDatabaseOpen = true; mOpenHelper = new GeoBeagleSqliteOpenHelper(mContext); final SQLiteDatabase sqDb = mOpenHelper.getReadableDatabase(); mDatabase = new DatabaseDI.SQLiteWrapper(sqDb); mSqliteWrapper = mOpenHelper.getWritableSqliteWrapper(); } public synchronized void closeDatabase() { if (!mIsDatabaseOpen) return; //Log.d("GeoBeagle", "DbFrontend.closeDatabase()"); mIsDatabaseOpen = false; mOpenHelper.close(); mCacheWriter = null; mDatabase = null; } public AbstractList<Geocache> loadCachesPrecomputed(String where) { return loadCachesPrecomputed(where, -1); } /** If 'where' is null, returns all caches * @param maxResults if <= 0, means no limit */ public AbstractList<Geocache> loadCachesPrecomputed(String where, int maxResults) { openDatabase(); String limit = null; if (maxResults > 0) { limit = "0, " + maxResults; } long start = mClock.getCurrentTime(); //CacheReaderCursor cursor = mCacheReader.open(where, limit); Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, READER_COLUMNS, where, null, null, null, limit); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Geocache> geocaches = new ArrayList<Geocache>(); do { Geocache geocache = mGeocacheFactory.fromCursor(cursor, mSourceNameTranslator); geocaches.add(geocache); } while (cursor.moveToNext()); cursor.close(); Log.d("GeoBeagle", "DbFrontend.loadCachesPrecomputed took " + (mClock.getCurrentTime()-start) + " ms (loaded " + geocaches.size() + " caches)"); return new GeocacheListPrecomputed(geocaches); } /** If 'where' is null, returns all caches */ public AbstractList<Geocache> loadCaches(String where) { return loadCaches(where, -1); } /** If 'where' is null, returns all caches. * Loads the caches when first used, not from this method. * @param maxResults if <= 0, means no limit */ public AbstractList<Geocache> loadCaches(String where, int maxResults) { openDatabase(); String limit = null; if (maxResults > 0) { limit = "0, " + maxResults; } long start = mClock.getCurrentTime(); final String fields[] = { "Id" }; Cursor cursor = mDatabase.query(Database.TBL_CACHES, fields, where, null, null, null, limit); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Object> idList = new ArrayList<Object>(); if (cursor != null) { do { idList.add(cursor.getString(0)); } while (cursor.moveToNext()); cursor.close(); } Log.d("GeoBeagle", "DbFrontend.loadCachesLazy took " + (mClock.getCurrentTime()-start) + " ms (loaded " + idList.size() + " caches)"); return new GeocacheListLazy(this, idList); } /** @param sqlQuery A complete SQL query to be executed. * The query must return the id's of geocaches. */ public AbstractList<Geocache> loadCachesRaw(String sqlQuery) { openDatabase(); long start = mClock.getCurrentTime(); Cursor cursor = mDatabase.rawQuery(sqlQuery, new String[]{} ); if (!cursor.moveToFirst()) { cursor.close(); return GeocacheListPrecomputed.EMPTY; } ArrayList<Object> idList = new ArrayList<Object>(); do { idList.add(cursor.getString(0)); } while (cursor.moveToNext()); cursor.close(); Log.d("GeoBeagle", "DbFrontend.loadCachesRaw took " + (mClock.getCurrentTime()-start) + " ms to load " + idList.size() + " caches from query " + sqlQuery); return new GeocacheListLazy(this, idList); } /** @return null if the cache id is not in the database */ public Geocache loadCacheFromId(String id) { Geocache loadedGeocache = mGeocacheFactory.getFromId(id); if (loadedGeocache != null) { return loadedGeocache; } openDatabase(); Cursor cursor = mSqliteWrapper.query(Database.TBL_CACHES, READER_COLUMNS, "Id='"+id+"'", null, null, null, null); if (!cursor.moveToFirst()) { cursor.close(); return null; } Geocache geocache = mGeocacheFactory.fromCursor(cursor, mSourceNameTranslator); cursor.close(); return geocache; } public CacheWriter getCacheWriter() { if (mCacheWriter != null) return mCacheWriter; openDatabase(); mCacheWriter = DatabaseDI.createCacheWriter(mDatabase, mGeocacheFactory, this); return mCacheWriter; } private int countAll() { if (mTotalCacheCount != -1) return mTotalCacheCount; openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor; countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES, null); countCursor.moveToFirst(); mTotalCacheCount = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.countAll took " + (mClock.getCurrentTime()-start) + " ms (" + mTotalCacheCount + " caches)"); return mTotalCacheCount; } /** If 'where' is empty, returns the total number of caches */ public int count(String where) { if (where == null || where.equals("")) return countAll(); openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHES + " WHERE " + where, null); countCursor.moveToFirst(); int count = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.count took " + (mClock.getCurrentTime()-start) + " ms (" + count + " caches)"); return count; } /** 'sql' must be a complete SQL query that returns a single row * with the result in the first column */ public int countRaw(String sql) { openDatabase(); long start = mClock.getCurrentTime(); Cursor countCursor = mDatabase.rawQuery(sql, null); countCursor.moveToFirst(); int count = countCursor.getInt(0); countCursor.close(); Log.d("GeoBeagle", "DbFrontend.countRaw took " + (mClock.getCurrentTime()-start) + " ms (" + count + " caches)"); return count; } public void flushTotalCount() { mTotalCacheCount = -1; } public boolean geocacheHasTag(CharSequence geocacheId, int tagId) { if (geocacheId == null) //Work-around for unexplained crash return false; openDatabase(); if (mDatabase == null) { //TODO: Remove. This only occurs when there's a //thread interleaving bug which seems to be fixed. Log.e("GeoBeagle", "DbFrontend.geocacheHasTag: mDatabase=null"); return false; } Cursor cursor = mDatabase.rawQuery("SELECT COUNT(*) FROM " + Database.TBL_CACHETAGS + " WHERE CacheId='" + geocacheId + "' AND TagId=" + tagId, null); if (cursor == null) { return false; } cursor.moveToFirst(); int count = cursor.getInt(0); cursor.close(); return (count > 0); } /** Sets or clear a tag for a geocache */ public void setGeocacheTag(CharSequence geocacheId, int tagId, boolean set) { openDatabase(); //Log.d("GeoBeagle", "setGeocacheTag(" + geocacheId + ", " + tagId // + ", " + (set?"true":"false")+ ")"); if (set) mSqliteWrapper.execSQL(Database.SQL_REPLACE_CACHETAG, geocacheId, tagId); else mSqliteWrapper.execSQL(Database.SQL_DELETE_CACHETAG, geocacheId, tagId); } public void clearTagForAllCaches(int tag) { openDatabase(); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_TAGS, tag); mGeocacheFactory.flushCacheIcons(); //The ones with 'tag' would be enough } public void deleteAll() { Log.i("GeoBeagle", "DbFrontend.deleteAll()"); clearTagForAllCaches(Tags.LOCKED_FROM_OVERWRITING); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_CACHES); mSqliteWrapper.execSQL(Database.SQL_DELETE_ALL_GPX); mGeocacheFactory.flushCache(); mTotalCacheCount = 0; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.code.geobeagle.database.DbFrontend; import java.util.AbstractList; import java.util.ArrayList; import java.util.Iterator; /** Fetch the geocaches from the database (or previously loaded instance) * when first needed */ public class GeocacheListLazy extends AbstractList<Geocache> { /** Elements are either String (cacheId) or Geocache */ private final ArrayList<Object> mList; private final DbFrontend mDbFrontend; public GeocacheListLazy() { mList = new ArrayList<Object>(); mDbFrontend = null; } /** @param initialList The list of cacheIds (Strings) to load */ public GeocacheListLazy(DbFrontend dbFrontend, ArrayList<Object> initialList) { mDbFrontend = dbFrontend; mList = initialList; } public boolean equals(GeocacheListLazy otherList) { if (otherList == this || otherList.mList == mList) return true; if (mList.size() != otherList.mList.size()) return false; for (int i = 0; i < mList.size(); i++) { if (mList.get(i) == otherList.mList.get(i)) continue; Object obj = mList.get(i); Object obj2 = otherList.mList.get(i); CharSequence id1; if (obj instanceof Geocache) { id1 = ((Geocache)obj).getId(); } else { id1 = (CharSequence)obj; } CharSequence id2; if (obj2 instanceof Geocache) { id2 = ((Geocache)obj2).getId(); } else { id2 = (CharSequence)obj2; } if (!id1.equals(id2)) return false; } return true; } private class LazyIterator implements Iterator<Geocache> { private int nextIx = 0; @Override public boolean hasNext() { return mList.size() > nextIx; } @Override public Geocache next() { Geocache cache = get(nextIx); nextIx++; return cache; } @Override public void remove() { //GeocacheLists are immutable throw new UnsupportedOperationException(); } } @Override public Iterator<Geocache> iterator() { return new LazyIterator(); } @Override public int size() { return mList.size(); } public Geocache get(int position) { Object nextObj = mList.get(position); if (nextObj instanceof String) { Geocache cache = mDbFrontend.loadCacheFromId((String)nextObj); mList.set(position, cache); return cache; } return (Geocache)nextObj; } }
Java
package com.google.code.geobeagle; import android.app.Activity; import android.content.SharedPreferences; import java.util.HashSet; import java.util.Set; //TODO: Allow filtering on Source /** * A CacheFilter determines which of all geocaches that should be * visible in the list and map views. * It can be translated into a SQL constraint for accessing the database. */ public class CacheFilter { private final Activity mActivity; /** The name of this filter as visible to the user */ private String mName; /** The string used in Preferences to identify this filter */ public final String mId; /** The name of this filter as visible to the user */ public String getName() { return mName; } public static interface FilterGui { public boolean getBoolean(int id); public String getString(int id); public void setBoolean(int id, boolean value); public void setString(int id, String value); } private static class BooleanOption { public final String PrefsName; public final String SqlClause; public boolean Selected; public int ViewResource; public BooleanOption(String prefsName, String sqlClause, int viewResource) { PrefsName = prefsName; SqlClause = sqlClause; Selected = true; ViewResource = viewResource; } } private final BooleanOption[] mTypeOptions = { new BooleanOption("Traditional", "CacheType = 1", R.id.ToggleButtonTrad), new BooleanOption("Multi", "CacheType = 2", R.id.ToggleButtonMulti), new BooleanOption("Unknown", "CacheType = 3", R.id.ToggleButtonMystery), new BooleanOption("MyLocation", "CacheType = 4", R.id.ToggleButtonMyLocation), new BooleanOption("Others", "CacheType = 0 OR (CacheType >= 5 AND CacheType <= 14)", R.id.ToggleButtonOthers), new BooleanOption("Waypoints", "(CacheType >= 20 AND CacheType <= 25)", R.id.ToggleButtonWaypoints), }; //These SQL are to be applied when the option is deselected! private final BooleanOption[] mSizeOptions = { new BooleanOption("Micro", "Container != 1", R.id.ToggleButtonMicro), new BooleanOption("Small", "Container != 2", R.id.ToggleButtonSmall), new BooleanOption("UnknownSize", "Container != 0", R.id.ToggleButtonUnknownSize), }; private String mFilterString; private static final Set<Integer> EMPTY_SET = new HashSet<Integer>(); /** Limits the filter to only include geocaches with this tag. * Zero means no limit. */ private Set<Integer> mRequiredTags = EMPTY_SET; /** Caches with this tag are not included in the results no matter what. * Zero means no restriction. */ private Set<Integer> mForbiddenTags = EMPTY_SET; public CacheFilter(String id, Activity activity) { mId = id; mActivity = activity; SharedPreferences preferences = mActivity.getSharedPreferences(mId, 0); loadFromPreferences(preferences); } public CacheFilter(String id, Activity activity, SharedPreferences sharedPreferences) { mId = id; mActivity = activity; loadFromPreferences(sharedPreferences); } /** * Load the values from SharedPreferences. * @return true if any value in the filter was changed */ private void loadFromPreferences(SharedPreferences preferences) { for (BooleanOption option : mTypeOptions) { option.Selected = preferences.getBoolean(option.PrefsName, true); } for (BooleanOption option : mSizeOptions) { option.Selected = preferences.getBoolean(option.PrefsName, true); } mFilterString = preferences.getString("FilterString", null); String required = preferences.getString("FilterTags", ""); mRequiredTags = StringToIntegerSet(required); String forbidden = preferences.getString("FilterForbiddenTags", ""); mForbiddenTags = StringToIntegerSet(forbidden); mName = preferences.getString("FilterName", "Unnamed"); } public void saveToPreferences() { SharedPreferences preferences = mActivity.getSharedPreferences(mId, 0); SharedPreferences.Editor editor = preferences.edit(); for (BooleanOption option : mTypeOptions) { editor.putBoolean(option.PrefsName, option.Selected); } for (BooleanOption option : mSizeOptions) { editor.putBoolean(option.PrefsName, option.Selected); } editor.putString("FilterString", mFilterString); editor.putString("FilterTags", SetToString(mRequiredTags)); editor.putString("FilterForbiddenTags", SetToString(mForbiddenTags)); editor.putString("FilterName", mName); editor.commit(); } private static String SetToString(Set<Integer> set) { StringBuffer buffer = new StringBuffer(); boolean first = true; for (int i : set) { if (first) first = false; else buffer.append(' '); buffer.append(i); } return buffer.toString(); } private static Set<Integer> StringToIntegerSet(String string) { if (string.equals("")) return EMPTY_SET; Set<Integer> set = new HashSet<Integer>(); String[] parts = string.split(" "); for (String part : parts) { set.add(Integer.decode(part)); } return set; } /** @return A number of conditions separated by AND, * or an empty string if there isn't any limit */ public String getSqlWhereClause() { int count = 0; for (BooleanOption option : mTypeOptions) { if (option.Selected) count++; } StringBuilder result = new StringBuilder(); boolean isFirst = true; if (count != mTypeOptions.length && count != 0) { for (BooleanOption option : mTypeOptions) { if (!option.Selected) continue; if (isFirst) { result.append("("); isFirst = false; } else { result.append(" OR "); } result.append(option.SqlClause); } result.append(")"); } if (mFilterString != null && !mFilterString.equals("")) { if (isFirst) { isFirst = false; } else { result.append(" AND "); } if (containsUppercase(mFilterString)) { //Do case-sensitive query result.append("(Id LIKE '%" + mFilterString + "%' OR Description LIKE '%" + mFilterString + "%')"); } else { //Do case-insensitive search result.append("(lower(Id) LIKE '%" + mFilterString + "%' OR lower(Description) LIKE '%" + mFilterString + "%')"); } } for (BooleanOption option : mSizeOptions) { if (!option.Selected) { if (isFirst) { isFirst = false; } else { result.append(" AND "); } result.append(option.SqlClause); } } return result.toString(); } public Set<Integer> getRequiredTags() { return mRequiredTags; } private static boolean containsUppercase(String string) { return !string.equals(string.toLowerCase()); } public void loadFromGui(FilterGui provider) { String newName = provider.getString(R.id.NameOfFilter); if (!newName.trim().equals("")) { mName = newName; } for (BooleanOption option : mTypeOptions) { option.Selected = provider.getBoolean(option.ViewResource); } for (BooleanOption option : mSizeOptions) { option.Selected = provider.getBoolean(option.ViewResource); } mFilterString = provider.getString(R.id.FilterString); mRequiredTags = new HashSet<Integer>(); mForbiddenTags = new HashSet<Integer>(); if (provider.getBoolean(R.id.CheckBoxRequireFavorites)) mRequiredTags.add(Tags.FAVORITES); else if (provider.getBoolean(R.id.CheckBoxForbidFavorites)) mForbiddenTags.add(Tags.FAVORITES); if (provider.getBoolean(R.id.CheckBoxRequireFound)) mRequiredTags.add(Tags.FOUND); else if (provider.getBoolean(R.id.CheckBoxForbidFound)) mForbiddenTags.add(Tags.FOUND); if (provider.getBoolean(R.id.CheckBoxRequireDNF)) mRequiredTags.add(Tags.DNF); else if (provider.getBoolean(R.id.CheckBoxForbidDNF)) mForbiddenTags.add(Tags.DNF); } /** Set up the view from the values in this CacheFilter. */ public void pushToGui(FilterGui provider) { provider.setString(R.id.NameOfFilter, mName); for (BooleanOption option : mTypeOptions) { provider.setBoolean(option.ViewResource, option.Selected); } for (BooleanOption option : mSizeOptions) { provider.setBoolean(option.ViewResource, option.Selected); } String filter = mFilterString == null ? "" : mFilterString; provider.setString(R.id.FilterString, filter); provider.setBoolean(R.id.CheckBoxRequireFavorites, mRequiredTags.contains(Tags.FAVORITES)); provider.setBoolean(R.id.CheckBoxForbidFavorites, mForbiddenTags.contains(Tags.FAVORITES)); provider.setBoolean(R.id.CheckBoxRequireFound, mRequiredTags.contains(Tags.FOUND)); provider.setBoolean(R.id.CheckBoxForbidFound, mForbiddenTags.contains(Tags.FOUND)); provider.setBoolean(R.id.CheckBoxRequireDNF, mRequiredTags.contains(Tags.DNF)); provider.setBoolean(R.id.CheckBoxForbidDNF, mForbiddenTags.contains(Tags.DNF)); } public Set<Integer> getForbiddenTags() { return mForbiddenTags; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle; import com.google.android.maps.GeoPoint; import com.google.code.geobeagle.GeocacheFactory.Provider; import com.google.code.geobeagle.GeocacheFactory.Source; import com.google.code.geobeagle.activity.main.GeoUtils; import com.google.code.geobeagle.database.CacheWriter; import com.google.code.geobeagle.database.DbFrontend; import android.content.res.Resources; import android.graphics.drawable.Drawable; import android.util.FloatMath; /** * Geocache or letterbox description, id, and coordinates. */ public class Geocache { static interface AttributeFormatter { CharSequence formatAttributes(int difficulty, int terrain); } static class AttributeFormatterImpl implements AttributeFormatter { public CharSequence formatAttributes(int difficulty, int terrain) { return (difficulty / 2.0) + " / " + (terrain / 2.0); } } static class AttributeFormatterNull implements AttributeFormatter { public CharSequence formatAttributes(int difficulty, int terrain) { return ""; } } public static final String CACHE_TYPE = "cacheType"; public static final String CONTAINER = "container"; public static final String DIFFICULTY = "difficulty"; public static final String ID = "id"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String NAME = "name"; public static final String SOURCE_NAME = "sourceName"; public static final String SOURCE_TYPE = "sourceType"; public static final String TERRAIN = "terrain"; private final AttributeFormatter mAttributeFormatter; private final CacheType mCacheType; private final int mContainer; /** Difficulty rating * 2 (difficulty=1.5 => mDifficulty=3) */ private final int mDifficulty; private GeoPoint mGeoPoint; private final CharSequence mId; private final double mLatitude; private final double mLongitude; private final CharSequence mName; private final String mSourceName; private final Source mSourceType; private final int mTerrain; private Drawable mIcon = null; //private Drawable mIconBig = null; private Drawable mIconMap = null; public Geocache(CharSequence id, CharSequence name, double latitude, double longitude, Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain, int container, AttributeFormatter attributeFormatter) { mId = id; mName = name; mLatitude = latitude; mLongitude = longitude; mSourceType = sourceType; mSourceName = sourceName; mCacheType = cacheType; mDifficulty = difficulty; mTerrain = terrain; mContainer = container; mAttributeFormatter = attributeFormatter; } /* public float[] calculateDistanceAndBearing(Location here) { if (here != null) { Location.distanceBetween(here.getLatitude(), here.getLongitude(), getLatitude(), getLongitude(), mDistanceAndBearing); return mDistanceAndBearing; } mDistanceAndBearing[0] = -1; mDistanceAndBearing[1] = -1; return mDistanceAndBearing; } */ public int describeContents() { return 0; } public CacheType getCacheType() { return mCacheType; } public int getContainer() { return mContainer; } public Drawable getIcon(Resources resources, GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) { if (mIcon == null) { Drawable overlayIcon = null; if (dbFrontend.geocacheHasTag(getId(), Tags.MINE)) overlayIcon = resources.getDrawable(R.drawable.overlay_mine_cacheview); else if (dbFrontend.geocacheHasTag(getId(), Tags.FOUND)) overlayIcon = resources.getDrawable(R.drawable.overlay_found_cacheview); else if (dbFrontend.geocacheHasTag(getId(), Tags.DNF)) overlayIcon = resources.getDrawable(R.drawable.overlay_dnf_cacheview); // else if (dbFrontend.geocacheHasTag(getId(), Tags.NEW)) // overlayIcon = resources.getDrawable(R.drawable.overlay_new_cacheview); mIcon = graphicsGenerator.createIconListView(this, overlayIcon, resources); } return mIcon; } public Drawable getIconMap(Resources resources, GraphicsGenerator graphicsGenerator, DbFrontend dbFrontend) { if (mIconMap == null) { Drawable overlayIcon = null; if (dbFrontend.geocacheHasTag(getId(), Tags.MINE)) overlayIcon = resources.getDrawable(R.drawable.overlay_mine); else if (dbFrontend.geocacheHasTag(getId(), Tags.FOUND)) overlayIcon = resources.getDrawable(R.drawable.overlay_found); else if (dbFrontend.geocacheHasTag(getId(), Tags.DNF)) overlayIcon = resources.getDrawable(R.drawable.overlay_dnf); else if (dbFrontend.geocacheHasTag(getId(), Tags.NEW)) overlayIcon = resources.getDrawable(R.drawable.overlay_new); mIconMap = graphicsGenerator.createIconMapView(this, overlayIcon, resources); } return mIconMap; } public GeocacheFactory.Provider getContentProvider() { // Must use toString() rather than mId.subSequence(0,2).equals("GC"), // because editing the text in android produces a SpannableString rather // than a String, so the CharSequences won't be equal. String prefix = mId.subSequence(0, 2).toString(); for (Provider provider : GeocacheFactory.ALL_PROVIDERS) { if (prefix.equals(provider.getPrefix())) return provider; } return Provider.GROUNDSPEAK; } public int getDifficulty() { return mDifficulty; } //Formerly calculateDistanceFast public float getDistanceTo(double latitude, double longitude) { double dLat = Math.toRadians(latitude - mLatitude); double dLon = Math.toRadians(longitude - mLongitude); final float sinDLat = FloatMath.sin((float)(dLat / 2)); final float sinDLon = FloatMath.sin((float)(dLon / 2)); float a = sinDLat * sinDLat + FloatMath.cos((float)Math.toRadians(mLatitude)) * FloatMath.cos((float)Math.toRadians(latitude)) * sinDLon * sinDLon; float c = (float)(2 * Math.atan2(FloatMath.sqrt(a), FloatMath.sqrt(1 - a))); return 6371000 * c; } public CharSequence getFormattedAttributes() { return mAttributeFormatter.formatAttributes(mDifficulty, mTerrain); } public GeoPoint getGeoPoint() { if (mGeoPoint == null) { int latE6 = (int)(mLatitude * GeoUtils.MILLION); int lonE6 = (int)(mLongitude * GeoUtils.MILLION); mGeoPoint = new GeoPoint(latE6, lonE6); } return mGeoPoint; } public CharSequence getId() { return mId; } public CharSequence getIdAndName() { if (mId.length() == 0) return mName; else if (mName.length() == 0) return mId; else return mId + ": " + mName; } public double getLatitude() { return mLatitude; } public double getLongitude() { return mLongitude; } public CharSequence getName() { return mName; } public CharSequence getShortId() { if (mId.length() > 2) return mId.subSequence(2, mId.length()); return ""; } public String getSourceName() { return mSourceName; } public Source getSourceType() { return mSourceType; } public int getTerrain() { return mTerrain; } /** @return true if the database needed to be updated */ public boolean saveToDbIfNeeded(DbFrontend dbFrontend) { CacheWriter cacheWriter = dbFrontend.getCacheWriter(); cacheWriter.startWriting(); boolean changed = cacheWriter.conditionallyWriteCache(getId(), getName(), getLatitude(), getLongitude(), getSourceType(), getSourceName(), getCacheType(), getDifficulty(), getTerrain(), getContainer()); cacheWriter.stopWriting(); return changed; } public void saveToDb(DbFrontend dbFrontend) { CacheWriter cacheWriter = dbFrontend.getCacheWriter(); cacheWriter.startWriting(); cacheWriter.insertAndUpdateCache(getId(), getName(), getLatitude(), getLongitude(), getSourceType(), getSourceName(), getCacheType(), getDifficulty(), getTerrain(), getContainer()); cacheWriter.stopWriting(); } /** The icons will be recalculated the next time they are needed. */ public void flushIcons() { mIcon = null; mIconMap = null; } }
Java
package com.google.code.geobeagle.formatting; public class DistanceFormatterImperial implements DistanceFormatter { public CharSequence formatDistance(float distance) { if (distance == -1) { return ""; } final float miles = distance / 1609.344f; if (miles > 0.1) return String.format("%1$1.2fmi", miles); final int feet= (int)(miles * 5280); return String.format("%1$1dft", feet); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.formatting; public interface DistanceFormatter { public abstract CharSequence formatDistance(float distance); }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.formatting; public class DistanceFormatterMetric implements DistanceFormatter { public CharSequence formatDistance(float distance) { if (distance == -1) { return ""; } if (distance >= 1000) { return String.format("%1$1.2fkm", distance / 1000.0); } return String.format("%1$dm", (int)distance); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import com.google.code.geobeagle.R; import android.app.Activity; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class CacheDetailsLoader { static interface Details { String getString(); } static class DetailsError implements Details { private final Activity mActivity; private final String mPath; private final int mResourceId; DetailsError(Activity activity, int resourceId, String path) { mActivity = activity; mResourceId = resourceId; mPath = path; } public String getString() { return mActivity.getString(mResourceId, mPath); } } static class DetailsImpl implements Details { private final byte[] mBuffer; DetailsImpl(byte[] buffer) { mBuffer = buffer; } public String getString() { return new String(mBuffer); } } public static class DetailsOpener { private final Activity mActivity; public DetailsOpener(Activity activity) { mActivity = activity; } DetailsReader open(File file) { FileInputStream fileInputStream; String absolutePath = file.getAbsolutePath(); try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { return new DetailsReaderFileNotFound(mActivity, e.getMessage()); } byte[] buffer = new byte[(int)file.length()]; return new DetailsReaderImpl(mActivity, absolutePath, fileInputStream, buffer); } } interface DetailsReader { Details read(); } static class DetailsReaderFileNotFound implements DetailsReader { private final Activity mActivity; private final String mPath; DetailsReaderFileNotFound(Activity activity, String path) { mActivity = activity; mPath = path; } public Details read() { return new DetailsError(mActivity, R.string.error_opening_details_file, mPath); } } static class DetailsReaderImpl implements DetailsReader { private final Activity mActivity; private final byte[] mBuffer; private final FileInputStream mFileInputStream; private final String mPath; DetailsReaderImpl(Activity activity, String path, FileInputStream fileInputStream, byte[] buffer) { mActivity = activity; mFileInputStream = fileInputStream; mPath = path; mBuffer = buffer; } public Details read() { try { mFileInputStream.read(mBuffer); mFileInputStream.close(); return new DetailsImpl(mBuffer); } catch (IOException e) { return new DetailsError(mActivity, R.string.error_reading_details_file, mPath); } } } public static final String DETAILS_DIR = "/sdcard/GeoBeagle/"; private final DetailsOpener mDetailsOpener; public CacheDetailsLoader(DetailsOpener detailsOpener) { mDetailsOpener = detailsOpener; } public String load(CharSequence cacheId) { final String sanitized = CacheDetailsWriter.replaceIllegalFileChars(cacheId.toString()); String path = DETAILS_DIR + sanitized + ".html"; File file = new File(path); DetailsReader detailsReader = mDetailsOpener.open(file); Details details = detailsReader.read(); return details.getString(); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import java.io.IOException; public class HtmlWriter { private final WriterWrapper mWriter; public HtmlWriter(WriterWrapper writerWrapper) { mWriter = writerWrapper; } public void close() throws IOException { mWriter.close(); } public void open(String path) throws IOException { mWriter.open(path); } public void write(String text) throws IOException { mWriter.write(text + "<br/>\n"); } public void writeFooter() throws IOException { mWriter.write(" </body>\n"); mWriter.write("</html>\n"); } public void writeHeader() throws IOException { mWriter.write("<html>\n"); mWriter.write(" <body>\n"); } public void writeSeparator() throws IOException { mWriter.write("<hr/>\n"); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.cachedetails; import java.io.IOException; public class CacheDetailsWriter { public static final String GEOBEAGLE_DIR = "/sdcard/GeoBeagle"; private final HtmlWriter mHtmlWriter; private String mLatitude; private String mLongitude; public CacheDetailsWriter(HtmlWriter htmlWriter) { mHtmlWriter = htmlWriter; } public void close() throws IOException { mHtmlWriter.writeFooter(); mHtmlWriter.close(); } public void latitudeLongitude(String latitude, String longitude) { mLatitude = latitude; mLongitude = longitude; } public void open(String wpt) throws IOException { final String sanitized = replaceIllegalFileChars(wpt); mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + sanitized + ".html"); } public static String replaceIllegalFileChars(String wpt) { return wpt.replaceAll("[<\\\\/:\\*\\?\">| \\t]", "_"); } public void writeHint(String text) throws IOException { mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>"); } public void writeLine(String text) throws IOException { mHtmlWriter.write(text); } public void writeLogDate(String text) throws IOException { mHtmlWriter.writeSeparator(); mHtmlWriter.write(text); } public void writeWptName(String wpt) throws IOException { mHtmlWriter.writeHeader(); mHtmlWriter.write(wpt); mHtmlWriter.write(mLatitude + ", " + mLongitude); mLatitude = mLongitude = null; } }
Java
package com.google.code.geobeagle; /** Allow objects that need to be paused/resumed to be sent as parameters * without requiring their specific type to be exposed. */ public interface IPausable { void onPause(); void onResume(); }
Java
package com.google.code.geobeagle; import java.util.HashMap; import java.util.Map; public class Tags { /** This id must never occur in the database */ public final static int NULL = 0; public final static int FOUND = 1; public final static int DNF = 2; public final static int FAVORITES = 3; //TODO: Rename to FAVORITE //These attributes are actually not related to the specific user public final static int UNAVAILABLE = 4; public final static int ARCHIVED = 5; /** The cache is newly added */ public final static int NEW = 6; /** The user placed this cache */ public final static int MINE = 7; /** No logs for this cache */ public final static int FOUND_BY_NOONE = 8; /** Indicates that the user has edited the cache. * Don't overwrite when importing a newer GPX. */ public final static int LOCKED_FROM_OVERWRITING = 9; //This method will be refactored into a more elegant solution public static Map<Integer, String> GetAllTags() { HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(FOUND, "Found"); map.put(DNF, "Did Not Find"); map.put(FAVORITES, "Favorite"); map.put(NEW, "New"); map.put(MINE, "Mine"); map.put(UNAVAILABLE, "Unavailable"); map.put(LOCKED_FROM_OVERWRITING, "Locked from overwriting"); return map; } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ** See the License for the specific language governing permissions and ** limitations under the License. */ package com.google.code.geobeagle.test; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.MenuItem; import android.view.SubMenu; import android.view.ContextMenu.ContextMenuInfo; class MenuActionStub implements MenuItem { @Override public char getAlphabeticShortcut() { return 0; } @Override public int getGroupId() { return 0; } @Override public Drawable getIcon() { return null; } @Override public Intent getIntent() { return null; } @Override public int getItemId() { return 7; } @Override public ContextMenuInfo getMenuInfo() { return null; } @Override public char getNumericShortcut() { return 0; } @Override public int getOrder() { return 0; } @Override public SubMenu getSubMenu() { return null; } @Override public CharSequence getTitle() { return null; } @Override public CharSequence getTitleCondensed() { return null; } @Override public boolean hasSubMenu() { return false; } @Override public boolean isCheckable() { return false; } @Override public boolean isChecked() { return false; } @Override public boolean isEnabled() { return false; } @Override public boolean isVisible() { return false; } @Override public MenuItem setAlphabeticShortcut(char alphaChar) { return null; } @Override public MenuItem setCheckable(boolean checkable) { return null; } @Override public MenuItem setChecked(boolean checked) { return null; } @Override public MenuItem setEnabled(boolean enabled) { return null; } @Override public MenuItem setIcon(Drawable icon) { return null; } @Override public MenuItem setIcon(int iconRes) { return null; } @Override public MenuItem setIntent(Intent intent) { return null; } @Override public MenuItem setNumericShortcut(char numericChar) { return null; } @Override public MenuItem setOnMenuItemClickListener( OnMenuItemClickListener menuItemClickListener) { return null; } @Override public MenuItem setShortcut(char numericChar, char alphaChar) { return null; } @Override public MenuItem setTitle(CharSequence title) { return null; } @Override public MenuItem setTitle(int title) { return null; } @Override public MenuItem setTitleCondensed(CharSequence title) { return null; } @Override public MenuItem setVisible(boolean visible) { 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. */ /* * maps.jar doesn't include all its dependencies; fake them out here for testing. */ package android.widget; public class ZoomButtonsController { }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 android.text.Editable; import android.text.InputFilter; class StubEditable implements Editable { private final String mString; public StubEditable(String s) { mString = s; } public Editable append(char arg0) { return null; } public Editable append(CharSequence arg0) { return null; } public Editable append(CharSequence arg0, int arg1, int arg2) { return null; } public char charAt(int index) { return mString.charAt(index); } public void clear() { } public void clearSpans() { } public Editable delete(int arg0, int arg1) { return null; } public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) { mString.getChars(srcBegin, srcEnd, dst, dstBegin); } public InputFilter[] getFilters() { return null; } public int getSpanEnd(Object arg0) { return 0; } public int getSpanFlags(Object arg0) { return 0; } public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) { return null; } public int getSpanStart(Object arg0) { return 0; } public Editable insert(int arg0, CharSequence arg1) { return null; } public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) { return null; } public int length() { return mString.length(); } @SuppressWarnings("unchecked") public int nextSpanTransition(int arg0, int arg1, Class arg2) { return 0; } public void removeSpan(Object arg0) { } public Editable replace(int arg0, int arg1, CharSequence arg2) { return null; } public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) { return null; } public void setFilters(InputFilter[] arg0) { } public void setSpan(Object arg0, int arg1, int arg2, int arg3) { } public CharSequence subSequence(int start, int end) { return mString.subSequence(start, end); } @Override public String toString() { return mString; } }
Java
package com.google.code.geobeagle; import static org.easymock.EasyMock.expect; import org.powermock.api.easymock.PowerMock; public class Common { public static Geocache mockGeocache(double latitude, double longitude) { Geocache geocache = PowerMock.createMock(Geocache.class); expect(geocache.getLatitude()).andReturn(latitude).anyTimes(); expect(geocache.getLongitude()).andReturn(longitude).anyTimes(); 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.database; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheListPrecomputed; import java.util.ArrayList; class CachesProviderStub implements ICachesProviderArea { private ArrayList<Geocache> mGeocaches = new ArrayList<Geocache>(); private double mLatLow = 0.0; private double mLatHigh = 0.0; private double mLonLow = 0.0; private double mLonHigh = 0.0; private boolean mHasChanged = true; private int mBoundsCalls = 0; private boolean mIsInitialized = false; public CachesProviderStub() { } public CachesProviderStub(ArrayList<Geocache> geocacheList) { mGeocaches = geocacheList; } public void addCache(Geocache geocache) { mGeocaches.add(geocache); } /** maxCount <= 0 means no limit */ private GeocacheListPrecomputed fetchCaches(int maxCount) { if (!mIsInitialized) return new GeocacheListPrecomputed(mGeocaches); ArrayList<Geocache> selection = new ArrayList<Geocache>(); for (Geocache geocache : mGeocaches) { if (geocache.getLatitude() >= mLatLow && geocache.getLatitude() <= mLatHigh && geocache.getLongitude() >= mLonLow && geocache.getLongitude() <= mLonHigh) { selection.add(geocache); if (selection.size() == maxCount) break; } } return new GeocacheListPrecomputed(selection); } @Override public GeocacheListPrecomputed getCaches() { return fetchCaches(-1); } @Override public GeocacheListPrecomputed getCaches(int maxCount) { return fetchCaches(maxCount); } @Override public int getCount() { return fetchCaches(-1).size(); } public int getSetBoundsCalls() { return mBoundsCalls; } @Override public void setBounds(double latLow, double lonLow, double latHigh, double lonHigh) { mBoundsCalls += 1; mLatLow = latLow; mLatHigh = latHigh; mLonLow = lonLow; mLonHigh = lonHigh; mHasChanged = true; mIsInitialized = true; } @Override public boolean hasChanged() { return mHasChanged; } @Override public void resetChanged() { mHasChanged = false; } public void setChanged(boolean changed) { mHasChanged = changed; } @Override public int getTotalCount() { return mGeocaches.size(); } @Override public void clearBounds() { mIsInitialized = false; } }
Java
package com.google.code.geobeagle; import java.util.Hashtable; public class CacheTypeFactory { private final Hashtable<Integer, CacheType> mCacheTypes = new Hashtable<Integer, CacheType>(CacheType.values().length); public CacheTypeFactory() { for (CacheType cacheType : CacheType.values()) mCacheTypes.put(cacheType.toInt(), cacheType); } public CacheType fromInt(int i) { return mCacheTypes.get(i); } public CacheType fromTag(String tag) { for (CacheType cacheType : mCacheTypes.values()) { if (tag.equals(cacheType.getTag())) return cacheType; } //Quick-n-dirty way of implementing additional names for certain cache types if (tag.equals("Traditional Cache")) return CacheType.TRADITIONAL; if (tag.equals("Multi-cache")) return CacheType.MULTI; if (tag.equals("Virtual")) return CacheType.VIRTUAL; if (tag.equals("Event")) return CacheType.EVENT; if (tag.equals("Webcam")) return CacheType.WEBCAM; if (tag.equals("Earth")) return CacheType.EARTHCACHE; return CacheType.NULL; } public int container(String container) { if (container.equals("Micro")) { return 1; } else if (container.equals("Small")) { return 2; } else if (container.equals("Regular")) { return 3; } else if (container.equals("Large")) { return 4; } return 0; } public int stars(String stars) { try { return Math.round(Float.parseFloat(stars) * 2); } catch (Exception ex) { 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.map; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapView; import com.google.android.maps.Overlay; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Point; import android.graphics.Rect; import java.util.List; public class DensityOverlay extends Overlay { // Create delegate because it's not possible to test classes that extend // Android classes. public static DensityOverlayDelegate createDelegate(List<DensityMatrix.DensityPatch> patches, GeoPoint nullGeoPoint, QueryManager queryManager) { final Rect patchRect = new Rect(); final Paint paint = new Paint(); paint.setARGB(128, 255, 0, 0); final Point screenLow = new Point(); final Point screenHigh = new Point(); final DensityPatchManager densityPatchManager = new DensityPatchManager(patches, queryManager); return new DensityOverlayDelegate(patchRect, paint, screenLow, screenHigh, densityPatchManager); } private DensityOverlayDelegate mDelegate; public DensityOverlay(DensityOverlayDelegate densityOverlayDelegate) { mDelegate = densityOverlayDelegate; } @Override public void draw(Canvas canvas, MapView mapView, boolean shadow) { super.draw(canvas, mapView, shadow); mDelegate.draw(canvas, mapView, shadow); } }
Java
/* ** Licensed under the Apache License, Version 2.0 (the "License"); ** you may not use this file except in compliance with the License. ** You may obtain a copy of the License at ** ** http://www.apache.org/licenses/LICENSE-2.0 ** ** Unless required by applicable law or agreed to in writing, software ** distributed under the License is distributed on an "AS IS" BASIS, ** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.ItemizedOverlay; import com.google.android.maps.MapView; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.activity.cachelist.GeocacheListController; import com.google.code.geobeagle.activity.main.GeoBeagle; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import java.util.ArrayList; public class CachePinsOverlay extends ItemizedOverlay<CacheItem> { private final CacheItemFactory mCacheItemFactory; private final Context mContext; private final ArrayList<Geocache> mCacheList; public CachePinsOverlay(CacheItemFactory cacheItemFactory, Context context, Drawable defaultMarker, ArrayList<Geocache> list) { super(boundCenterBottom(defaultMarker)); mContext = context; mCacheItemFactory = cacheItemFactory; mCacheList = list; populate(); } /* (non-Javadoc) * @see com.google.android.maps.Overlay#draw(android.graphics.Canvas, com.google.android.maps.MapView, boolean, long) */ @Override public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) { return super.draw(canvas, mapView, shadow, when); } @Override protected boolean onTap(int i) { Geocache geocache = getItem(i).getGeocache(); if (geocache == null) return false; final Intent intent = new Intent(mContext, GeoBeagle.class); intent.setAction(GeocacheListController.SELECT_CACHE); intent.putExtra("geocache", geocache); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); mContext.startActivity(intent); return true; } @Override protected CacheItem createItem(int i) { return mCacheItemFactory.createCacheItem(mCacheList.get(i)); } @Override public int size() { return mCacheList.size(); } }
Java