code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.ImportThreadWrapper;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.io.GpxImporterDI.ToastFactory;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.app.ListActivity;
import android.widget.Toast;
public class GpxImporter {
private final Database mDatabase;
private final ErrorDisplayer mErrorDisplayer;
private final GpxLoader mGpxLoader;
private final ImportThreadWrapper mImportThreadWrapper;
private final ListActivity mListActivity;
private final MessageHandler mMessageHandler;
private final SQLiteWrapper mSqliteWrapper;
private final ToastFactory mToastFactory;
GpxImporter(GpxLoader gpxLoader, Database database, SQLiteWrapper sqliteWrapper,
ListActivity listActivity, ImportThreadWrapper importThreadWrapper,
MessageHandler messageHandler, ErrorDisplayer errorDisplayer, ToastFactory toastFactory) {
mSqliteWrapper = sqliteWrapper;
mDatabase = database;
mListActivity = listActivity;
mGpxLoader = gpxLoader;
mImportThreadWrapper = importThreadWrapper;
mMessageHandler = messageHandler;
mErrorDisplayer = errorDisplayer;
mToastFactory = toastFactory;
}
public void abort() throws InterruptedException {
mMessageHandler.abortLoad();
mGpxLoader.abort();
if (mImportThreadWrapper.isAlive()) {
mImportThreadWrapper.join();
mSqliteWrapper.close();
mToastFactory.showToast(mListActivity, R.string.import_canceled, Toast.LENGTH_SHORT);
}
}
public void importGpxs(CacheListDelegate cacheListDelegate) {
mSqliteWrapper.openReadableDatabase(mDatabase);
mImportThreadWrapper.open(cacheListDelegate, mGpxLoader, mErrorDisplayer);
mImportThreadWrapper.start();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.io.Database.ISQLiteDatabase;
/**
* @author sng
*/
public class CacheWriter {
private final ISQLiteDatabase mSqlite;
private final DbToGeocacheAdapter mDbToGeocacheAdapter;
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
};
CacheWriter(ISQLiteDatabase sqlite, DbToGeocacheAdapter dbToGeocacheAdapter) {
mSqlite = sqlite;
mDbToGeocacheAdapter = dbToGeocacheAdapter;
}
public void clearCaches(String source) {
mSqlite.execSQL(Database.SQL_CLEAR_CACHES, source);
}
/**
* Deletes any cache/gpx entries marked delete_me, then marks all remaining
* gpx-based caches, and gpx entries with delete_me = 1.
*/
public void clearEarlierLoads() {
for (String sql : CacheWriter.SQLS_CLEAR_EARLIER_LOADS) {
mSqlite.execSQL(sql);
}
}
public void deleteCache(CharSequence id) {
mSqlite.execSQL(Database.SQL_DELETE_CACHE, id);
}
public void insertAndUpdateCache(CharSequence id, CharSequence name, double latitude,
double longitude, Source sourceType, String sourceName) {
mSqlite.execSQL(Database.SQL_REPLACE_CACHE, id, name, new Double(latitude), new Double(
longitude), mDbToGeocacheAdapter.sourceTypeToSourceName(sourceType, sourceName));
}
public boolean isGpxAlreadyLoaded(String gpxName, String gpxTime) {
boolean gpxAlreadyLoaded = mSqlite.countResults(Database.TBL_GPX,
Database.SQL_MATCH_NAME_AND_EXPORTED_LATER, gpxName, gpxTime) > 0;
if (gpxAlreadyLoaded) {
mSqlite.execSQL(Database.SQL_CACHES_DONT_DELETE_ME, gpxName);
mSqlite.execSQL(Database.SQL_GPX_DONT_DELETE_ME, gpxName);
}
return gpxAlreadyLoaded;
}
public void startWriting() {
mSqlite.beginTransaction();
}
public void stopWriting() {
// TODO: abort if no writes--otherwise sqlite is unhappy.
mSqlite.setTransactionSuccessful();
mSqlite.endTransaction();
}
public void writeGpx(String gpxName, String pocketQueryExportTime) {
mSqlite.execSQL(Database.SQL_REPLACE_GPX, gpxName, pocketQueryExportTime);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
public class LocationSaver {
private final CacheWriter mCacheWriter;
private final Database mDatabase;
private final SQLiteWrapper mSQLiteWrapper;
public LocationSaver(Database database, SQLiteWrapper sqliteWrapper, CacheWriter cacheWriter) {
mDatabase = database;
mSQLiteWrapper = sqliteWrapper;
mCacheWriter = cacheWriter;
}
public void saveLocation(Geocache geocache) {
mSQLiteWrapper.openWritableDatabase(mDatabase);
// TODO: catch errors on open
mCacheWriter.startWriting();
mCacheWriter.insertAndUpdateCache(geocache.getId(), geocache.getName(), geocache
.getLatitude(), geocache.getLongitude(), geocache.getSourceType(), geocache
.getSourceName());
mCacheWriter.stopWriting();
mSQLiteWrapper.close();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.io.CachePersisterFacadeDI.FileFactory;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.io.GpxToCacheDI.XmlPullParserWrapper;
import android.os.PowerManager.WakeLock;
import java.io.File;
import java.io.IOException;
public class CachePersisterFacade {
public static final int WAKELOCK_DURATION = 5000;
private final CacheDetailsWriter mCacheDetailsWriter;
private final CacheTagWriter mCacheTagWriter;
private final FileFactory mFileFactory;
private final MessageHandler mMessageHandler;
private final WakeLock mWakeLock;
CachePersisterFacade(CacheTagWriter cacheTagWriter, FileFactory fileFactory,
CacheDetailsWriter cacheDetailsWriter, MessageHandler messageHandler, WakeLock wakeLock) {
mCacheTagWriter = cacheTagWriter;
mFileFactory = fileFactory;
mCacheDetailsWriter = cacheDetailsWriter;
mMessageHandler = messageHandler;
mWakeLock = wakeLock;
}
public void close(boolean success) {
mCacheTagWriter.stopWriting(success);
}
public void end() {
mCacheTagWriter.end();
}
void endTag() throws IOException {
mCacheDetailsWriter.close();
mCacheTagWriter.write();
}
public void gpxName(String text) {
mCacheTagWriter.gpxName(text);
}
public boolean gpxTime(String gpxTime) {
return mCacheTagWriter.gpxTime(gpxTime);
}
void groundspeakName(String text) {
mMessageHandler.updateName(text);
mCacheTagWriter.cacheName(text);
}
public void hint(String text) throws IOException {
mCacheDetailsWriter.writeHint(text);
}
void line(String text) throws IOException {
mCacheDetailsWriter.writeLine(text);
}
void logDate(String text) throws IOException {
mCacheDetailsWriter.writeLogDate(text);
}
void open(String text) {
mMessageHandler.updateSource(text);
mCacheTagWriter.startWriting();
mCacheTagWriter.gpxName(text);
}
void start() {
File file = mFileFactory.createFile(CacheDetailsWriter.GEOBEAGLE_DIR);
file.mkdirs();
}
public void symbol(String text) {
mCacheTagWriter.symbol(text);
}
void wpt(XmlPullParserWrapper mXmlPullParser) {
mCacheTagWriter.clear();
String latitude = mXmlPullParser.getAttributeValue(null, "lat");
String longitude = mXmlPullParser.getAttributeValue(null, "lon");
mCacheTagWriter.latitudeLongitude(latitude, longitude);
mCacheDetailsWriter.latitudeLongitude(latitude, longitude);
}
void wptName(String wpt) throws IOException {
mCacheDetailsWriter.open(wpt);
mCacheDetailsWriter.writeWptName(wpt);
mCacheTagWriter.id(wpt);
mMessageHandler.updateWaypointId(wpt);
mWakeLock.acquire(WAKELOCK_DURATION);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.io.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 reset() {
mPath = "";
}
public void startTag(String mCurrentTag) {
mPath += "/" + mCurrentTag;
}
}
private final GpxEventHandler mGpxEventHandler;
private final XmlPathBuilder mXmlPathBuilder;
private final XmlPullParserWrapper mXmlPullParser;
public EventHelper(XmlPathBuilder xmlPathBuilder, GpxEventHandler gpxEventHandler,
XmlPullParserWrapper xmlPullParser) {
mXmlPathBuilder = xmlPathBuilder;
mGpxEventHandler = gpxEventHandler;
mXmlPullParser = xmlPullParser;
}
public boolean handleEvent(int eventType) throws IOException {
switch (eventType) {
case XmlPullParser.START_TAG:
mXmlPathBuilder.startTag(mXmlPullParser.getName());
mGpxEventHandler.startTag(mXmlPathBuilder.getPath(), mXmlPullParser);
break;
case XmlPullParser.END_TAG:
mGpxEventHandler.endTag(mXmlPathBuilder.getPath());
mXmlPathBuilder.endTag(mXmlPullParser.getName());
break;
case XmlPullParser.TEXT:
return mGpxEventHandler.text(mXmlPathBuilder.getPath(), mXmlPullParser.getText());
}
return true;
}
public void reset() {
mXmlPathBuilder.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.io;
import com.google.code.geobeagle.io.CachePersisterFacadeDI.WriterWrapper;
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.io;
import com.google.code.geobeagle.io.GpxToCacheDI.XmlPullParserWrapper;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.Reader;
public class GpxToCache {
@SuppressWarnings("serial")
public static class CancelException extends Exception {
}
private boolean mAbort;
private final EventHelper mEventHelper;
private final XmlPullParserWrapper mXmlPullParserWrapper;
GpxToCache(XmlPullParserWrapper xmlPullParserWrapper, EventHelper eventHelper) {
mXmlPullParserWrapper = xmlPullParserWrapper;
mEventHelper = eventHelper;
}
public void abort() {
mAbort = true;
}
public String getSource() {
return mXmlPullParserWrapper.getSource();
}
/**
* @return false if this file has already been loaded.
* @throws XmlPullParserException
* @throws IOException
* @throws CancelException
*/
public boolean load() throws XmlPullParserException, IOException, CancelException {
int eventType;
for (eventType = mXmlPullParserWrapper.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = mXmlPullParserWrapper
.next()) {
if (mAbort)
throw new CancelException();
// File already loaded.
if (!mEventHelper.handleEvent(eventType))
return true;
}
// Pick up END_DOCUMENT event as well.
mEventHelper.handleEvent(eventType);
return false;
}
public void open(String source, Reader reader) throws XmlPullParserException, IOException {
mXmlPullParserWrapper.open(source, reader);
mEventHelper.reset();
mAbort = 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.io;
import java.io.IOException;
public class GpxEventHandler {
public static final String XPATH_GPXNAME = "/gpx/name";
public static final String XPATH_GPXTIME = "/gpx/time";
public static final String XPATH_GROUNDSPEAKNAME = "/gpx/wpt/groundspeak:cache/groundspeak:name";
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";
public static final String[] XPATH_PLAINLINES = {
"/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"
};
public static final String XPATH_SYM = "/gpx/wpt/sym";
public static final String XPATH_WPT = "/gpx/wpt";
public static final String XPATH_WPTNAME = "/gpx/wpt/name";
private final CachePersisterFacade mCachePersisterFacade;
public GpxEventHandler(CachePersisterFacade cachePersisterFacade) {
mCachePersisterFacade = cachePersisterFacade;
}
public void endTag(String previousFullPath) throws IOException {
if (previousFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.endTag();
}
}
public void startTag(String mFullPath, GpxToCacheDI.XmlPullParserWrapper mXmlPullParser) {
if (mFullPath.equals(XPATH_WPT)) {
mCachePersisterFacade.wpt(mXmlPullParser);
}
}
public boolean text(String mFullPath, String text) throws IOException {
text = text.trim();
if (mFullPath.equals(XPATH_WPTNAME)) {
mCachePersisterFacade.wptName(text);
} else if (mFullPath.equals(XPATH_GPXNAME)) {
mCachePersisterFacade.gpxName(text);
} else if (mFullPath.equals(XPATH_GPXTIME)) {
return mCachePersisterFacade.gpxTime(text);
} else if (mFullPath.equals(XPATH_GROUNDSPEAKNAME)) {
mCachePersisterFacade.groundspeakName(text);
} else if (mFullPath.equals(XPATH_LOGDATE)) {
mCachePersisterFacade.logDate(text);
} else if (mFullPath.equals(XPATH_SYM)) {
mCachePersisterFacade.symbol(text);
} else if (mFullPath.equals(XPATH_HINT)) {
if (!text.equals("")) {
mCachePersisterFacade.hint(text);
}
} else {
for (String writeLineMatch : XPATH_PLAINLINES) {
if (mFullPath.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.io;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class Database {
public static interface ISQLiteDatabase {
void beginTransaction();
int countResults(String table, String sql, String... args);
void endTransaction();
void execSQL(String s, Object... bindArg1);
public Cursor query(String table, String[] columns, String selection, String groupBy,
String having, String orderBy, String limit, String... selectionArgs);
void setTransactionSuccessful();
}
public static class OpenHelperDelegate {
public void onCreate(ISQLiteDatabase db) {
db.execSQL(SQL_CREATE_CACHE_TABLE);
db.execSQL(SQL_CREATE_GPX_TABLE);
db.execSQL(SQL_CREATE_IDX_LATITUDE);
db.execSQL(SQL_CREATE_IDX_LONGITUDE);
db.execSQL(SQL_CREATE_IDX_SOURCE);
}
public void onUpgrade(ISQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 9) {
db.execSQL(SQL_DROP_CACHE_TABLE);
db.execSQL(SQL_CREATE_CACHE_TABLE);
db.execSQL(SQL_CREATE_IDX_LATITUDE);
db.execSQL(SQL_CREATE_IDX_LONGITUDE);
db.execSQL(SQL_CREATE_IDX_SOURCE);
}
if (oldVersion == 9) {
db.execSQL(SQL_CACHES_ADD_COLUMN);
}
if (oldVersion < 10) {
db.execSQL(SQL_CREATE_GPX_TABLE);
}
}
}
public static final String DATABASE_NAME = "GeoBeagle.db";
public static final int DATABASE_VERSION = 10;
public static final String[] READER_COLUMNS = new String[] {
"Latitude", "Longitude", "Id", "Description", "Source"
};
public static final String S0_COLUMN_DELETE_ME = "DeleteMe BOOLEAN NOT NULL Default 1";
public static final String S0_INTENT = "intent";
public static final String SQL_CACHES_ADD_COLUMN = "ALTER TABLE CACHES ADD COLUMN "
+ S0_COLUMN_DELETE_ME;
public static final String SQL_CACHES_DONT_DELETE_ME = "UPDATE CACHES SET DeleteMe = 0 WHERE Source = ?";
public static final String SQL_CLEAR_CACHES = "DELETE FROM CACHES WHERE Source=?";
public static final String SQL_CREATE_CACHE_TABLE = "CREATE TABLE CACHES ("
+ "Id VARCHAR PRIMARY KEY, Description VARCHAR, "
+ "Latitude DOUBLE, Longitude DOUBLE, Source VARCHAR, " + S0_COLUMN_DELETE_ME + ")";
public static final String SQL_CREATE_GPX_TABLE = "CREATE TABLE GPX ("
+ "Name VARCHAR PRIMARY KEY NOT NULL, ExportTime DATETIME NOT NULL, DeleteMe BOOLEAN NOT NULL)";
public static final String SQL_CREATE_IDX_LATITUDE = "CREATE INDEX IDX_LATITUDE on CACHES (Latitude)";
public static final String SQL_CREATE_IDX_LONGITUDE = "CREATE INDEX IDX_LONGITUDE on CACHES (Longitude)";
public static final String SQL_CREATE_IDX_SOURCE = "CREATE INDEX IDX_SOURCE on CACHES (Source)";
public static final String SQL_DELETE_CACHE = "DELETE FROM CACHES WHERE Id=?";
public static final String SQL_DELETE_OLD_CACHES = "DELETE FROM CACHES WHERE DeleteMe = 1";
public static final String SQL_DELETE_OLD_GPX = "DELETE FROM GPX WHERE DeleteMe = 1";
public static final String SQL_DROP_CACHE_TABLE = "DROP TABLE IF EXISTS CACHES";
public static final String SQL_GPX_DONT_DELETE_ME = "UPDATE GPX SET DeleteMe = 0 WHERE Name = ?";
public static final String SQL_MATCH_NAME_AND_EXPORTED_LATER = "Name = ? AND ExportTime >= ?";
public static final String SQL_REPLACE_CACHE = "REPLACE INTO CACHES "
+ "(Id, Description, Latitude, Longitude, Source, DeleteMe) VALUES (?, ?, ?, ?, ?, 0)";
public static final String SQL_REPLACE_GPX = "REPLACE INTO GPX (Name, ExportTime, DeleteMe) VALUES (?, ?, 0)";
public static final String SQL_RESET_DELETE_ME_CACHES = "UPDATE CACHES SET DeleteMe = 1 WHERE Source != '"
+ S0_INTENT + "'";
public static final String SQL_RESET_DELETE_ME_GPX = "UPDATE GPX SET DeleteMe = 1";
public static final String TBL_CACHES = "CACHES";
public static final String TBL_GPX = "GPX";
private final SQLiteOpenHelper mSqliteOpenHelper;
Database(SQLiteOpenHelper sqliteOpenHelper) {
mSqliteOpenHelper = sqliteOpenHelper;
}
public SQLiteDatabase getReadableDatabase() {
return mSqliteOpenHelper.getReadableDatabase();
}
public SQLiteDatabase getWritableDatabase() {
return mSqliteOpenHelper.getWritableDatabase();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.Geocaches;
import com.google.code.geobeagle.io.CacheReader.CacheReaderCursor;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import java.util.ArrayList;
public class GeocachesSql {
private final CacheReader mCacheReader;
private final Database mDatabase;
private final Geocaches mGeocaches;
private final LocationControl mLocationControl;
private final SQLiteWrapper mSQLiteWrapper;
GeocachesSql(CacheReader cacheReader, Geocaches geocaches, Database database,
SQLiteWrapper sqliteWrapper, LocationControl locationControl) {
mCacheReader = cacheReader;
mGeocaches = geocaches;
mDatabase = database;
mSQLiteWrapper = sqliteWrapper;
mLocationControl = locationControl;
}
public int getCount() {
mSQLiteWrapper.openWritableDatabase(mDatabase);
int count = mCacheReader.getTotalCount();
mSQLiteWrapper.close();
return count;
}
public ArrayList<Geocache> getGeocaches() {
return mGeocaches.getAll();
}
public void loadNearestCaches() {
// TODO: This has to be writable for upgrade to work; we should open one
// readable and one writable at the activity level, and then pass it
// down.
mSQLiteWrapper.openWritableDatabase(mDatabase);
CacheReaderCursor cursor = mCacheReader.open(mLocationControl.getLocation());
if (cursor != null) {
read(cursor);
cursor.close();
}
mSQLiteWrapper.close();
}
public void read(CacheReaderCursor cursor) {
mGeocaches.clear();
do {
mGeocaches.add(cursor.getCache());
} while (cursor.moveToNext());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
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;
}
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 {
mHtmlWriter.open(CacheDetailsWriter.GEOBEAGLE_DIR + "/" + wpt + ".html");
}
public void writeHint(String text) throws IOException {
mHtmlWriter.write("<br />Hint: <font color=gray>" + text + "</font>");
}
void writeLine(String text) throws IOException {
mHtmlWriter.write(text);
}
void writeLogDate(String text) throws IOException {
mHtmlWriter.writeSeparator();
mHtmlWriter.write(text);
}
void writeWptName(String wpt) throws IOException {
mHtmlWriter.writeHeader();
mHtmlWriter.write(wpt);
mHtmlWriter.write(mLatitude + ", " + mLongitude);
mLatitude = mLongitude = null;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.data.Geocache.Source;
// TODO: Rename to CacheTagSqlWriter.
/**
* @author sng
*/
public class CacheTagWriter {
public final CacheWriter mCacheWriter;
private boolean mFound;
private String mGpxName;
private CharSequence mId;
private double mLatitude;
private double mLongitude;
private CharSequence mName;
private String mSqlDate;
public CacheTagWriter(CacheWriter cacheWriter) {
mCacheWriter = cacheWriter;
}
public void cacheName(String name) {
mName = name;
}
public void clear() { // TODO: ensure source is not reset
mId = mName = null;
mLatitude = mLongitude = 0;
mFound = false;
}
public void end() {
mCacheWriter.clearEarlierLoads();
}
public void gpxName(String gpxName) {
mGpxName = gpxName;
}
/**
* @param gpxTime
* @return true if we should load this gpx; false if the gpx is already
* loaded.
*/
public boolean gpxTime(String gpxTime) {
mSqlDate = isoTimeToSql(gpxTime);
if (mCacheWriter.isGpxAlreadyLoaded(mGpxName, mSqlDate)) {
return false;
}
mCacheWriter.clearCaches(mGpxName);
return true;
}
public void id(CharSequence id) {
mId = id;
}
public String isoTimeToSql(String gpxTime) {
return gpxTime.substring(0, 10) + " " + gpxTime.substring(11, 19);
}
public void latitudeLongitude(String latitude, String longitude) {
mLatitude = Double.parseDouble(latitude);
mLongitude = Double.parseDouble(longitude);
}
public void startWriting() {
mCacheWriter.startWriting();
}
public void stopWriting(boolean successfulGpxImport) {
mCacheWriter.stopWriting();
if (successfulGpxImport)
mCacheWriter.writeGpx(mGpxName, mSqlDate);
}
public void symbol(String symbol) {
mFound = symbol.equals("Geocache Found");
}
public void write() {
if (!mFound)
mCacheWriter.insertAndUpdateCache(mId, mName, mLatitude, mLongitude, Source.GPX,
mGpxName);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.io;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.gpx.IGpxReader;
import com.google.code.geobeagle.gpx.GpxAndZipFiles.GpxAndZipFilesIter;
import com.google.code.geobeagle.io.GpxImporterDI.MessageHandler;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ImportThreadDelegate {
public static class ImportThreadHelper {
private final ErrorDisplayer mErrorDisplayer;
private final GpxLoader mGpxLoader;
private final MessageHandler mMessageHandler;
public ImportThreadHelper(GpxLoader gpxLoader, MessageHandler messageHandler,
ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mGpxLoader = gpxLoader;
mMessageHandler = messageHandler;
}
public void cleanup() {
mMessageHandler.loadComplete();
}
public void end() {
mGpxLoader.end();
}
public boolean processFile(IGpxReader iGpxFile) {
String filename = iGpxFile.getFilename();
try {
mGpxLoader.open(filename, iGpxFile.open());
if (!mGpxLoader.load())
return false;
return true;
} catch (final FileNotFoundException e) {
mErrorDisplayer.displayError(R.string.error_opening_file, filename);
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
return false;
}
public boolean start(boolean hasNext) {
if (!hasNext) {
mErrorDisplayer.displayError(R.string.error_no_gpx_files);
return false;
}
mGpxLoader.start();
return true;
}
}
private final GpxAndZipFiles mGpxAndZipFiles;
private ImportThreadHelper mImportThreadHelper;
private ErrorDisplayer mErrorDisplayer;
public ImportThreadDelegate(GpxAndZipFiles gpxAndZipFiles,
ImportThreadHelper importThreadHelper, ErrorDisplayer errorDisplayer) {
mGpxAndZipFiles = gpxAndZipFiles;
mImportThreadHelper = importThreadHelper;
mErrorDisplayer = errorDisplayer;
}
public void run() {
try {
tryRun();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
} finally {
mImportThreadHelper.cleanup();
}
}
protected void tryRun() throws IOException {
GpxAndZipFilesIter gpxFileIter = mGpxAndZipFiles.iterator();
if (gpxFileIter == null) {
mErrorDisplayer.displayError(R.string.error_cant_read_sd);
return;
}
if (!mImportThreadHelper.start(gpxFileIter.hasNext()))
return;
while (gpxFileIter.hasNext()) {
if (!mImportThreadHelper.processFile(gpxFileIter.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.io;
import com.google.code.geobeagle.data.Geocache.Source;
public class DbToGeocacheAdapter {
public Source sourceNameToSourceType(String sourceName) {
if (sourceName.equals("intent"))
return Source.WEB_URL;
else if (sourceName.equals("mylocation"))
return Source.MY_LOCATION;
return Source.GPX;
}
public String sourceTypeToSourceName(Source source, String sourceName) {
if (source == Source.MY_LOCATION)
return "mylocation";
else if (source == Source.WEB_URL)
return "intent";
return sourceName;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.net.Uri;
public class UriParser {
public Uri parse(String uriString) {
return Uri.parse(uriString);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.net.UrlQuerySanitizer;
import android.net.UrlQuerySanitizer.ValueSanitizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Util {
public static final String[] geocachingQueryParam = new String[] {
"q"
};
// #Wildwood Park, Saratoga, CA(The Nut Case #89882)
private static final Pattern PAT_ATLASQUEST = Pattern.compile(".*\\((.*)#(.*)\\)");
private static final Pattern PAT_ATSIGN_FORMAT = Pattern.compile("([^@]*)@(.*)");
private static final Pattern PAT_COORD_COMPONENT = Pattern.compile("([\\d.]+)[^\\d]*");
private static final Pattern PAT_LATLON = Pattern
.compile("([NS]?[^NSEW,]*[NS]?),?\\s*([EW]?.*)");
private static final Pattern PAT_NEGSIGN = Pattern.compile("[-WS]");
private static final Pattern PAT_PAREN_FORMAT = Pattern.compile("([^(]*)\\(([^)]*).*");
private static final Pattern PAT_SIGN = Pattern.compile("[-EWNS]");
public static CharSequence formatDegreesAsDecimalDegreesString(double fDegrees) {
final double fAbsDegrees = Math.abs(fDegrees);
final int dAbsDegrees = (int)fAbsDegrees;
return String.format((fDegrees < 0 ? "-" : "") + "%1$d %2$06.3f", dAbsDegrees,
60.0 * (fAbsDegrees - dAbsDegrees));
}
public static String getStackTrace(Exception e) {
final StackTraceElement stack[] = e.getStackTrace();
final StringBuilder sb = new StringBuilder();
for (final StackTraceElement s : stack) {
sb.append(s.toString() + "\n");
}
return sb.toString();
}
public static double parseCoordinate(CharSequence string) {
int sign = 1;
final Matcher negsignMatcher = PAT_NEGSIGN.matcher(string);
if (negsignMatcher.find()) {
sign = -1;
}
final Matcher signMatcher = PAT_SIGN.matcher(string);
string = signMatcher.replaceAll("");
final Matcher dmsMatcher = PAT_COORD_COMPONENT.matcher(string);
double degrees = 0.0;
for (double scale = 1.0; scale <= 3600.0 && dmsMatcher.find(); scale *= 60.0) {
degrees += Double.parseDouble(dmsMatcher.group(1)) / scale;
}
return sign * degrees;
}
public static CharSequence[] parseDescription(CharSequence string) {
Matcher matcher = PAT_ATLASQUEST.matcher(string);
if (matcher.matches())
return new CharSequence[] {
"LB" + matcher.group(2).trim(), matcher.group(1).trim()
};
return new CharSequence[] {
string, ""
};
}
public static CharSequence parseHttpUri(String query, UrlQuerySanitizer sanitizer,
ValueSanitizer valueSanitizer) {
sanitizer.registerParameters(geocachingQueryParam, valueSanitizer);
sanitizer.parseQuery(query);
return sanitizer.getValue("q");
}
public static CharSequence[] splitCoordsAndDescription(CharSequence location) {
Matcher matcher = PAT_ATSIGN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(2).trim(), matcher.group(1).trim()
};
}
matcher = PAT_PAREN_FORMAT.matcher(location);
if (matcher.matches()) {
return new CharSequence[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
}
// No description.
return new CharSequence[] {
location, ""
};
}
public static CharSequence[] splitLatLon(CharSequence string) {
Matcher matcher = PAT_LATLON.matcher(string);
if (matcher.matches())
return new String[] {
matcher.group(1).trim(), matcher.group(2).trim()
};
return null;
}
public static CharSequence[] splitLatLonDescription(CharSequence location) {
CharSequence coordsAndDescription[] = splitCoordsAndDescription(location);
CharSequence latLon[] = splitLatLon(coordsAndDescription[0]);
CharSequence[] parseDescription = parseDescription(coordsAndDescription[1]);
return new CharSequence[] {
latLon[0], latLon[1], parseDescription[0], parseDescription[1]
};
}
}
| Java |
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import android.location.Location;
public class GeocacheFromMyLocationFactory {
private final LocationControl mLocationControl;
private final ErrorDisplayer mErrorDisplayer;
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory,
LocationControl locationControl, ErrorDisplayer errorDisplayer) {
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
mErrorDisplayer = errorDisplayer;
}
public Geocache create() {
Location location = mLocationControl.getLocation();
if (location == null) {
mErrorDisplayer.displayError(R.string.current_location_null);
return null;
}
long time = location.getTime();
return mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format(
"[%1$tk:%1$tM] My Location", time), location.getLatitude(),
location.getLongitude(), Source.MY_LOCATION, null);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.io.LocationSaver;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class GeocacheVector implements IGeocacheVector {
public static class LocationComparator implements Comparator<IGeocacheVector> {
public int compare(IGeocacheVector destination1, IGeocacheVector destination2) {
final float d1 = destination1.getDistance();
final float d2 = destination2.getDistance();
if (d1 < d2)
return -1;
if (d1 > d2)
return 1;
return 0;
}
public void sort(ArrayList<IGeocacheVector> arrayList) {
Collections.sort(arrayList, this);
}
}
public static class MyLocation implements IGeocacheVector {
private final ResourceProvider mResourceProvider;
private GeocacheFromMyLocationFactory mGeocacheFromMyLocationFactory;
private final LocationSaver mLocationSaver;
public MyLocation(ResourceProvider resourceProvider,
GeocacheFromMyLocationFactory geocacheFromMyLocationFactory, LocationSaver locationSaver) {
mResourceProvider = resourceProvider;
mGeocacheFromMyLocationFactory = geocacheFromMyLocationFactory;
mLocationSaver = locationSaver;
}
public CharSequence getCoordinatesIdAndName() {
return null;
}
public Geocache getDestination() {
return null;
}
public float getDistance() {
return -1;
}
public CharSequence getId() {
return mResourceProvider.getString(R.string.my_current_location);
}
public CharSequence getFormattedDistance() {
return "";
}
public CharSequence getIdAndName() {
return mResourceProvider.getString(R.string.my_current_location);
}
public Geocache getGeocache() {
Geocache geocache = mGeocacheFromMyLocationFactory.create();
mLocationSaver.saveLocation(geocache);
return geocache;
}
}
private final Geocache mGeocache;
private final float mDistance;
private final DistanceFormatter mDistanceFormatter;
GeocacheVector(Geocache geocache, float distance, DistanceFormatter distanceFormatter) {
mGeocache = geocache;
mDistance = distance;
mDistanceFormatter = distanceFormatter;
}
public float getDistance() {
return mDistance;
}
public CharSequence getId() {
return mGeocache.getId();
}
public CharSequence getFormattedDistance() {
return mDistanceFormatter.format(mDistance);
}
public CharSequence getIdAndName() {
return mGeocache.getIdAndName();
}
public Geocache getGeocache() {
return mGeocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
public interface IGeocacheVector {
public Geocache getGeocache();
public CharSequence getFormattedDistance();
public float getDistance();
public CharSequence getId();
public CharSequence getIdAndName();
}
| Java |
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.data.Geocache.Source;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
Source source = Source.MY_LOCATION;
int iSource = preferences.getInt("sourceType", -1);
if (iSource != -1)
source = mGeocacheFactory.sourceFromInt(iSource);
return mGeocacheFactory.create(preferences.getString("id", "GCMEY7"), preferences
.getString("name", "Google Falls"), preferences.getFloat("latitude", 37.42235f),
preferences.getFloat("longitude", -122.082217f), source, preferences.getString(
"sourceName", null));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import java.util.ArrayList;
public class Geocaches {
private ArrayList<Geocache> mGeocaches;
public Geocaches() {
mGeocaches = new ArrayList<Geocache>();
}
public void add(Geocache geocache) {
mGeocaches.add(geocache);
}
public void clear() {
mGeocaches.clear();
}
public ArrayList<Geocache> getAll() {
return mGeocaches;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Geocache or letterbox description, id, and coordinates.
*/
public class Geocache implements Parcelable {
public static enum Provider {
ATLAS_QUEST(0), GROUNDSPEAK(1), MY_LOCATION(-1);
private final int mIx;
Provider(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
public static enum Source {
GPX(0), MY_LOCATION(1), WEB_URL(2);
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.mIx] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
public static Parcelable.Creator<Geocache> CREATOR = new GeocacheFactory.CreateGeocacheFromParcel();
public static final String ID = "id";
public static final String LATITUDE = "latitude";
public static final String LONGITUDE = "longitude";
public static final String NAME = "name";
public static final String SOURCE_NAME = "sourceName";
public static final String SOURCE_TYPE = "sourceType";
private final CharSequence mId;
private final double mLatitude;
private final double mLongitude;
private final CharSequence mName;
private final String mSourceName;
private final Source mSourceType;
public Geocache(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
mSourceType = sourceType;
mSourceName = sourceName;
}
public int describeContents() {
return 0;
}
public Provider getContentProvider() {
String prefix = mId.subSequence(0, 2).toString();
if (prefix.equals("GC"))
return Provider.GROUNDSPEAK;
if (prefix.equals("LB"))
return Provider.ATLAS_QUEST;
else
return Provider.MY_LOCATION;
}
public CharSequence getId() {
return mId;
}
public CharSequence getIdAndName() {
if (mId.length() == 0)
return mName;
else if (mName.length() == 0)
return mId;
else
return mId + ": " + mName;
}
public double getLatitude() {
return mLatitude;
}
public double getLongitude() {
return mLongitude;
}
public CharSequence getName() {
return mName;
}
public CharSequence getShortId() {
if (mId.length() > 2)
return mId.subSequence(2, mId.length());
else
return "";
}
public String getSourceName() {
return mSourceName;
}
public Source getSourceType() {
return mSourceType;
}
public void writeToParcel(Parcel out, int flags) {
Bundle bundle = new Bundle();
bundle.putCharSequence(ID, mId);
bundle.putCharSequence(NAME, mName);
bundle.putDouble(LATITUDE, mLatitude);
bundle.putDouble(LONGITUDE, mLongitude);
bundle.putInt(SOURCE_TYPE, mSourceType.mIx);
bundle.putString(SOURCE_NAME, mSourceName);
out.writeBundle(bundle);
}
public void writeToPrefs(Editor editor) {
editor.putString(ID, mId.toString());
editor.putString(NAME, mName.toString());
editor.putFloat(LATITUDE, (float)mLatitude);
editor.putFloat(LONGITUDE, (float)mLongitude);
editor.putInt(SOURCE_TYPE, mSourceType.mIx);
editor.putString(SOURCE_NAME, mSourceName);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import com.google.code.geobeagle.data.GeocacheVector.LocationComparator;
import android.location.Location;
import java.util.ArrayList;
public class GeocacheVectors {
private final GeocacheVectorFactory mGeocacheVectorFactory;
private final ArrayList<IGeocacheVector> mGeocacheVectorsList;
private final LocationComparator mLocationComparator;
public GeocacheVectors(LocationComparator locationComparator,
GeocacheVectorFactory geocacheVectorFactory) {
mGeocacheVectorsList = new ArrayList<IGeocacheVector>(0);
mLocationComparator = locationComparator;
mGeocacheVectorFactory = geocacheVectorFactory;
}
public void add(IGeocacheVector destinationVector) {
mGeocacheVectorsList.add(0, destinationVector);
}
public void addLocations(ArrayList<Geocache> geocaches, Location here) {
for (Geocache geocache : geocaches) {
add(mGeocacheVectorFactory.create(geocache, here));
}
}
public IGeocacheVector get(int position) {
return mGeocacheVectorsList.get(position);
}
public void remove(int position) {
mGeocacheVectorsList.remove(position);
}
public void reset(int size) {
mGeocacheVectorsList.clear();
mGeocacheVectorsList.ensureCapacity(size);
}
public int size() {
return mGeocacheVectorsList.size();
}
public void sort() {
mLocationComparator.sort(mGeocacheVectorsList);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.data;
import android.location.Location;
import java.util.ArrayList;
public class CacheListData {
private final GeocacheVectorFactory mGeocacheVectorFactory;
private final GeocacheVectors mGeocacheVectors;
public CacheListData(GeocacheVectors geocacheVectors, GeocacheVectorFactory geocacheVectorFactory) {
mGeocacheVectors = geocacheVectors;
mGeocacheVectorFactory = geocacheVectorFactory;
}
public void add(ArrayList<Geocache> geocaches, Location here) {
mGeocacheVectors.reset(geocaches.size());
mGeocacheVectors.addLocations(geocaches, here);
mGeocacheVectors.add(mGeocacheVectorFactory.createMyLocation());
mGeocacheVectors.sort();
}
}
| Java |
package com.google.code.geobeagle.data;
public class DistanceFormatter {
public CharSequence format(float distance) {
if (distance == -1) {
return "";
}
if (distance >= 1000) {
return (int)(distance / 1000) + "km";
}
return (int)distance + "m";
}
}
| Java |
package com.google.code.geobeagle.data;
import android.os.Bundle;
import android.os.Parcel;
public class GeocacheFromParcelFactory {
private final GeocacheFactory mGeocacheFactory;
public GeocacheFromParcelFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(Parcel in) {
Bundle bundle = in.readBundle();
return mGeocacheFactory.create(bundle.getCharSequence("id"),
bundle.getCharSequence("name"), bundle.getDouble("latitude"), bundle
.getDouble("longitude"), mGeocacheFactory.sourceFromInt(bundle
.getInt("sourceType")), bundle.getString("sourceName"));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.gpx;
import com.google.code.geobeagle.gpx.IGpxReader;
import com.google.code.geobeagle.gpx.IGpxReaderIter;
public class GpxFileOpener {
class GpxFileIter implements IGpxReaderIter {
public boolean hasNext() {
return mFilename != null;
}
public IGpxReader next() {
final IGpxReader gpxReader = new GpxReader(mFilename);
mFilename = null;
return gpxReader;
}
}
private String mFilename;
public GpxFileOpener(String filename) {
mFilename = filename;
}
public IGpxReaderIter iterator() {
return new GpxFileIter();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.gpx;
import com.google.code.geobeagle.gpx.GpxAndZipFiles;
import com.google.code.geobeagle.gpx.IGpxReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
public GpxReader(String filename) {
mFilename = filename;
}
public String getFilename() {
return mFilename;
}
public Reader open() throws FileNotFoundException {
return new BufferedReader(new FileReader(GpxAndZipFiles.GPX_DIR + mFilename));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx;
import java.io.IOException;
public interface IGpxReaderIter {
public boolean hasNext() throws IOException;
public IGpxReader next() throws IOException;
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx;
import com.google.code.geobeagle.gpx.gpx.GpxFileOpener;
import com.google.code.geobeagle.gpx.zip.ZipFileOpener;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
public class GpxAndZipFiles {
public static class GpxAndZipFilesIter {
private final String[] mFileList;
private final GpxAndZipFilesIterFactory mGpxAndZipFileIterFactory;
private int mIxFileList;
private IGpxReaderIter mSubIter;
GpxAndZipFilesIter(String[] fileList, GpxAndZipFilesIterFactory gpxAndZipFilesIterFactory) {
mFileList = fileList;
mGpxAndZipFileIterFactory = gpxAndZipFilesIterFactory;
mIxFileList = 0;
}
public boolean hasNext() throws IOException {
if (mSubIter != null && mSubIter.hasNext())
return true;
return mIxFileList < mFileList.length;
}
public IGpxReader next() throws IOException {
if (mSubIter == null || !mSubIter.hasNext())
mSubIter = mGpxAndZipFileIterFactory.fromFile(mFileList[mIxFileList++]);
return mSubIter.next();
}
}
public static class GpxAndZipFilesIterFactory {
public IGpxReaderIter fromFile(String filename) throws IOException {
if (filename.endsWith(".zip")) {
return new ZipFileOpener(GPX_DIR + filename, new ZipInputStreamFactory())
.iterator();
}
return new GpxFileOpener(filename).iterator();
}
}
public static class GpxAndZipFilenameFilter implements FilenameFilter {
public boolean accept(File dir, String name) {
return !name.startsWith(".") && (name.endsWith(".gpx") || name.endsWith(".zip"));
}
}
public static final String GPX_DIR = "/sdcard/download/";
private final FilenameFilter mFilenameFilter;
private final GpxAndZipFilesIterFactory mGpxFileIterFactory;
public GpxAndZipFiles(FilenameFilter filenameFilter,
GpxAndZipFilesIterFactory gpxFileIterFactory) {
mFilenameFilter = filenameFilter;
mGpxFileIterFactory = gpxFileIterFactory;
}
public GpxAndZipFilesIter iterator() {
String[] fileList = new File(GPX_DIR).list(mFilenameFilter);
if (fileList == null)
return null;
return new GpxAndZipFilesIter(fileList, mGpxFileIterFactory);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx;
import java.io.FileNotFoundException;
import java.io.Reader;
public interface IGpxReader {
String getFilename();
Reader open() throws FileNotFoundException;
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.zip;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class GpxZipInputStream {
private ZipEntry mNextEntry;
private final ZipInputStream mZipInputStream;
public GpxZipInputStream(ZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
}
ZipEntry getNextEntry() throws IOException {
mNextEntry = null;
mNextEntry = mZipInputStream.getNextEntry();
while (mNextEntry != null && mNextEntry.getName().endsWith("-wpts.gpx")) {
mNextEntry = mZipInputStream.getNextEntry();
}
return mNextEntry;
}
InputStream getStream() throws IOException {
return mZipInputStream;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.zip;
import com.google.code.geobeagle.gpx.IGpxReader;
import java.io.Reader;
class GpxReader implements IGpxReader {
private final String mFilename;
private final Reader mReader;
GpxReader(String filename, Reader reader) {
mFilename = filename;
mReader = reader;
}
public String getFilename() {
return mFilename;
}
public Reader open() {
return mReader;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.zip;
import com.google.code.geobeagle.gpx.IGpxReader;
import com.google.code.geobeagle.gpx.IGpxReaderIter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
public class ZipFileOpener {
public static class ZipFileIter implements IGpxReaderIter {
private ZipEntry mNextZipEntry;
private final GpxZipInputStream mZipInputStream;
ZipFileIter(GpxZipInputStream zipInputStream) {
mZipInputStream = zipInputStream;
mNextZipEntry = null;
}
public boolean hasNext() throws IOException {
if (mNextZipEntry == null)
mNextZipEntry = mZipInputStream.getNextEntry();
return mNextZipEntry != null;
}
public IGpxReader next() throws IOException {
if (mNextZipEntry == null)
mNextZipEntry = mZipInputStream.getNextEntry();
if (mNextZipEntry == null)
return null;
final String name = mNextZipEntry.getName();
mNextZipEntry = null;
return new GpxReader(name, new InputStreamReader(mZipInputStream.getStream()));
}
}
private final String mFilename;
private final ZipInputStreamFactory mZipInputStreamFactory;
public ZipFileOpener(String filename, ZipInputStreamFactory zipInputStreamFactory) {
mFilename = filename;
mZipInputStreamFactory = zipInputStreamFactory;
}
public ZipFileIter iterator() throws IOException {
GpxZipInputStream zipInputStream = mZipInputStreamFactory.create(mFilename);
return new ZipFileIter(zipInputStream);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.ui.ContentSelector;
import android.app.Activity;
import android.content.SharedPreferences;
import android.widget.Spinner;
public class GeoBeagleBuilder {
private final Activity mActivity;
public GeoBeagleBuilder(Activity context) {
mActivity = context;
}
public ContentSelector createContentSelector(SharedPreferences preferences) {
return new ContentSelector((Spinner)mActivity.findViewById(R.id.content_provider),
preferences);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.LocationControl.LocationChooser;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheFactory;
import com.google.code.geobeagle.data.GeocacheFromPreferencesFactory;
import com.google.code.geobeagle.data.Geocache.Source;
import com.google.code.geobeagle.intents.GeocacheToCachePage;
import com.google.code.geobeagle.intents.GeocacheToGoogleMap;
import com.google.code.geobeagle.intents.IntentFactory;
import com.google.code.geobeagle.intents.IntentStarterLocation;
import com.google.code.geobeagle.intents.IntentStarterRadar;
import com.google.code.geobeagle.intents.IntentStarterViewUri;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI;
import com.google.code.geobeagle.io.LocationSaver;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
import com.google.code.geobeagle.ui.CacheListDelegate;
import com.google.code.geobeagle.ui.ContentSelector;
import com.google.code.geobeagle.ui.EditCacheActivity;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheListOnClickListener;
import com.google.code.geobeagle.ui.GeocacheViewer;
import com.google.code.geobeagle.ui.GetCoordsToast;
import com.google.code.geobeagle.ui.GpsStatusWidget;
import com.google.code.geobeagle.ui.Misc;
import com.google.code.geobeagle.ui.MockableTextView;
import com.google.code.geobeagle.ui.MyLocationProvider;
import com.google.code.geobeagle.ui.OnCacheButtonClickListenerBuilder;
import com.google.code.geobeagle.ui.OnContentProviderSelectedListener;
import com.google.code.geobeagle.ui.WebPageAndDetailsButtonEnabler;
import com.google.code.geobeagle.ui.GpsStatusWidget.MeterFormatter;
import com.google.code.geobeagle.ui.GpsStatusWidget.MeterView;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.location.Location;
import android.location.LocationManager;
import android.net.UrlQuerySanitizer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
/*
* Main Activity for GeoBeagle.
*/
public class GeoBeagle extends Activity implements LifecycleManager {
private WebPageAndDetailsButtonEnabler mWebPageButtonEnabler;
private ContentSelector mContentSelector;
private final ErrorDisplayer mErrorDisplayer;
private GeoBeagleDelegate mGeoBeagleDelegate;
private Geocache mGeocache;
private GeocacheFromPreferencesFactory mGeocacheFromPreferencesFactory;
private GeocacheViewer mGeocacheViewer;
private LocationControl mGpsControl;
private final Handler mHandler;
private GeoBeagleLocationListener mLocationListener;
private GpsStatusWidget mLocationViewer;
private final ResourceProvider mResourceProvider;
private final Runnable mUpdateTimeTask = new Runnable() {
public void run() {
mLocationViewer.refreshLocation();
mHandler.postDelayed(mUpdateTimeTask, 100);
}
};
private LocationSaver mLocationSaver;
public GeoBeagle() {
super();
mErrorDisplayer = new ErrorDisplayer(this);
mResourceProvider = new ResourceProvider(this);
mHandler = new Handler();
}
private MockableTextView createTextView(int id) {
return new MockableTextView((TextView)findViewById(id));
}
private void getCoordinatesFromIntent(GeocacheViewer geocacheViewer, Intent intent,
ErrorDisplayer errorDisplayer) {
try {
if (intent.getType() == null) {
final String query = intent.getData().getQuery();
final CharSequence sanitizedQuery = Util.parseHttpUri(query,
new UrlQuerySanitizer(), UrlQuerySanitizer
.getAllButNulAndAngleBracketsLegal());
final CharSequence[] latlon = Util.splitLatLonDescription(sanitizedQuery);
mGeocache = new Geocache(latlon[2], latlon[3], Util.parseCoordinate(latlon[0]),
Util.parseCoordinate(latlon[1]), Source.WEB_URL, null);
mLocationSaver.saveLocation(mGeocache);
geocacheViewer.set(mGeocache);
}
} catch (final Exception e) {
errorDisplayer.displayError("Error: " + e.getMessage());
}
}
public Geocache getGeocache() {
return mGeocache;
}
private boolean maybeGetCoordinatesFromIntent() {
final Intent intent = getIntent();
if (intent != null) {
final String action = intent.getAction();
if (action != null) {
if (action.equals(Intent.ACTION_VIEW)) {
getCoordinatesFromIntent(mGeocacheViewer, intent, mErrorDisplayer);
return true;
} else if (action.equals(CacheListDelegate.SELECT_CACHE)) {
mGeocache = intent.<Geocache> getParcelableExtra("geocache");
mGeocacheViewer.set(mGeocache);
mWebPageButtonEnabler.check();
return true;
}
}
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == 0)
setIntent(data);
}
@Override
public void onCreate(final Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GeoBeagleBuilder builder = new GeoBeagleBuilder(this);
mContentSelector = builder.createContentSelector(getPreferences(Activity.MODE_PRIVATE));
final SQLiteWrapper sqliteWrapper = new SQLiteWrapper(null);
final Database Database = DatabaseDI.create(this);
mLocationSaver = new LocationSaver(Database, sqliteWrapper, DatabaseDI
.createCacheWriter(sqliteWrapper));
mWebPageButtonEnabler = Misc.create(this,
findViewById(R.id.cache_page), findViewById(R.id.cache_details));
mLocationViewer = new GpsStatusWidget(mResourceProvider, new MeterView(
createTextView(R.id.location_viewer), new MeterFormatter()),
createTextView(R.id.provider), createTextView(R.id.lag),
createTextView(R.id.accuracy), createTextView(R.id.status),
new Misc.Time(), new Location(""));
final LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mGpsControl = new LocationControl(locationManager, new LocationChooser());
mLocationListener = new GeoBeagleLocationListener(mGpsControl, mLocationViewer);
final GeocacheFactory geocacheFactory = new GeocacheFactory();
mGeocacheFromPreferencesFactory = new GeocacheFromPreferencesFactory(geocacheFactory);
final TextView gcid = (TextView)findViewById(R.id.gcid);
final TextView gcname = (TextView)findViewById(R.id.gcname);
final TextView gccoords = (TextView)findViewById(R.id.gccoords);
mGeocacheViewer = new GeocacheViewer(gcid, gcname, gccoords);
setCacheClickListeners();
((Button)findViewById(R.id.go_to_list))
.setOnClickListener(new GeocacheListOnClickListener(this));
AppLifecycleManager appLifecycleManager = new AppLifecycleManager(
getPreferences(MODE_PRIVATE), new LifecycleManager[] {
this, new LocationLifecycleManager(mLocationListener, locationManager),
mContentSelector
});
mGeoBeagleDelegate = GeoBeagleDelegate.buildGeoBeagleDelegate(this,
appLifecycleManager, mGeocacheViewer, mErrorDisplayer);
mGeoBeagleDelegate.onCreate();
((Spinner)findViewById(R.id.content_provider))
.setOnItemSelectedListener(new OnContentProviderSelectedListener(
mResourceProvider, new MockableTextView(
(TextView)findViewById(R.id.select_cache_prompt))));
mHandler.removeCallbacks(mUpdateTimeTask);
mHandler.postDelayed(mUpdateTimeTask, 1000);
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(R.string.menu_edit_geocache);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, EditCacheActivity.class);
intent.putExtra("geocache", mGeocache);
startActivityForResult(intent, 0);
return true;
}
@Override
public void onPause() {
super.onPause();
mGeoBeagleDelegate.onPause();
}
public void onPause(Editor editor) {
getGeocache().writeToPrefs(editor);
}
@Override
protected void onResume() {
super.onResume();
mGeoBeagleDelegate.onResume();
maybeGetCoordinatesFromIntent();
mWebPageButtonEnabler.check();
final Location location = mGpsControl.getLocation();
if (location != null)
mLocationListener.onLocationChanged(location);
}
public void onResume(SharedPreferences preferences) {
setGeocache(mGeocacheFromPreferencesFactory.create(preferences));
}
private void setCacheClickListeners() {
IntentFactory intentFactory = new IntentFactory(new UriParser());
GetCoordsToast getCoordsToast = new GetCoordsToast(this);
MyLocationProvider myLocationProvider = new MyLocationProvider(mGpsControl, mErrorDisplayer);
OnCacheButtonClickListenerBuilder cacheClickListenerSetter = new OnCacheButtonClickListenerBuilder(
this, mErrorDisplayer);
cacheClickListenerSetter.set(R.id.object_map, new IntentStarterLocation(this,
mResourceProvider, intentFactory, myLocationProvider, mContentSelector,
R.array.map_objects, getCoordsToast), "");
cacheClickListenerSetter.set(R.id.nearest_objects, new IntentStarterLocation(this,
mResourceProvider, intentFactory, myLocationProvider, mContentSelector,
R.array.nearest_objects, getCoordsToast), "");
cacheClickListenerSetter.set(R.id.maps, new IntentStarterViewUri(this, intentFactory,
mGeocacheViewer, new GeocacheToGoogleMap(mResourceProvider)), "");
cacheClickListenerSetter.set(R.id.cache_page, new IntentStarterViewUri(this, intentFactory,
mGeocacheViewer, new GeocacheToCachePage(mResourceProvider)), "");
cacheClickListenerSetter.set(R.id.radar, new IntentStarterRadar(this, intentFactory),
"\nPlease install the Radar application to use Radar.");
}
void setGeocache(Geocache geocache) {
mGeocache = geocache;
mGeocacheViewer.set(getGeocache());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.content.Intent;
public interface ActivityStarter {
void startActivity(Intent intent);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.ui.GpsStatusWidget;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
/*
* Listener for the Location control.
*/
public class GeoBeagleLocationListener implements LocationListener {
private final LocationControl mLocationControl;
private final GpsStatusWidget mLocationViewer;
public GeoBeagleLocationListener(LocationControl locationControl, GpsStatusWidget gpsStatusWidget) {
mLocationViewer = gpsStatusWidget;
mLocationControl = locationControl;
}
public void onLocationChanged(Location location) {
// Ask the location control to pick the most accurate location (might
// not be this one).
mLocationViewer.setLocation(mLocationControl.getLocation());
}
public void onProviderDisabled(String provider) {
mLocationViewer.setDisabled();
}
public void onProviderEnabled(String provider) {
mLocationViewer.setEnabled();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
mLocationViewer.setStatus(provider, status);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public interface LifecycleManager {
public abstract void onPause(Editor editor);
public abstract void onResume(SharedPreferences preferences);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.content.Context;
public class ResourceProvider {
private final Context mContext;
public ResourceProvider(Context context) {
mContext = context;
}
public String getString(int resourceId) {
return mContext.getString(resourceId);
}
public String[] getStringArray(int resourceId) {
return mContext.getResources().getStringArray(resourceId);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.location.Location;
import android.location.LocationManager;
public class LocationControl {
public static class LocationChooser {
/**
* Choose the better of two locations: If one location is newer and more
* accurate, choose that. (This favors the gps). Otherwise, if one
* location is newer, less accurate, but farther away than the sum of
* the two accuracies, choose that. (This favors the network locator if
* you've driven a distance and haven't been able to get a gps fix yet.)
*/
public Location choose(Location location1, Location location2) {
if (location1 == null)
return location2;
if (location2 == null)
return location1;
if (location2.getTime() > location1.getTime()) {
if (location2.getAccuracy() <= location1.getAccuracy())
return location2;
else if (location1.distanceTo(location2) >= location1.getAccuracy()
+ location2.getAccuracy()) {
return location2;
}
}
return location1;
}
}
private final LocationChooser mLocationChooser;
private final LocationManager mLocationManager;
LocationControl(LocationManager locationManager, LocationChooser locationChooser) {
mLocationManager = locationManager;
mLocationChooser = locationChooser;
}
/*
* (non-Javadoc)
* @see
* com.android.geobrowse.GpsControlI#getLocation(android.content.Context)
*/
public Location getLocation() {
return mLocationChooser.choose(mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER), mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.ui.CacheDetailsOnClickListener;
import com.google.code.geobeagle.ui.ErrorDisplayer;
import com.google.code.geobeagle.ui.GeocacheViewer;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.LayoutInflater;
import android.widget.Button;
public class GeoBeagleDelegate {
static GeoBeagleDelegate buildGeoBeagleDelegate(GeoBeagle parent,
AppLifecycleManager appLifecycleManager, GeocacheViewer geocacheViewer,
ErrorDisplayer errorDisplayer) {
final AlertDialog.Builder cacheDetailsBuilder = new AlertDialog.Builder(parent);
final DialogInterface.OnClickListener cacheDetailsOkListener = new CacheDetailsOnClickListener.OkListener();
final CacheDetailsOnClickListener.Env env = new CacheDetailsOnClickListener.Env(
LayoutInflater.from(parent));
final CacheDetailsOnClickListener cacheDetailsOnClickListener = CacheDetailsOnClickListener
.create(parent, cacheDetailsBuilder, geocacheViewer, errorDisplayer, env);
return new GeoBeagleDelegate(parent, appLifecycleManager, cacheDetailsBuilder,
cacheDetailsOkListener, cacheDetailsOnClickListener, errorDisplayer);
}
private final AppLifecycleManager mAppLifecycleManager;
private final Builder mCacheDetailsBuilder;
private final OnClickListener mCacheDetailsOkListener;
private final CacheDetailsOnClickListener mCacheDetailsOnClickListener;
private final ErrorDisplayer mErrorDisplayer;
private final Activity mParent;
public GeoBeagleDelegate(Activity parent, AppLifecycleManager appLifecycleManager,
Builder cacheDetailsBuilder, OnClickListener cacheDetailsOkListener,
CacheDetailsOnClickListener cacheDetailsOnClickListener, ErrorDisplayer errorDisplayer) {
mParent = parent;
mAppLifecycleManager = appLifecycleManager;
mCacheDetailsBuilder = cacheDetailsBuilder;
mCacheDetailsOkListener = cacheDetailsOkListener;
mCacheDetailsOnClickListener = cacheDetailsOnClickListener;
mErrorDisplayer = errorDisplayer;
}
public void onCreate() {
mCacheDetailsBuilder.setPositiveButton("Ok", mCacheDetailsOkListener);
mCacheDetailsBuilder.create();
((Button)mParent.findViewById(R.id.cache_details))
.setOnClickListener(mCacheDetailsOnClickListener);
}
public void onPause() {
try {
mAppLifecycleManager.onPause();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
public void onResume() {
try {
mAppLifecycleManager.onResume();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.Geocache.Provider;
import com.google.code.geobeagle.data.Geocache.Source;
import android.view.View;
public class WebPageAndDetailsButtonEnabler {
private final View mWebPageButton;
private final View mDetailsButton;
private final GeoBeagle mGeoBeagle;
WebPageAndDetailsButtonEnabler(GeoBeagle geoBeagle, View cachePageButton, View detailsButton) {
mGeoBeagle = geoBeagle;
mWebPageButton = cachePageButton;
mDetailsButton = detailsButton;
}
public void check() {
Geocache geocache = mGeoBeagle.getGeocache();
mDetailsButton.setEnabled(geocache.getSourceType() == Source.GPX);
final Provider contentProvider = geocache.getContentProvider();
mWebPageButton.setEnabled(contentProvider == Provider.GROUNDSPEAK
|| contentProvider == Provider.ATLAS_QUEST);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.Util;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
// TODO: this class needs tests.
public class ErrorDisplayer {
private class DisplayErrorRunnable implements Runnable {
private DisplayErrorRunnable() {
}
public void run() {
mAlertDialogBuilder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
mAlertDialogBuilder.create().show();
}
}
private final Activity mActivity;
private Builder mAlertDialogBuilder;
public ErrorDisplayer(Activity activity) {
mActivity = activity;
}
public void displayError(int resourceId) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(resourceId);
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
public void displayError(int resId, Object... args) {
displayError(String.format((String)mActivity.getText(resId), args));
}
public void displayError(String string) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(string);
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
public void displayErrorAndStack(Exception e) {
displayErrorAndStack("", e);
}
public void displayErrorAndStack(String msg, Exception e) {
mAlertDialogBuilder = new Builder(mActivity);
mAlertDialogBuilder.setMessage(("Error " + msg + ":" + e.toString() + "\n\n" + Util
.getStackTrace(e)));
mActivity.runOnUiThread(new DisplayErrorRunnable());
}
}
| Java |
/**
*
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.R;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class CacheDetailsOnClickListener implements View.OnClickListener {
public static class CacheDetailsLoader {
public String load(Env env, ErrorDisplayer mErrorDisplayer, CharSequence id) {
final String path = "/sdcard/GeoBeagle/" + id + ".html";
try {
FileInputStream fileInputStream = env.createFileInputStream(path);
byte[] buffer = env.createBuffer(fileInputStream.available());
fileInputStream.read(buffer);
fileInputStream.close();
return new String(buffer);
} catch (FileNotFoundException e) {
return "Error opening cache details file '" + path
+ "'. Please try unmounting your sdcard or re-importing the cache file.";
} catch (IOException e) {
return "Error reading cache details file '" + path
+ "'. Please try unmounting your sdcard or re-importing the cache file.";
}
}
}
public static class Env {
LayoutInflater mLayoutInflater;
public Env(LayoutInflater layoutInflater) {
mLayoutInflater = layoutInflater;
}
public byte[] createBuffer(int size) {
return new byte[size];
}
public FileInputStream createFileInputStream(String path) throws FileNotFoundException {
return new FileInputStream(path);
}
MockableView inflate(int resource, ViewGroup root) {
return new MockableView(mLayoutInflater.inflate(R.layout.cache_details, null));
}
}
public static class MockableView {
private final View mView;
public MockableView(View view) {
mView = view;
}
public View findViewById(int id) {
return mView.findViewById(id);
}
public View getView() {
return mView;
}
}
public static class OkListener implements DialogInterface.OnClickListener {
// @Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
public static CacheDetailsOnClickListener create(GeoBeagle geoBeagle,
Builder alertDialogBuilder, GeocacheViewer geocacheViewer,
ErrorDisplayer errorDisplayer, Env env) {
final CacheDetailsLoader cacheDetailsLoader = new CacheDetailsLoader();
return new CacheDetailsOnClickListener(geoBeagle, alertDialogBuilder, geocacheViewer,
errorDisplayer, env, cacheDetailsLoader);
}
private final Builder mAlertDialogBuilder;
private final CacheDetailsLoader mCacheDetailsLoader;
private final Env mEnv;
private final ErrorDisplayer mErrorDisplayer;
private GeoBeagle mGeoBeagle;
public CacheDetailsOnClickListener(GeoBeagle geoBeagle, Builder alertDialogBuilder,
GeocacheViewer geocacheViewer, ErrorDisplayer errorDisplayer, Env env,
CacheDetailsLoader cacheDetailsLoader) {
mAlertDialogBuilder = alertDialogBuilder;
mErrorDisplayer = errorDisplayer;
mEnv = env;
mCacheDetailsLoader = cacheDetailsLoader;
mGeoBeagle = geoBeagle;
}
public void onClick(View v) {
try {
MockableView detailsView = mEnv.inflate(R.layout.cache_details, null);
CharSequence id = mGeoBeagle.getGeocache().getId();
mAlertDialogBuilder.setTitle(id);
mAlertDialogBuilder.setView(detailsView.getView());
WebView webView = (WebView)detailsView.findViewById(R.id.webview);
webView.loadDataWithBaseURL(null, mCacheDetailsLoader.load(mEnv, mErrorDisplayer, id),
"text/html", "utf-8", "about:blank");
mAlertDialogBuilder.create().show();
} catch (Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.CacheListData;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.io.GeocachesSql;
import com.google.code.geobeagle.io.GpxImporter;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener;
import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import java.util.ArrayList;
public class CacheListDelegate {
public static class CacheListOnCreateContextMenuListener implements OnCreateContextMenuListener {
public static class Factory {
public OnCreateContextMenuListener create(GeocacheVectors geocacheVectors) {
return new CacheListOnCreateContextMenuListener(geocacheVectors);
}
}
private final GeocacheVectors mGeocacheVectors;
CacheListOnCreateContextMenuListener(GeocacheVectors geocacheVectors) {
mGeocacheVectors = geocacheVectors;
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterContextMenuInfo acmi = (AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(mGeocacheVectors.get(acmi.position).getId());
menu.add(0, MENU_VIEW, 0, "View");
if (acmi.position > 0)
menu.add(0, MENU_DELETE, 1, "Delete");
}
}
public static final int MENU_DELETE = 0;
public static final int MENU_VIEW = 1;
public static final String SELECT_CACHE = "SELECT_CACHE";
private final Action mActions[];
private final CacheListData mCacheListData;
private final GeocachesSql mGeocachesSql;
private final CacheListOnCreateContextMenuListener.Factory mCreateContextMenuFactory;
private final ErrorDisplayer mErrorDisplayer;
private final GpxImporter mGpxImporter;
private final LocationControl mLocationControl;
private final ListActivity mParent;
private final GeocacheListAdapter mGeocacheListAdapter;
private final GeocacheVectors mGeocacheVectors;
CacheListDelegate(ListActivity parent, GeocachesSql geocachesSql,
LocationControl locationControl, CacheListData cacheListData,
GeocacheVectors geocacheVectors, GeocacheListAdapter geocacheListAdapter,
ErrorDisplayer errorDisplayer, Action[] actions,
CacheListOnCreateContextMenuListener.Factory factory, GpxImporter gpxImporter) {
mParent = parent;
mGeocachesSql = geocachesSql;
mLocationControl = locationControl;
mCacheListData = cacheListData;
mGeocacheVectors = geocacheVectors;
mErrorDisplayer = errorDisplayer;
mActions = actions;
mCreateContextMenuFactory = factory;
mGpxImporter = gpxImporter;
mGeocacheListAdapter = geocacheListAdapter;
}
public boolean onContextItemSelected(MenuItem menuItem) {
try {
AdapterContextMenuInfo adapterContextMenuInfo = (AdapterContextMenuInfo)menuItem
.getMenuInfo();
mActions[menuItem.getItemId()].act(adapterContextMenuInfo.position,
mGeocacheListAdapter);
return true;
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
return false;
}
public void onCreate() {
mParent.setContentView(R.layout.cache_list);
mParent.getListView().setOnCreateContextMenuListener(
mCreateContextMenuFactory.create(mGeocacheVectors));
}
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(R.string.menu_import_gpx);
return true;
}
public void onListItemClick(ListView l, View v, int position, long id) {
try {
mActions[MENU_VIEW].act(position, mGeocacheListAdapter);
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
public boolean onOptionsItemSelected(MenuItem item) {
mGpxImporter.importGpxs(this);
return true;
}
public void onPause() {
try {
mGpxImporter.abort();
} catch (InterruptedException e) {
// Nothing we can do here! There is no chance to communicate to the
// user.
}
}
public void onResume() {
try {
mGeocachesSql.loadNearestCaches();
ArrayList<Geocache> geocaches = mGeocachesSql.getGeocaches();
mCacheListData.add(geocaches, mLocationControl.getLocation());
mParent.setListAdapter(mGeocacheListAdapter);
mParent.setTitle("Nearest Unfound Caches (" + geocaches.size() + " / "
+ mGeocachesSql.getCount() + ")");
} catch (final Exception e) {
mErrorDisplayer.displayErrorAndStack(e);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
public class OnContentProviderSelectedListener implements OnItemSelectedListener {
private final MockableTextView mContentProviderCaption;
private final ResourceProvider mResourceProvider;
public OnContentProviderSelectedListener(ResourceProvider resourceProvider,
MockableTextView contentProviderCaption) {
mResourceProvider = resourceProvider;
mContentProviderCaption = contentProviderCaption;
}
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final String[] objectNames = mResourceProvider.getStringArray(R.array.object_names);
mContentProviderCaption.setText(mResourceProvider.getString(R.string.search_for) + " "
+ objectNames[position] + ":");
}
public void onNothingSelected(AdapterView<?> parent) {
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.data.IGeocacheVector;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
public class GeocacheRowInflater {
public static class GeocacheRowViews {
private final TextView mCache;
private final TextView mDistance;
public GeocacheRowViews(TextView cache, TextView txtDistance) {
mCache = cache;
mDistance = txtDistance;
}
public void set(IGeocacheVector geocacheVector) {
mCache.setText(geocacheVector.getIdAndName());
mDistance.setText(geocacheVector.getFormattedDistance());
}
}
private final LayoutInflater mLayoutInflater;
public GeocacheRowInflater(LayoutInflater layoutInflater) {
mLayoutInflater = layoutInflater;
}
public View inflateIfNecessary(View convertView) {
if (convertView != null) {
return convertView;
}
convertView = mLayoutInflater.inflate(R.layout.cache_row, null);
GeocacheRowViews geocacheRowViews = new GeocacheRowViews(((TextView)convertView
.findViewById(R.id.txt_cache)), ((TextView)convertView.findViewById(R.id.distance)));
convertView.setTag(geocacheRowViews);
return convertView;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.intents.IntentStarter;
import android.content.ActivityNotFoundException;
import android.view.View;
import android.view.View.OnClickListener;
public class CacheButtonOnClickListener implements OnClickListener {
private final IntentStarter mDestinationToIntentFactory;
private final ErrorDisplayer mErrorDisplayer;
private final String mErrorMessage;
public CacheButtonOnClickListener(IntentStarter intentStarter, ErrorDisplayer errorDisplayer,
String errorMessage) {
mDestinationToIntentFactory = intentStarter;
mErrorDisplayer = errorDisplayer;
mErrorMessage = errorMessage;
}
public void onClick(View view) {
try {
mDestinationToIntentFactory.startIntent();
} catch (final ActivityNotFoundException e) {
mErrorDisplayer.displayError("Error: " + e.getMessage() + mErrorMessage);
} catch (final Exception e) {
mErrorDisplayer.displayError("Error: " + e.getMessage());
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MockableButton extends MockableTextView {
private final Button mButton;
public MockableButton(Button button) {
super(button);
mButton = button;
}
public void setOnClickListener(OnClickListener onClickListener) {
mButton.setOnClickListener(onClickListener);
}
@Override
public void setTextColor(int red) {
mButton.setTextColor(red);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import android.content.Context;
import android.content.Intent;
public class ViewAction implements Action {
private final Context mContext;
private final Intent mIntent;
private GeocacheVectors mGeocacheVectors;
ViewAction(GeocacheVectors geocacheVectors, Context context, Intent intent) {
mGeocacheVectors = geocacheVectors;
mContext = context;
mIntent = intent;
}
public void act(int position, GeocacheListAdapter geocacheListAdapter) {
mIntent.putExtra("geocache", mGeocacheVectors.get(position).getGeocache()).setAction(
CacheListDelegate.SELECT_CACHE);
mContext.startActivity(mIntent);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
public class MockableEditText {
private final EditText mEditText;
public MockableEditText(EditText editText) {
mEditText = editText;
}
public CharSequence getText() {
return mEditText.getText();
}
public void setOnFocusChangeListener(OnFocusChangeListener l) {
mEditText.setOnFocusChangeListener(l);
}
public void setText(CharSequence s) {
mEditText.setText(s);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
interface Action {
public void act(int position, GeocacheListAdapter geocacheListAdapter);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.Util;
import com.google.code.geobeagle.data.Geocache;
import android.widget.TextView;
public class GeocacheViewer {
public static final String FNAME_RECENT_LOCATIONS = "RECENT_LOCATIONS";
public static final String PREFS_LOCATION = "Location";
private final TextView mId;
private final TextView mName;
private final TextView mCoords;
public GeocacheViewer(TextView gcid, TextView gcname, TextView gccoords) {
mId = gcid;
mName = gcname;
mCoords = gccoords;
}
public void set(Geocache geocache) {
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mCoords.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()) + ", "
+ Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.intents.IntentStarter;
import android.app.Activity;
import android.widget.Button;
public class OnCacheButtonClickListenerBuilder {
private final Activity mContext;
private final ErrorDisplayer mErrorDisplayer;
public OnCacheButtonClickListenerBuilder(Activity context, ErrorDisplayer errorDisplayer) {
mErrorDisplayer = errorDisplayer;
mContext = context;
}
public void set(int id, IntentStarter intentStarter, String errorString) {
((Button)mContext.findViewById(id)).setOnClickListener(new CacheButtonOnClickListener(
intentStarter, mErrorDisplayer, errorString));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Util;
import com.google.code.geobeagle.data.Geocache;
import com.google.code.geobeagle.io.LocationSaver;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class EditCacheActivityDelegate {
public static class CancelButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
public CancelButtonOnClickListener(Activity activity) {
mActivity = activity;
}
public void onClick(View v) {
// TODO: replace magic number.
mActivity.setResult(-1, null);
mActivity.finish();
}
}
public static class EditCache {
private final EditText mId;
private final EditText mLatitude;
private final EditText mLongitude;
private final EditText mName;
private Geocache mOriginalGeocache;
public EditCache(EditText id, EditText name, EditText latitude, EditText longitude) {
mId = id;
mName = name;
mLatitude = latitude;
mLongitude = longitude;
}
Geocache get() {
return new Geocache(mId.getText(), mName.getText(), Util.parseCoordinate(mLatitude
.getText()), Util.parseCoordinate(mLongitude.getText()), mOriginalGeocache
.getSourceType(), mOriginalGeocache.getSourceName());
}
void set(Geocache geocache) {
mOriginalGeocache = geocache;
mId.setText(geocache.getId());
mName.setText(geocache.getName());
mLatitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLatitude()));
mLongitude.setText(Util.formatDegreesAsDecimalDegreesString(geocache.getLongitude()));
mLatitude.requestFocus();
}
}
public static class SetButtonOnClickListener implements OnClickListener {
private final Activity mActivity;
private final EditCache mGeocacheView;
private final LocationSaver mLocationSaver;
public SetButtonOnClickListener(Activity activity, EditCache editCache,
LocationSaver locationSaver) {
mActivity = activity;
mGeocacheView = editCache;
mLocationSaver = locationSaver;
}
public void onClick(View v) {
Geocache geocache = mGeocacheView.get();
mLocationSaver.saveLocation(geocache);
Intent i = new Intent();
i.setAction(CacheListDelegate.SELECT_CACHE);
i.putExtra("geocache", geocache);
mActivity.setResult(0, i);
mActivity.finish();
}
}
private final CancelButtonOnClickListener mCancelButtonOnClickListener;
private final LocationSaver mLocationSaver;
private final Activity mParent;
public EditCacheActivityDelegate(Activity parent,
CancelButtonOnClickListener cancelButtonOnClickListener, LocationSaver locationSaver) {
mParent = parent;
mCancelButtonOnClickListener = cancelButtonOnClickListener;
mLocationSaver = locationSaver;
}
public void onCreate(Bundle savedInstanceState) {
mParent.setContentView(R.layout.cache_edit);
}
public void onResume() {
Intent intent = mParent.getIntent();
Geocache geocache = intent.<Geocache> getParcelableExtra("geocache");
EditCache editCache = new EditCache((EditText)mParent.findViewById(R.id.edit_id),
(EditText)mParent.findViewById(R.id.edit_name), (EditText)mParent
.findViewById(R.id.edit_latitude), (EditText)mParent
.findViewById(R.id.edit_longitude));
editCache.set(geocache);
SetButtonOnClickListener setButtonOnClickListener = new SetButtonOnClickListener(mParent,
editCache, mLocationSaver);
((Button)mParent.findViewById(R.id.edit_set)).setOnClickListener(setButtonOnClickListener);
Button cancel = (Button)mParent.findViewById(R.id.edit_cancel);
cancel.setOnClickListener(mCancelButtonOnClickListener);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.ui.Misc.Time;
import android.location.Location;
import android.location.LocationProvider;
/**
* @author sng Displays the GPS status (accuracy, availability, etc).
*/
public class GpsStatusWidget {
public static class MeterFormatter {
public int accuracyToBarCount(float accuracy) {
return Math.min(METER_LEFT.length(), (int)(Math.log(Math.max(1, accuracy)) / Math
.log(2)));
}
public String barsToMeterText(int bars) {
return METER_LEFT.substring(METER_LEFT.length() - bars) + "×"
+ METER_RIGHT.substring(0, bars);
}
public int lagToAlpha(long milliseconds) {
return Math.max(128, 255 - (int)(milliseconds >> 3));
}
}
public static class MeterView {
private final MeterFormatter mMeterFormatter;
private final MockableTextView mTextView;
public MeterView(MockableTextView textView, MeterFormatter meterFormatter) {
mTextView = textView;
mMeterFormatter = meterFormatter;
}
public void set(long lag, float accuracy) {
mTextView.setText(mMeterFormatter.barsToMeterText(mMeterFormatter
.accuracyToBarCount(accuracy)));
mTextView.setTextColor(mMeterFormatter.lagToAlpha(lag), 147, 190, 38);
}
}
public final static String METER_LEFT = "····«····‹····";
public final static String METER_RIGHT = "····›····»····";
private float mAccuracy;
private final MockableTextView mAccuracyView;
private final MockableTextView mLag;
private long mLastUpdateTime;
private long mLocationTime;
private final MeterView mMeterView;
private final MockableTextView mProvider;
private final ResourceProvider mResourceProvider;
private final MockableTextView mStatus;
private final Time mTime;
public GpsStatusWidget(ResourceProvider resourceProvider, MeterView meterView,
MockableTextView provider, MockableTextView lag, MockableTextView accuracy,
MockableTextView status, Time time, Location initialLocation) {
mResourceProvider = resourceProvider;
mMeterView = meterView;
mLag = lag;
mAccuracyView = accuracy;
mProvider = provider;
mStatus = status;
mTime = time;
}
public void refreshLocation() {
long currentTime = mTime.getCurrentTime();
long lastUpdateLag = currentTime - mLastUpdateTime;
long locationLag = currentTime - mLocationTime;
mLag.setText((locationLag / 1000 + "s").trim());
mAccuracyView.setText((mAccuracy + "m").trim());
mMeterView.set(lastUpdateLag, mAccuracy);
};
public void setDisabled() {
mStatus.setText("DISABLED");
}
public void setEnabled() {
mStatus.setText("ENABLED");
}
public void setLocation(Location location) {
// TODO: use currentTime for alpha channel, but locationTime for text
// lag.
mLastUpdateTime = mTime.getCurrentTime();
mLocationTime = Math.min(location.getTime(), mLastUpdateTime);
mProvider.setText(location.getProvider());
mAccuracy = location.getAccuracy();
}
public void setStatus(String provider, int status) {
switch (status) {
case LocationProvider.OUT_OF_SERVICE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.out_of_service));
break;
case LocationProvider.AVAILABLE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.available));
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
mStatus.setText(provider + " status: "
+ mResourceProvider.getString(R.string.temporarily_unavailable));
break;
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.io.CacheWriter;
import com.google.code.geobeagle.io.Database;
import com.google.code.geobeagle.io.DatabaseDI.SQLiteWrapper;
public class DeleteAction implements Action {
private final CacheWriter mCacheWriter;
private final Database mDatabase;
private final SQLiteWrapper mSQLiteWrapper;
private final GeocacheVectors mGeocacheVectors;
DeleteAction(Database database, SQLiteWrapper sqliteWrapper, CacheWriter cacheWriter,
GeocacheVectors geocacheVectors, ErrorDisplayer errorDisplayer) {
mGeocacheVectors = geocacheVectors;
mDatabase = database;
mSQLiteWrapper = sqliteWrapper;
mCacheWriter = cacheWriter;
}
public void act(int position, GeocacheListAdapter geocacheListAdapter) {
// TODO: pull sqliteDatabase and then cachewriter up to top level so
// they're shared.
mSQLiteWrapper.openWritableDatabase(mDatabase);
mCacheWriter.deleteCache(mGeocacheVectors.get(position).getId());
mSQLiteWrapper.close();
mGeocacheVectors.remove(position);
geocacheListAdapter.notifyDataSetChanged();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.R;
import android.content.Context;
import android.widget.Toast;
public class GetCoordsToast {
private final Toast mToast;
public GetCoordsToast(Context context) {
mToast = Toast.makeText(context, R.string.get_coords_toast, Toast.LENGTH_LONG);
}
public void show() {
mToast.show();
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.LocationControl;
import com.google.code.geobeagle.R;
import android.location.Location;
public class MyLocationProvider {
private final ErrorDisplayer mErrorDisplayer;
private final LocationControl mLocationControl;
public MyLocationProvider(LocationControl locationControl, ErrorDisplayer errorDisplayer) {
mLocationControl = locationControl;
mErrorDisplayer = errorDisplayer;
}
public Location getLocation() {
Location location = mLocationControl.getLocation();
if (null == location) {
mErrorDisplayer.displayError(R.string.error_cant_get_location);
}
return location;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.data.GeocacheVectors;
import com.google.code.geobeagle.ui.GeocacheRowInflater.GeocacheRowViews;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class GeocacheListAdapter extends BaseAdapter {
private final GeocacheVectors mGeocacheVectors;
private final GeocacheRowInflater mCacheRow;
public GeocacheListAdapter(GeocacheVectors geocacheVectors, GeocacheRowInflater geocacheRowInflater) {
mGeocacheVectors = geocacheVectors;
mCacheRow = geocacheRowInflater;
}
public int getCount() {
return mGeocacheVectors.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mCacheRow.inflateIfNecessary(convertView);
((GeocacheRowViews)convertView.getTag()).set(mGeocacheVectors.get(position));
return convertView;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import android.graphics.Color;
import android.widget.TextView;
public class MockableTextView {
private final TextView mTextView;
public MockableTextView(TextView textView) {
mTextView = textView;
}
public CharSequence getText() {
return mTextView.getText();
}
public void setEnabled(boolean enabled) {
mTextView.setEnabled(enabled);
}
public void setText(CharSequence text) {
mTextView.setText(text);
}
public void setText(int id) {
mTextView.setText(id);
}
public void setTextColor(int color) {
mTextView.setTextColor(color);
}
public void setTextColor(int alpha, int r, int g, int b) {
mTextView.setTextColor(Color.argb(alpha, r, g, b));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.CacheList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
public class GeocacheListOnClickListener implements OnClickListener {
final private Activity mActivity;
public GeocacheListOnClickListener(Activity activity) {
mActivity = activity;
}
protected Intent createIntent(Context context, Class<?> cls) {
return new Intent(context, cls);
}
public void onClick(View v) {
mActivity.startActivity(createIntent(mActivity, CacheList.class));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import com.google.code.geobeagle.LifecycleManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.widget.Spinner;
public class ContentSelector implements LifecycleManager {
private static final String CONTENT_PROVIDER = "ContentProvider";
private final SharedPreferences mPreferences;
private final Spinner mSpinner;
public ContentSelector(Spinner spinner, SharedPreferences sharedPreferences) {
mSpinner = spinner;
mPreferences = sharedPreferences;
}
public int getIndex() {
return mSpinner.getSelectedItemPosition();
}
public void onPause(Editor editor) {
editor.putInt(CONTENT_PROVIDER, mSpinner.getSelectedItemPosition());
}
public void onResume(SharedPreferences preferences) {
mSpinner.setSelection(mPreferences.getInt(CONTENT_PROVIDER, 1));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import android.content.SharedPreferences;
public class AppLifecycleManager {
private final LifecycleManager[] mLifecycleManagers;
private final SharedPreferences mPreferences;
public AppLifecycleManager(SharedPreferences preferences, LifecycleManager[] lifecycleManagers) {
mLifecycleManagers = lifecycleManagers;
mPreferences = preferences;
}
public void onPause() {
final SharedPreferences.Editor editor = mPreferences.edit();
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onPause(editor);
}
editor.commit();
}
public void onResume() {
for (LifecycleManager lifecycleManager : mLifecycleManagers) {
lifecycleManager.onResume(mPreferences);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.Geocache;
public class GeocacheToGoogleMap implements GeocacheToUri {
private final ResourceProvider mResourceProvider;
public GeocacheToGoogleMap(ResourceProvider resourceProvider) {
mResourceProvider = resourceProvider;
}
public String convert(Geocache geocache) {
// "geo:%1$.5f,%2$.5f?name=cachename"
return String.format(mResourceProvider.getString(R.string.map_intent), geocache
.getLatitude(), geocache.getLongitude(), geocache.getIdAndName());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.ui.ContentSelector;
import com.google.code.geobeagle.ui.GetCoordsToast;
import com.google.code.geobeagle.ui.MyLocationProvider;
import android.app.Activity;
import android.content.Intent;
import android.location.Location;
public class IntentStarterLocation implements IntentStarter {
private final Activity mActivity;
private final ContentSelector mContentSelector;
private final GetCoordsToast mGetCoordsToast;
private final IntentFactory mIntentFactory;
private final MyLocationProvider mMyLocationProvider;
private final ResourceProvider mResourceProvider;
private final int mUriId;
public IntentStarterLocation(Activity activity, ResourceProvider resourceProvider,
IntentFactory intentFactory, MyLocationProvider myLocationProvider,
ContentSelector contentSelector, int uriId, GetCoordsToast getCoordsToast) {
mActivity = activity;
mGetCoordsToast = getCoordsToast;
mIntentFactory = intentFactory;
mMyLocationProvider = myLocationProvider;
mResourceProvider = resourceProvider;
mContentSelector = contentSelector;
mUriId = uriId;
}
public void startIntent() {
final Location location = mMyLocationProvider.getLocation();
if (location == null)
return;
mGetCoordsToast.show();
mActivity.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, String.format(
mResourceProvider.getStringArray(mUriId)[mContentSelector.getIndex()], location
.getLatitude(), location.getLongitude())));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.ResourceProvider;
import com.google.code.geobeagle.data.Geocache;
/*
* Convert a Geocache to the cache page url.
*/
public class GeocacheToCachePage implements GeocacheToUri {
private final ResourceProvider mResourceProvider;
public GeocacheToCachePage(ResourceProvider resourceProvider) {
mResourceProvider = resourceProvider;
}
// TODO: move strings into Provider enum.
public String convert(Geocache geocache) {
return String.format(mResourceProvider.getStringArray(R.array.cache_page_url)[geocache
.getContentProvider().toInt()], geocache.getShortId());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.UriParser;
import android.content.Intent;
public class IntentFactory {
private final UriParser mUriParser;
public IntentFactory(UriParser uriParser) {
mUriParser = uriParser;
}
public Intent createIntent(String action) {
return new Intent(action);
}
public Intent createIntent(String action, String uri) {
return new Intent(action, mUriParser.parse(uri));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.data.Geocache;
import android.content.Intent;
public class IntentStarterRadar implements IntentStarter {
private final IntentFactory mIntentFactory;
private final GeoBeagle mGeoBeagle;
public IntentStarterRadar(GeoBeagle geoBeagle, IntentFactory intentFactory) {
mIntentFactory = intentFactory;
mGeoBeagle = geoBeagle;
}
public void startIntent() {
final Geocache geocache = mGeoBeagle.getGeocache();
final Intent intent = mIntentFactory.createIntent("com.google.android.radar.SHOW_RADAR");
intent.putExtra("latitude", (float)geocache.getLatitude());
intent.putExtra("longitude", (float)geocache.getLongitude());
mGeoBeagle.startActivity(intent);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.GeoBeagle;
import com.google.code.geobeagle.ui.GeocacheViewer;
import android.content.Intent;
public class IntentStarterViewUri implements IntentStarter {
private final GeoBeagle mGeoBeagle;
private final GeocacheToUri mGeocacheToUri;
private final IntentFactory mIntentFactory;
public IntentStarterViewUri(GeoBeagle geoBeagle, IntentFactory intentFactory,
GeocacheViewer geocacheViewer, GeocacheToUri geocacheToUri) {
mGeoBeagle = geoBeagle;
mGeocacheToUri = geocacheToUri;
mIntentFactory = intentFactory;
}
public void startIntent() {
mGeoBeagle.startActivity(mIntentFactory.createIntent(Intent.ACTION_VIEW, mGeocacheToUri
.convert(mGeoBeagle.getGeocache())));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
public interface IntentStarter {
public abstract void startIntent();
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.intents;
import com.google.code.geobeagle.data.Geocache;
interface GeocacheToUri {
public String convert(Geocache geocache);
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.ui;
import android.text.Editable;
import android.text.InputFilter;
class StubEditable implements Editable {
private String mString;
public StubEditable(String s) {
mString = s;
}
public Editable append(char arg0) {
return null;
}
public Editable append(CharSequence arg0) {
return null;
}
public Editable append(CharSequence arg0, int arg1, int arg2) {
return null;
}
public char charAt(int index) {
return mString.charAt(index);
}
public void clear() {
}
public void clearSpans() {
}
public Editable delete(int arg0, int arg1) {
return null;
}
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
mString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
public InputFilter[] getFilters() {
return null;
}
public int getSpanEnd(Object arg0) {
return 0;
}
public int getSpanFlags(Object arg0) {
return 0;
}
public <T> T[] getSpans(int arg0, int arg1, Class<T> arg2) {
return null;
}
public int getSpanStart(Object arg0) {
return 0;
}
public Editable insert(int arg0, CharSequence arg1) {
return null;
}
public Editable insert(int arg0, CharSequence arg1, int arg2, int arg3) {
return null;
}
public int length() {
return mString.length();
}
@SuppressWarnings("unchecked")
public int nextSpanTransition(int arg0, int arg1, Class arg2) {
return 0;
}
public void removeSpan(Object arg0) {
}
public Editable replace(int arg0, int arg1, CharSequence arg2) {
return null;
}
public Editable replace(int arg0, int arg1, CharSequence arg2, int arg3, int arg4) {
return null;
}
public void setFilters(InputFilter[] arg0) {
}
public void setSpan(Object arg0, int arg1, int arg2, int arg3) {
}
public CharSequence subSequence(int start, int end) {
return mString.subSequence(start, end);
}
public String toString() {
return mString;
}
}
| Java |
package roboguice.util;
import android.os.Handler;
import android.util.Log;
import java.util.concurrent.*;
/**
* A class similar but unrelated to android's {@link android.os.AsyncTask}.
*
* Unlike AsyncTask, this class properly propagates exceptions.
*
* If you're familiar with AsyncTask and are looking for {@link android.os.AsyncTask#doInBackground(Object[])},
* we've named it {@link #call()} here to conform with java 1.5's {@link java.util.concurrent.Callable} interface.
*
* Current limitations: does not yet handle progress, although it shouldn't be
* hard to add.
*
* @param <ResultT>
*/
public abstract class SafeAsyncTask<ResultT> implements Callable<ResultT> {
protected Handler handler;
protected ThreadFactory threadFactory;
protected FutureTask<Void> future = new FutureTask<Void>( newTask() );
public SafeAsyncTask() {
this.handler = new Handler();
this.threadFactory = Executors.defaultThreadFactory();
}
public SafeAsyncTask( Handler handler ) {
this.handler = handler;
this.threadFactory = Executors.defaultThreadFactory();
}
public SafeAsyncTask( ThreadFactory threadFactory ) {
this.handler = new Handler();
this.threadFactory = threadFactory;
}
public SafeAsyncTask( Handler handler, ThreadFactory threadFactory ) {
this.handler = handler;
this.threadFactory = threadFactory;
}
public void execute() {
threadFactory.newThread( future ).start();
}
public boolean cancel( boolean mayInterruptIfRunning ) {
return future != null && future.cancel(mayInterruptIfRunning);
}
/**
* @throws Exception, captured on passed to onException() if present.
*/
protected void onPreExecute() throws Exception {}
/**
* @param t the result of {@link #call()}
* @throws Exception, captured on passed to onException() if present.
*/
@SuppressWarnings({"UnusedDeclaration"})
protected void onSuccess( ResultT t ) throws Exception {}
/**
* Called when the thread has been interrupted, likely because
* the task was canceled.
*
* By default, calls {@link #onException(Exception)}, but this method
* may be overridden to handle interruptions differently than other
* exceptions.
*
* @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)}
*/
protected void onInterrupted( InterruptedException e ) {
onException(e);
}
/**
* Logs the exception as an Error by default, but this method may
* be overridden by subclasses.
*
* @param e the exception thrown from {@link #onPreExecute()}, {@link #call()}, or {@link #onSuccess(Object)}
* @throws RuntimeException, ignored
*/
protected void onException( Exception e ) throws RuntimeException {
Log.e("roboguice", "Exception caught during background processing", e);
}
/**
* @throws RuntimeException, ignored
*/
protected void onFinally() throws RuntimeException {}
protected Task<ResultT> newTask() {
return new Task<ResultT>(this);
}
protected static class Task<ResultT> implements Callable<Void> {
protected SafeAsyncTask<ResultT> parent;
public Task(SafeAsyncTask parent) {
this.parent = parent;
}
public Void call() throws Exception {
try {
doPreExecute();
doSuccess(doCall());
return null;
} catch( final Exception e ) {
try {
doException(e);
} catch( Exception f ) {
// ignored, throw original instead
}
throw e;
} finally {
doFinally();
}
}
protected void doPreExecute() throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onPreExecute();
return null;
}
});
}
protected ResultT doCall() throws Exception {
return parent.call();
}
protected void doSuccess( final ResultT r ) throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onSuccess(r);
return null;
}
});
}
protected void doException( final Exception e ) throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
if( e instanceof InterruptedException )
parent.onInterrupted((InterruptedException)e);
else
parent.onException(e);
return null;
}
});
}
protected void doFinally() throws Exception {
postToUiThreadAndWait( new Callable<Object>() {
public Object call() throws Exception {
parent.onFinally();
return null;
}
});
}
/**
* Posts the specified runnable to the UI thread using a handler,
* and waits for operation to finish. If there's an exception,
* it captures it and rethrows it.
* @param c the callable to post
* @throws Exception on error
*/
protected void postToUiThreadAndWait( final Callable c ) throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
final Exception[] exceptions = new Exception[1];
// Execute onSuccess in the UI thread, but wait
// for it to complete.
// If it throws an exception, capture that exception
// and rethrow it later.
parent.handler.post( new Runnable() {
public void run() {
try {
c.call();
} catch( Exception e ) {
exceptions[0] = e;
} finally {
latch.countDown();
}
}
});
// Wait for onSuccess to finish
latch.await();
if( exceptions[0] != null )
throw exceptions[0];
}
}
} | Java |
package roboguice.util;
import roboguice.inject.ContextScope;
import android.content.Context;
import com.google.inject.Inject;
import com.google.inject.Provider;
/**
* An extension to {@link Thread} which propogates the current
* Context to the background thread.
*
* Current limitations: any parameters set in the RoboThread are
* ignored other than Runnable. This means that priorities, groups,
* names, etc. won't be honored. Yet.
*/
public class RoboThread extends Thread {
@Inject static public Provider<Context> contextProvider;
@Inject static protected Provider<ContextScope> scopeProvider;
public RoboThread() {
}
public RoboThread(Runnable runnable) {
super(runnable);
}
@Override
public void start() {
final ContextScope scope = scopeProvider.get();
final Context context = contextProvider.get();
// BUG any parameters set in the RoboThread are ignored other than Runnable.
// This means that priorities, groups, names, etc. won't be honored. Yet.
new Thread() {
@Override
public void run() {
try {
scope.enter(context);
RoboThread.this.run();
} finally {
scope.exit(context);
}
}
}.start();
}
} | Java |
package roboguice.util;
import roboguice.inject.ContextScope;
import android.content.Context;
import android.os.Handler;
import com.google.inject.Inject;
import com.google.inject.Provider;
import java.util.concurrent.ThreadFactory;
/**
* Allows injection to happen for tasks that execute in a background thread.
*
* @param <ResultT>
*/
public abstract class RoboAsyncTask<ResultT> extends SafeAsyncTask<ResultT> {
@Inject static protected Provider<Context> contextProvider;
@Inject static protected Provider<ContextScope> scopeProvider;
protected ContextScope scope = scopeProvider.get();
protected Context context = contextProvider.get();
protected RoboAsyncTask() {
}
protected RoboAsyncTask(Handler handler) {
super(handler);
}
protected RoboAsyncTask(Handler handler, ThreadFactory threadFactory) {
super(handler, threadFactory);
}
protected RoboAsyncTask(ThreadFactory threadFactory) {
super(threadFactory);
}
@Override
protected Task<ResultT> newTask() {
return new RoboTask<ResultT>(this);
}
protected class RoboTask<ResultT> extends SafeAsyncTask.Task<ResultT> {
public RoboTask(SafeAsyncTask parent) {
super(parent);
}
@Override
protected ResultT doCall() throws Exception {
try {
scope.enter(context);
return super.doCall();
} finally {
scope.exit(context);
}
}
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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) {
String tagLower = tag.toLowerCase();
int longestMatch = 0;
CacheType result = CacheType.NULL;
for (CacheType cacheType : mCacheTypes.values()) {
if (tagLower.contains(cacheType.getTag()) && cacheType.getTag().length() > longestMatch) {
result = cacheType;
longestMatch = cacheType.getTag().length();
// Necessary to continue the search to find mega-events and
// individual waypoint types.
}
}
return result;
}
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;
} else if (container.equals("Other")) {
return 5;
}
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.Projection;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.Timing;
import com.google.code.geobeagle.activity.map.QueryManager.LoaderImpl;
import com.google.code.geobeagle.activity.map.click.MapClickIntentFactory;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.res.Resources;
import android.util.Log;
import java.util.ArrayList;
public class CachePinsOverlayFactory {
private final CacheItemFactory cacheItemFactory;
private CachePinsOverlay cachePinsOverlay;
private final Activity activity;
private final QueryManager queryManager;
private final Resources resources;
private final LoaderImpl loaderImpl;
private final MapClickIntentFactory mapClickIntentFactory;
@Inject
public CachePinsOverlayFactory(Activity activity,
CacheItemFactory cacheItemFactory,
QueryManager queryManager,
Resources resources,
LoaderImpl loaderImpl,
MapClickIntentFactory mapClickIntentFactory) {
this.resources = resources;
this.activity = activity;
this.cacheItemFactory = cacheItemFactory;
this.mapClickIntentFactory = mapClickIntentFactory;
this.cachePinsOverlay = new CachePinsOverlay(resources, cacheItemFactory, activity,
new ArrayList<Geocache>(), mapClickIntentFactory);
this.queryManager = queryManager;
this.loaderImpl = loaderImpl;
}
public CachePinsOverlay getCachePinsOverlay() {
Log.d("GeoBeagle", "refresh Caches");
Timing timing = new Timing();
GeoMapView geoMapView = (GeoMapView)activity.findViewById(R.id.mapview);
Projection projection = geoMapView.getProjection();
GeoPoint newTopLeft = projection.fromPixels(0, 0);
GeoPoint newBottomRight = projection.fromPixels(geoMapView.getRight(),
geoMapView.getBottom());
timing.start();
if (!queryManager.needsLoading(newTopLeft, newBottomRight))
return cachePinsOverlay;
ArrayList<Geocache> cacheList = queryManager.load(newTopLeft, newBottomRight, loaderImpl);
timing.lap("Loaded caches");
cachePinsOverlay = new CachePinsOverlay(resources, cacheItemFactory, activity, cacheList,
mapClickIntentFactory);
return cachePinsOverlay;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.click;
import com.google.code.geobeagle.activity.map.click.MapClickIntentFactory;
import com.google.code.geobeagle.activity.map.click.MapClickIntentFactoryHoneycomb;
import com.google.code.geobeagle.activity.map.click.MapClickIntentFactoryPreHoneycomb;
import roboguice.config.AbstractAndroidModule;
import android.os.Build;
public class MapModule extends AbstractAndroidModule {
@Override
protected void configure() {
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
bind(MapClickIntentFactory.class).to(MapClickIntentFactoryHoneycomb.class);
} else {
bind(MapClickIntentFactory.class).to(MapClickIntentFactoryPreHoneycomb.class);
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.map;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter;
import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory;
import com.google.code.geobeagle.GraphicsGenerator.IconRenderer;
import com.google.code.geobeagle.GraphicsGenerator.MapViewBitmapCopier;
import com.google.inject.Inject;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
class CacheItemFactory {
private final IconRenderer mIconRenderer;
private final MapViewBitmapCopier mMapViewBitmapCopier;
private final IconOverlayFactory mIconOverlayFactory;
private final DifficultyAndTerrainPainter mDifficultyAndTerrainPainter;
@Inject
CacheItemFactory(MapViewBitmapCopier mapViewBitmapCopier,
IconOverlayFactory iconOverlayFactory, Resources resources,
DifficultyAndTerrainPainter difficultyAndTerrainPainter) {
mIconRenderer = new IconRenderer(resources);
mMapViewBitmapCopier = mapViewBitmapCopier;
mIconOverlayFactory = iconOverlayFactory;
mDifficultyAndTerrainPainter = difficultyAndTerrainPainter;
}
CacheItem createCacheItem(Geocache geocache) {
final CacheItem cacheItem = new CacheItem(geocache.getGeoPoint(), (String)geocache.getId(),
geocache);
final Drawable icon = mIconRenderer.renderIcon(geocache.getDifficulty(), geocache
.getTerrain(), geocache.getCacheType().iconMap(), mIconOverlayFactory.create(
geocache, false), mMapViewBitmapCopier, mDifficultyAndTerrainPainter);
cacheItem.setMarker(icon);
return cacheItem;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.compass.fieldnotes;
import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger.OnClickOk;
import com.google.inject.Inject;
import android.app.Activity;
import android.widget.EditText;
public class OnClickOkFactory {
private final CacheLogger cacheLogger;
private final Activity activity;
private final HasGeocache hasGeocache;
@Inject
public OnClickOkFactory(Activity activity, CacheLogger cacheLogger, HasGeocache hasGeocache) {
this.activity = activity;
this.cacheLogger = cacheLogger;
this.hasGeocache = hasGeocache;
}
public OnClickOk create(EditText editText, boolean dnf) {
return new OnClickOk(hasGeocache.get(activity).getId(), editText, cacheLogger, dnf);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.compass.fieldnotes;
import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperCommon;
import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperFile;
import com.google.code.geobeagle.activity.compass.fieldnotes.DialogHelperSms;
import com.google.code.geobeagle.activity.compass.fieldnotes.FieldnoteLogger;
import com.google.inject.Inject;
import android.content.SharedPreferences;
public class FieldnoteLoggerFactory {
private final DialogHelperCommon dialogHelperCommon;
private final DialogHelperFile dialogHelperFile;
private final SharedPreferences sharedPreferences;
@Inject
public FieldnoteLoggerFactory(DialogHelperCommon dialogHelperCommon,
DialogHelperFile dialogHelperFile,
SharedPreferences sharedPreferences) {
this.dialogHelperCommon = dialogHelperCommon;
this.dialogHelperFile = dialogHelperFile;
this.sharedPreferences = sharedPreferences;
}
public FieldnoteLogger create(DialogHelperSms dialogHelperSms) {
return new FieldnoteLogger(dialogHelperCommon, dialogHelperFile, dialogHelperSms,
sharedPreferences);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.compass.fieldnotes;
import com.google.inject.Inject;
public class DialogHelperSmsFactory {
private final FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf;
@Inject
public DialogHelperSmsFactory(FieldnoteStringsFVsDnf fieldnoteStringsFVsDnf) {
this.fieldnoteStringsFVsDnf = fieldnoteStringsFVsDnf;
}
public DialogHelperSms create(int geocacheIdLength, boolean dnf) {
return new DialogHelperSms(fieldnoteStringsFVsDnf, geocacheIdLength, dnf);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.compass;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.inject.Inject;
import android.content.SharedPreferences;
public class GeocacheFromPreferencesFactory {
private final GeocacheFactory mGeocacheFactory;
@Inject
public GeocacheFromPreferencesFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(SharedPreferences preferences) {
final int iSource = preferences.getInt(Geocache.SOURCE_TYPE, -1);
final Source source = mGeocacheFactory.sourceFromInt(Math.max(Source.MIN_SOURCE, Math.min(
iSource, Source.MAX_SOURCE)));
final int iCacheType = preferences.getInt(Geocache.CACHE_TYPE, 0);
final CacheType cacheType = mGeocacheFactory.cacheTypeFromInt(iCacheType);
return mGeocacheFactory.create(preferences.getString(Geocache.ID, "GCMEY7"), preferences
.getString(Geocache.NAME, "Google Falls"), preferences.getFloat(Geocache.LATITUDE, 0),
preferences.getFloat(Geocache.LONGITUDE, 0), source, preferences.getString(
Geocache.SOURCE_NAME, ""), cacheType, preferences.getInt(
Geocache.DIFFICULTY, 0), preferences.getInt(Geocache.TERRAIN, 0),
preferences.getInt(Geocache.CONTAINER, 0), preferences.getBoolean(Geocache.AVAILABLE, true),
preferences.getBoolean(Geocache.ARCHIVED, 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.activity.compass;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.code.geobeagle.activity.compass.Util;
import com.google.code.geobeagle.database.DbFrontend;
import com.google.code.geobeagle.database.LocationSaver;
import com.google.inject.Inject;
import com.google.inject.Provider;
import android.content.Intent;
import android.net.UrlQuerySanitizer;
import android.os.Bundle;
import android.util.Log;
public class GeocacheFromIntentFactory {
static final String GEO_BEAGLE_SAVED_IN_DATABASE = "com.google.code.geobeagle.SavedInDatabase";
private final GeocacheFactory mGeocacheFactory;
private final Provider<DbFrontend> mDbFrontendProvider;
@Inject
GeocacheFromIntentFactory(GeocacheFactory geocacheFactory, Provider<DbFrontend> dbFrontendProvider) {
mGeocacheFactory = geocacheFactory;
mDbFrontendProvider = dbFrontendProvider;
}
Geocache viewCacheFromMapsIntent(Intent intent, LocationSaver locationSaver,
Geocache defaultGeocache) {
Log.d("GeoBeagle", "viewCacheFromMapsIntent: " + intent);
final String query = intent.getData().getQuery();
CharSequence sanitizedQuery = Util.parseHttpUri(query, new UrlQuerySanitizer(),
UrlQuerySanitizer.getAllButNulAndAngleBracketsLegal());
if (sanitizedQuery == null)
return defaultGeocache;
final CharSequence[] latlon = Util
.splitLatLonDescription(sanitizedQuery);
CharSequence cacheId = latlon[2];
Bundle extras = intent.getExtras();
if (extras != null && extras.getBoolean(GEO_BEAGLE_SAVED_IN_DATABASE)) {
Log.d("GeoBeagle", "Loading from database: " + cacheId);
return mDbFrontendProvider.get().getCache(cacheId);
}
final Geocache geocache = mGeocacheFactory.create(cacheId, latlon[3],
Util.parseCoordinate(latlon[0]), Util
.parseCoordinate(latlon[1]), Source.WEB_URL, null,
CacheType.NULL, 0, 0, 0, true, false);
locationSaver.saveLocation(geocache);
intent.putExtra("com.google.code.geobeagle.SavedInDatabase", true);
return geocache;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.compass;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.GraphicsGenerator.DifficultyAndTerrainPainter;
import com.google.code.geobeagle.GraphicsGenerator.IconOverlayFactory;
import com.google.code.geobeagle.GraphicsGenerator.IconRenderer;
import com.google.code.geobeagle.GraphicsGenerator.MapViewBitmapCopier;
import com.google.code.geobeagle.GraphicsGenerator.RatingsArray;
import com.google.code.geobeagle.activity.cachelist.view.NameFormatter;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.AttributeViewer;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.NameViewer;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.ResourceImages;
import com.google.inject.Inject;
import android.app.Activity;
import android.content.res.Resources;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.Arrays;
public class GeocacheViewerFactory {
private final IconOverlayFactory iconOverlayFactory;
private final NameFormatter nameFormatter;
private final Resources resources;
private final RatingsArray ratingsArray;
private final MapViewBitmapCopier mapViewBitmapCopier;
private final DifficultyAndTerrainPainter difficultyAndTerrainPainter;
private final IconRenderer iconRenderer;
private final Activity activity;
@Inject
GeocacheViewerFactory(IconOverlayFactory iconOverlayFactory,
NameFormatter nameFormatter,
Resources resources,
RatingsArray ratingsArray,
MapViewBitmapCopier mapViewBitmapCopier,
DifficultyAndTerrainPainter difficultyAndTerrainPainter,
IconRenderer iconRenderer,
Activity activity) {
this.iconOverlayFactory = iconOverlayFactory;
this.nameFormatter = nameFormatter;
this.resources = resources;
this.ratingsArray = ratingsArray;
this.mapViewBitmapCopier = mapViewBitmapCopier;
this.difficultyAndTerrainPainter = difficultyAndTerrainPainter;
this.iconRenderer = iconRenderer;
this.activity = activity;
}
GeocacheViewer create(HasViewById hasViewById) {
RadarView radarView = (RadarView)hasViewById.findViewById(R.id.radarview);
radarView.setUseImperial(false);
radarView.setDistanceView((TextView)hasViewById.findViewById(R.id.radar_distance),
(TextView)hasViewById.findViewById(R.id.radar_bearing),
(TextView)hasViewById.findViewById(R.id.radar_accuracy));
TextView textViewName = (TextView)hasViewById.findViewById(R.id.gcname);
ImageView cacheTypeImageView = (ImageView)hasViewById.findViewById(R.id.gcicon);
NameViewer gcName = new NameViewer(textViewName, nameFormatter);
AttributeViewer gcDifficulty = CompassActivityModule.getLabelledAttributeViewer(
hasViewById, resources, ratingsArray, new int[] {
R.drawable.ribbon_unselected_dark, R.drawable.ribbon_half_bright,
R.drawable.ribbon_selected_bright
}, R.id.gc_difficulty, R.id.gc_text_difficulty);
AttributeViewer gcTerrain = CompassActivityModule.getLabelledAttributeViewer(hasViewById,
resources, ratingsArray, new int[] {
R.drawable.paw_unselected_dark, R.drawable.paw_half_light,
R.drawable.paw_selected_light
}, R.id.gc_terrain, R.id.gc_text_terrain);
ResourceImages gcContainer = new ResourceImages(
(TextView)hasViewById.findViewById(R.id.gc_text_container),
(ImageView)hasViewById.findViewById(R.id.gccontainer),
Arrays.asList(GeocacheViewer.CONTAINER_IMAGES));
return new GeocacheViewer(radarView, activity, gcName, cacheTypeImageView, gcDifficulty,
gcTerrain, gcContainer, iconOverlayFactory, mapViewBitmapCopier, iconRenderer,
difficultyAndTerrainPainter);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.compass;
import com.google.code.geobeagle.ErrorDisplayer;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache;
import com.google.code.geobeagle.activity.compass.intents.GeocacheToGoogleGeo;
import com.google.code.geobeagle.activity.compass.intents.IntentStarter;
import com.google.code.geobeagle.activity.compass.intents.IntentStarterGeo;
import com.google.code.geobeagle.activity.compass.intents.IntentStarterViewUri;
import com.google.code.geobeagle.activity.compass.menuactions.NavigateOnClickListener;
import com.google.code.geobeagle.activity.compass.view.install_radar.InstallRadarAppDialog;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
public class ChooseNavDialogProvider implements Provider<ChooseNavDialog> {
private final ErrorDisplayer errorDisplayer;
private final Activity activity;
private final Provider<Resources> resourcesProvider;
private final Provider<Context> contextProvider;
private final Provider<InstallRadarAppDialog> installRadarAppDialogProvider;
private final HasGeocache hasGeocache;
@Inject
public ChooseNavDialogProvider(Injector injector) {
errorDisplayer = injector.getInstance(ErrorDisplayer.class);
activity = injector.getInstance(Activity.class);
resourcesProvider = injector.getProvider(Resources.class);
contextProvider = injector.getProvider(Context.class);
installRadarAppDialogProvider = injector.getProvider(InstallRadarAppDialog.class);
hasGeocache = injector.getInstance(HasGeocache.class);
}
@Override
public ChooseNavDialog get() {
GeocacheToGoogleGeo geocacheToGoogleMaps = new GeocacheToGoogleGeo(resourcesProvider,
R.string.google_maps_intent);
GeocacheToGoogleGeo geocacheToNavigate = new GeocacheToGoogleGeo(resourcesProvider,
R.string.navigate_intent);
IntentStarterGeo intentStarterRadar = new IntentStarterGeo(activity, new Intent(
"com.google.android.radar.SHOW_RADAR"), hasGeocache);
IntentStarterViewUri intentStarterGoogleMaps = new IntentStarterViewUri(activity,
geocacheToGoogleMaps, errorDisplayer, hasGeocache);
IntentStarterViewUri intentStarterNavigate = new IntentStarterViewUri(activity,
geocacheToNavigate, errorDisplayer, hasGeocache);
IntentStarter[] intentStarters = {
intentStarterRadar, intentStarterGoogleMaps, intentStarterNavigate
};
OnClickListener onClickListener = new NavigateOnClickListener(intentStarters,
installRadarAppDialogProvider.get());
return new ChooseNavDialog(new AlertDialog.Builder(contextProvider.get())
.setItems(R.array.select_nav_choices, onClickListener)
.setTitle(R.string.select_nav_choices_title).create());
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.compass;
import com.google.code.geobeagle.GraphicsGenerator.RatingsArray;
import com.google.code.geobeagle.R;
import com.google.code.geobeagle.activity.compass.fieldnotes.ActivityWithGeocache;
import com.google.code.geobeagle.activity.compass.fieldnotes.FragmentWithGeocache;
import com.google.code.geobeagle.activity.compass.fieldnotes.HasGeocache;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.AttributeViewer;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.LabelledAttributeViewer;
import com.google.code.geobeagle.activity.compass.view.GeocacheViewer.UnlabelledAttributeViewer;
import com.google.inject.Provides;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import roboguice.config.AbstractAndroidModule;
import android.app.Activity;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.widget.ImageView;
import android.widget.TextView;
public class CompassActivityModule extends AbstractAndroidModule {
@Override
protected void configure() {
bind(ChooseNavDialog.class).toProvider(ChooseNavDialogProvider.class);
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
bind(CompassFragtivityOnCreateHandler.class).to(CompassFragmentOnCreateHandler.class);
bind(HasGeocache.class).to(FragmentWithGeocache.class);
} else {
bind(CompassFragtivityOnCreateHandler.class).to(CompassActivityOnCreateHandler.class);
bind(HasGeocache.class).to(ActivityWithGeocache.class);
}
}
private static UnlabelledAttributeViewer getImagesOnDifficulty(final Drawable[] pawDrawables,
ImageView imageView, RatingsArray ratingsArray) {
return new UnlabelledAttributeViewer(imageView, ratingsArray.getRatings(pawDrawables, 10));
}
@Provides
RadarView providesRadarView(Activity activity) {
RadarView radarView = (RadarView)activity.findViewById(R.id.radarview);
radarView.setUseImperial(false);
radarView.setDistanceView((TextView)activity.findViewById(R.id.radar_distance),
(TextView)activity.findViewById(R.id.radar_bearing), (TextView)activity
.findViewById(R.id.radar_accuracy));
return radarView;
}
@Provides
XmlPullParser providesXmlPullParser() throws XmlPullParserException {
return XmlPullParserFactory.newInstance().newPullParser();
}
static AttributeViewer getLabelledAttributeViewer(HasViewById activity, Resources resources,
RatingsArray ratingsArray, int[] resourceIds, int difficultyId, int labelId) {
final ImageView imageViewTerrain = (ImageView)activity.findViewById(difficultyId);
final Drawable[] pawDrawables = {
resources.getDrawable(resourceIds[0]), resources.getDrawable(resourceIds[1]),
resources.getDrawable(resourceIds[2]),
};
final AttributeViewer pawImages = getImagesOnDifficulty(pawDrawables, imageViewTerrain,
ratingsArray);
final AttributeViewer gcTerrain = new LabelledAttributeViewer((TextView)activity
.findViewById(labelId), pawImages);
return gcTerrain;
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY 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.compass;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.inject.Inject;
import android.os.Bundle;
import android.os.Parcel;
public class GeocacheFromParcelFactory {
private final GeocacheFactory mGeocacheFactory;
@Inject
public GeocacheFromParcelFactory(GeocacheFactory geocacheFactory) {
mGeocacheFactory = geocacheFactory;
}
public Geocache create(Parcel in) {
return createFromBundle(in.readBundle());
}
public Geocache createFromBundle(Bundle bundle) {
return mGeocacheFactory.create(bundle.getCharSequence(Geocache.ID), bundle
.getCharSequence(Geocache.NAME), bundle.getDouble(Geocache.LATITUDE), bundle
.getDouble(Geocache.LONGITUDE), mGeocacheFactory.sourceFromInt(bundle
.getInt(Geocache.SOURCE_TYPE)), bundle.getString(Geocache.SOURCE_NAME),
mGeocacheFactory.cacheTypeFromInt(bundle.getInt(Geocache.CACHE_TYPE)), bundle
.getInt(Geocache.DIFFICULTY), bundle.getInt(Geocache.TERRAIN), bundle
.getInt(Geocache.CONTAINER), bundle.getBoolean(Geocache.AVAILABLE), bundle
.getBoolean(Geocache.ARCHIVED));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist.model;
import com.google.code.geobeagle.CacheType;
import com.google.code.geobeagle.Geocache;
import com.google.code.geobeagle.GeocacheFactory;
import com.google.code.geobeagle.LocationControlBuffered;
import com.google.code.geobeagle.GeocacheFactory.Source;
import com.google.inject.Inject;
import android.location.Location;
public class GeocacheFromMyLocationFactory {
private final GeocacheFactory mGeocacheFactory;
private final LocationControlBuffered mLocationControl;
@Inject
public GeocacheFromMyLocationFactory(GeocacheFactory geocacheFactory,
LocationControlBuffered locationControl) {
mGeocacheFactory = geocacheFactory;
mLocationControl = locationControl;
}
public Geocache create() {
Location location = mLocationControl.getLocation();
if (location == null) {
return null;
}
long time = location.getTime();
return mGeocacheFactory.create(String.format("ML%1$tk%1$tM%1$tS", time), String.format(
"[%1$tk:%1$tM] My Location", time), location.getLatitude(),
location.getLongitude(), Source.MY_LOCATION, null, CacheType.MY_LOCATION, 0, 0, 0,
true, 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.activity.cachelist;
import com.google.code.geobeagle.CacheListActivityStarterHoneycomb;
import com.google.code.geobeagle.CacheListActivityStarter;
import com.google.code.geobeagle.CacheListActivityStarterPreHoneycomb;
import com.google.code.geobeagle.activity.cachelist.actions.menu.CompassFrameHider;
import com.google.code.geobeagle.activity.cachelist.actions.menu.HoneycombCompassFrameHider;
import com.google.code.geobeagle.activity.cachelist.actions.menu.NullCompassFrameHider;
import com.google.code.geobeagle.activity.cachelist.presenter.AbsoluteBearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.BearingFormatter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
import com.google.code.geobeagle.activity.cachelist.presenter.ListActivityOnCreateHandler;
import com.google.code.geobeagle.activity.cachelist.presenter.ListFragmentOnCreateHandler;
import com.google.code.geobeagle.activity.cachelist.presenter.ListFragtivityOnCreateHandler;
import com.google.code.geobeagle.activity.cachelist.presenter.RelativeBearingFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatter;
import com.google.code.geobeagle.formatting.DistanceFormatterImperial;
import com.google.code.geobeagle.formatting.DistanceFormatterMetric;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import roboguice.config.AbstractAndroidModule;
import android.content.SharedPreferences;
import android.os.Build;
public class CacheListModule extends AbstractAndroidModule {
@Override
protected void configure() {
bind(ActionManager.class).toProvider(ActionManagerProvider.class).in(Singleton.class);
bind(DistanceFormatter.class).toProvider(DistanceFormatterProvider.class);
bind(BearingFormatter.class).toProvider(BearingFormatterProvider.class);
int sdkVersion = Integer.parseInt(Build.VERSION.SDK);
if (sdkVersion >= Build.VERSION_CODES.HONEYCOMB) {
bind(ListFragtivityOnCreateHandler.class).to(ListFragmentOnCreateHandler.class);
bind(CompassFrameHider.class).to(HoneycombCompassFrameHider.class);
bind(CacheListActivityStarter.class).to(CacheListActivityStarterHoneycomb.class);
bind(ViewMenuAdder.class).to(ViewMenuAdderHoneycomb.class);
} else {
bind(ListFragtivityOnCreateHandler.class).to(ListActivityOnCreateHandler.class);
bind(CompassFrameHider.class).to(NullCompassFrameHider.class);
bind(CacheListActivityStarter.class).to(CacheListActivityStarterPreHoneycomb.class);
bind(ViewMenuAdder.class).to(ViewMenuAdderPreHoneycomb.class);
}
}
static class DistanceFormatterProvider implements Provider<DistanceFormatter> {
private final SharedPreferences preferenceManager;
private final DistanceFormatterMetric distanceFormatterMetric;
private final DistanceFormatterImperial distanceFormatterImperial;
@Inject
DistanceFormatterProvider(SharedPreferences preferenceManager) {
this.preferenceManager = preferenceManager;
this.distanceFormatterMetric = new DistanceFormatterMetric();
this.distanceFormatterImperial = new DistanceFormatterImperial();
}
@Override
public DistanceFormatter get() {
return preferenceManager.getBoolean("imperial", false) ? distanceFormatterImperial
: distanceFormatterMetric;
}
}
static class BearingFormatterProvider implements Provider<BearingFormatter> {
private final AbsoluteBearingFormatter absoluteBearingFormatter;
private final RelativeBearingFormatter relativeBearingFormatter;
private final SharedPreferences preferenceManager;
@Inject
BearingFormatterProvider(SharedPreferences preferenceManager) {
this.preferenceManager = preferenceManager;
this.absoluteBearingFormatter = new AbsoluteBearingFormatter();
this.relativeBearingFormatter = new RelativeBearingFormatter();
}
@Override
public BearingFormatter get() {
return preferenceManager.getBoolean("absolute-bearing", false) ? absoluteBearingFormatter
: relativeBearingFormatter;
}
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist;
import com.google.inject.Inject;
public class SearchWhereFactory {
private final SearchTarget searchTarget;
@Inject
SearchWhereFactory(SearchTarget searchTarget) {
this.searchTarget = searchTarget;
}
public String getWhereString() {
String target = searchTarget.getTarget();
if (target == null)
return "";
return " AND (Id LIKE '%" + target + "%' OR Description LIKE '%" + target + "%')";
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.activity.cachelist;
import com.google.code.geobeagle.GpsDisabledLocation;
import com.google.code.geobeagle.activity.cachelist.presenter.ActionAndTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.AdapterCachesSorter;
import com.google.code.geobeagle.activity.cachelist.presenter.CacheListRefresh.ActionManager;
import com.google.code.geobeagle.activity.cachelist.presenter.DistanceUpdater;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationAndAzimuthTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.LocationTolerance;
import com.google.code.geobeagle.activity.cachelist.presenter.SqlCacheLoader;
import com.google.code.geobeagle.activity.cachelist.presenter.ToleranceStrategy;
import com.google.inject.Inject;
import com.google.inject.Injector;
import com.google.inject.Provider;
class ActionManagerProvider implements Provider<ActionManager> {
private final GpsDisabledLocation gpsDisabledLocation;
private final AdapterCachesSorter adapterCachesSorter;
private final DistanceUpdater distanceUpdater;
private final SqlCacheLoader sqlCacheLoader;
public ActionManagerProvider(GpsDisabledLocation gpsDisabledLocation,
AdapterCachesSorter adapterCachesSorter, DistanceUpdater distanceUpdater,
SqlCacheLoader sqlCacheLoader) {
this.gpsDisabledLocation = gpsDisabledLocation;
this.adapterCachesSorter = adapterCachesSorter;
this.distanceUpdater = distanceUpdater;
this.sqlCacheLoader = sqlCacheLoader;
}
@Inject
public ActionManagerProvider(Injector injector) {
this.gpsDisabledLocation = injector.getInstance(GpsDisabledLocation.class);
this.adapterCachesSorter = injector.getInstance(AdapterCachesSorter.class);
this.distanceUpdater = injector.getInstance(DistanceUpdater.class);
this.sqlCacheLoader = injector.getInstance(SqlCacheLoader.class);
}
@Override
public ActionManager get() {
final ToleranceStrategy sqlCacheLoaderTolerance = new LocationTolerance(500,
gpsDisabledLocation, 10000);
final ToleranceStrategy adapterCachesSorterTolerance = new LocationTolerance(6,
gpsDisabledLocation, 5000);
final LocationTolerance distanceUpdaterLocationTolerance = new LocationTolerance(1,
gpsDisabledLocation, 1000);
final ToleranceStrategy distanceUpdaterTolerance = new LocationAndAzimuthTolerance(
distanceUpdaterLocationTolerance, 720);
final ActionAndTolerance[] actionAndTolerances = new ActionAndTolerance[] {
new ActionAndTolerance(sqlCacheLoader, sqlCacheLoaderTolerance),
new ActionAndTolerance(adapterCachesSorter, adapterCachesSorterTolerance),
new ActionAndTolerance(distanceUpdater, distanceUpdaterTolerance)
};
return new ActionManager(actionAndTolerances);
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpx.zip;
import com.google.code.geobeagle.xmlimport.gpx.zip.GpxZipInputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipInputStream;
public class ZipInputStreamFactory {
public GpxZipInputStream create(String filename) throws IOException {
return new GpxZipInputStream(new ZipInputStream(new BufferedInputStream(
new FileInputStream(filename))));
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.xmlimport.gpx;
import com.google.code.geobeagle.gpx.zip.ZipInputStreamFactory;
import com.google.code.geobeagle.xmlimport.AbortState;
import com.google.code.geobeagle.xmlimport.GeoBeagleEnvironment;
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 com.google.inject.Inject;
import com.google.inject.Provider;
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 Provider<AbortState> mAborterProvider;
private final ZipInputFileTester mZipInputFileTester;
private final GeoBeagleEnvironment mGeoBeagleEnvironment;
@Inject
public GpxFileIterAndZipFileIterFactory(ZipInputFileTester zipInputFileTester,
Provider<AbortState> aborterProvider,
GeoBeagleEnvironment geoBeagleEnvironment) {
mAborterProvider = aborterProvider;
mZipInputFileTester = zipInputFileTester;
mGeoBeagleEnvironment = geoBeagleEnvironment;
}
public IGpxReaderIter fromFile(String filename) throws IOException {
String importFolder = mGeoBeagleEnvironment.getImportFolder();
if (filename.endsWith(".zip")) {
return new ZipFileOpener(importFolder + filename, new ZipInputStreamFactory(),
mZipInputFileTester, mAborterProvider).iterator();
}
return new GpxFileOpener(importFolder + filename, mAborterProvider).iterator();
}
public void resetAborter() {
mAborterProvider.get().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;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import android.util.Log;
import java.util.regex.Pattern;
@Singleton
public class EmotifierPatternProvider implements Provider<Pattern> {
static Pattern createEmotifierPattern(String[] emoticons) {
StringBuffer keysBuffer = new StringBuffer();
String escapeChars = "()|?}^";
for (String emoticon : emoticons) {
String key = new String(emoticon);
for (int i = 0; i < escapeChars.length(); i++) {
char c = escapeChars.charAt(i);
key = key.replaceAll("\\" + String.valueOf(c), "\\\\" + c);
}
keysBuffer.append("|" + key);
}
keysBuffer.deleteCharAt(0);
final String keys = "\\[(" + keysBuffer.toString() + ")\\]";
try {
return Pattern.compile(keys);
} catch (Exception e) {
Log.d("GeoBeagle", e.getLocalizedMessage());
}
return null;
}
private Pattern pattern;
@Override
public Pattern get() {
if (pattern != null)
return pattern;
String emoticons[] = {
":(", ":o)", ":)", ":D", "8D", ":I", ":P", "}:)", ":)", ":D", "8D", ":I", ":P",
"}:)", ";)", "B)", "8", ":)", "8)", ":O", ":(!", "xx(", "|)", ":X", "V", "?",
"^"
};
pattern = createEmotifierPattern(emoticons);
return pattern;
}
} | Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.inject.Provider;
import com.google.inject.matcher.Matchers;
import roboguice.config.RoboGuiceModule;
import roboguice.inject.ActivityProvider;
import roboguice.inject.ContentResolverProvider;
import roboguice.inject.ContextScope;
import roboguice.inject.ContextScoped;
import roboguice.inject.ExtrasListener;
import roboguice.inject.ResourceListener;
import roboguice.inject.ResourcesProvider;
import roboguice.inject.SharedPreferencesProvider;
import roboguice.inject.SystemServiceProvider;
import roboguice.inject.ViewListener;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.location.LocationManager;
import android.os.PowerManager;
import android.view.LayoutInflater;
public class FasterRoboGuiceModule extends RoboGuiceModule {
public FasterRoboGuiceModule(ContextScope contextScope,
Provider<Context> throwingContextProvider, Provider<Context> contextProvider,
ResourceListener resourceListener, ViewListener viewListener,
ExtrasListener extrasListener, Application application) {
super(contextScope, throwingContextProvider, contextProvider, resourceListener,
viewListener, extrasListener, application);
}
@SuppressWarnings("unchecked")
@Override
protected void configure() {
// Sundry Android Classes
bind(Resources.class).toProvider(ResourcesProvider.class);
bind(ContentResolver.class).toProvider(ContentResolverProvider.class);
for (Class<? extends Object> c = application.getClass(); c != null
&& Application.class.isAssignableFrom(c); c = c.getSuperclass()) {
bind((Class<Object>)c).toInstance(application);
}
// System Services
bind(LocationManager.class).toProvider(
new SystemServiceProvider<LocationManager>(Context.LOCATION_SERVICE));
bind(LayoutInflater.class).toProvider(
new SystemServiceProvider<LayoutInflater>(Context.LAYOUT_INFLATER_SERVICE));
bind(ActivityManager.class).toProvider(
new SystemServiceProvider<ActivityManager>(Context.ACTIVITY_SERVICE));
bind(PowerManager.class).toProvider(
new SystemServiceProvider<PowerManager>(Context.POWER_SERVICE));
// Context Scope bindings
bindScope(ContextScoped.class, contextScope);
bind(ContextScope.class).toInstance(contextScope);
bind(Context.class).toProvider(throwingContextProvider).in(ContextScoped.class);
bind(Activity.class).toProvider(ActivityProvider.class);
// Android Resources, Views and extras require special handling
bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)),
resourceListener);
bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)),
viewListener);
bindListener(new ClassToTypeLiteralMatcherAdapter(Matchers.subclassesOf(Activity.class)),
extrasListener);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle.gpsstatuswidget;
import com.google.code.geobeagle.R;
import com.google.inject.Provides;
import roboguice.config.AbstractAndroidModule;
import android.app.Activity;
import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout;
public class GpsStatusWidgetModule extends AbstractAndroidModule {
static InflatedGpsStatusWidget inflatedGpsStatusWidgetCacheList;
@Override
protected void configure() {
}
@Provides
InflatedGpsStatusWidget providesInflatedGpsStatusWidget(Activity activity) {
Context context = activity.getApplicationContext();
InflatedGpsStatusWidget searchOnlineWidget = getInflatedGpsStatusWidgetSearchOnline(activity);
if (searchOnlineWidget != null)
return searchOnlineWidget;
return getInflatedGpsStatusWidgetCacheList(context);
}
InflatedGpsStatusWidget getInflatedGpsStatusWidgetCacheList(Context context) {
if (inflatedGpsStatusWidgetCacheList != null)
return inflatedGpsStatusWidgetCacheList;
inflatedGpsStatusWidgetCacheList = new InflatedGpsStatusWidget(context);
LinearLayout inflatedGpsStatusWidgetParent = new LinearLayout(context);
inflatedGpsStatusWidgetParent.addView(inflatedGpsStatusWidgetCacheList,
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
inflatedGpsStatusWidgetCacheList.setTag(inflatedGpsStatusWidgetParent);
return inflatedGpsStatusWidgetCacheList;
}
InflatedGpsStatusWidget getInflatedGpsStatusWidgetSearchOnline(Activity activity) {
return (InflatedGpsStatusWidget)activity.findViewById(R.id.gps_widget_view);
}
}
| Java |
/*
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
**
** http://www.apache.org/licenses/LICENSE-2.0
**
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*/
package com.google.code.geobeagle;
import com.google.code.geobeagle.CacheTypeFactory;
import com.google.code.geobeagle.Geocache.AttributeFormatter;
import com.google.code.geobeagle.Geocache.AttributeFormatterImpl;
import com.google.code.geobeagle.Geocache.AttributeFormatterNull;
import com.google.code.geobeagle.GeocacheFactory.Source.SourceFactory;
import com.google.code.geobeagle.activity.compass.GeocacheFromParcelFactory;
import android.os.Parcel;
import android.os.Parcelable;
public class GeocacheFactory {
public static class CreateGeocacheFromParcel implements Parcelable.Creator<Geocache> {
private final GeocacheFromParcelFactory mGeocacheFromParcelFactory = new GeocacheFromParcelFactory(
new GeocacheFactory());
@Override
public Geocache createFromParcel(Parcel in) {
return mGeocacheFromParcelFactory.create(in);
}
@Override
public Geocache[] newArray(int size) {
return new Geocache[size];
}
}
public static enum Provider {
ATLAS_QUEST(0, "LB"), GROUNDSPEAK(1, "GC"), MY_LOCATION(-1, "ML"), OPENCACHING(2, "OC"), GEOCACHING_AU(
3, "GA"), GEOCACHING_WP(4, "TP");
private final int mIx;
private final String mPrefix;
Provider(int ix, String prefix) {
mIx = ix;
mPrefix = prefix;
}
public int toInt() {
return mIx;
}
public String getPrefix() {
return mPrefix;
}
}
public static Provider ALL_PROVIDERS[] = {
Provider.ATLAS_QUEST, Provider.GROUNDSPEAK, Provider.MY_LOCATION, Provider.OPENCACHING
};
public static enum Source {
GPX(0), LOC(3), MY_LOCATION(1), WEB_URL(2);
public final static int MIN_SOURCE = 0;
public final static int MAX_SOURCE = 3;
public static class SourceFactory {
private final Source mSources[] = new Source[values().length];
public SourceFactory() {
for (Source source : values())
mSources[source.toInt()] = source;
}
public Source fromInt(int i) {
return mSources[i];
}
}
private final int mIx;
Source(int ix) {
mIx = ix;
}
public int toInt() {
return mIx;
}
}
static class AttributeFormatterFactory {
private AttributeFormatterImpl mAttributeFormatterImpl;
private AttributeFormatterNull mAttributeFormatterNull;
public AttributeFormatterFactory(AttributeFormatterImpl attributeFormatterImpl,
AttributeFormatterNull attributeFormatterNull) {
mAttributeFormatterImpl = attributeFormatterImpl;
mAttributeFormatterNull = attributeFormatterNull;
}
AttributeFormatter getAttributeFormatter(Source sourceType) {
if (sourceType == Source.GPX)
return mAttributeFormatterImpl;
return mAttributeFormatterNull;
}
}
private static CacheTypeFactory mCacheTypeFactory;
private static SourceFactory mSourceFactory;
private AttributeFormatterFactory mAttributeFormatterFactory;
public GeocacheFactory() {
mSourceFactory = new SourceFactory();
mCacheTypeFactory = new CacheTypeFactory();
mAttributeFormatterFactory = new AttributeFormatterFactory(new AttributeFormatterImpl(),
new AttributeFormatterNull());
}
public CacheType cacheTypeFromInt(int cacheTypeIx) {
return mCacheTypeFactory.fromInt(cacheTypeIx);
}
public Geocache create(CharSequence id, CharSequence name, double latitude, double longitude,
Source sourceType, String sourceName, CacheType cacheType, int difficulty, int terrain,
int container, boolean available, boolean archived) {
if (id.length() < 2) {
// ID is missing for waypoints imported from the browser; create a
// new id from the time.
id = String.format("WP%1$tk%1$tM%1$tS", System.currentTimeMillis());
}
if (name == null)
name = "";
final AttributeFormatter attributeFormatter = mAttributeFormatterFactory
.getAttributeFormatter(sourceType);
return new Geocache(id, name, latitude, longitude, sourceType, sourceName, cacheType,
difficulty, terrain, container, attributeFormatter, available, archived);
}
public Source sourceFromInt(int sourceIx) {
return mSourceFactory.fromInt(sourceIx);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.