code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; /** * Given a {@link TrackWriter}, this class manages the process of writing the * data in the track represented by the writer. This includes the display of * a progress dialog, updating the progress bar in said dialog, and notifying * interested parties when the write completes. * * @author Matthew Simmons */ class WriteProgressController { /** * This listener is used to notify interested parties when the write has * completed. */ public interface OnCompletionListener { /** * When this method is invoked, the write has completed, and the progress * dialog has been dismissed. Whether the write succeeded can be * determined by examining the {@link TrackWriter}. */ public void onComplete(); } private final Activity activity; private final TrackWriter writer; private ProgressDialog dialog; private OnCompletionListener onCompletionListener; private final int progressDialogId; /** * @param activity the activity associated with this write * @param writer the writer which writes the track to disk. Note that this * class will use the writer's completion listener. If callers are * interested in notification upon completion of the write, they should * use {@link #setOnCompletionListener}. */ public WriteProgressController(Activity activity, TrackWriter writer, int progressDialogId) { this.activity = activity; this.writer = writer; this.progressDialogId = progressDialogId; writer.setOnCompletionListener(writerCompleteListener); writer.setOnWriteListener(writerWriteListener); } /** Set a listener to be invoked when the write completes. */ public void setOnCompletionListener(OnCompletionListener onCompletionListener) { this.onCompletionListener = onCompletionListener; } // For testing purpose OnCompletionListener getOnCompletionListener() { return onCompletionListener; } public ProgressDialog createProgressDialog() { dialog = new ProgressDialog(activity); dialog.setIcon(android.R.drawable.ic_dialog_info); dialog.setTitle(activity.getString(R.string.generic_progress_title)); dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); dialog.setMessage(activity.getString(R.string.sd_card_progress_write_file)); dialog.setIndeterminate(true); dialog.setOnCancelListener(dialogCancelListener); return dialog; } /** Initiate an asynchronous write. */ public void startWrite() { activity.showDialog(progressDialogId); writer.writeTrackAsync(); } /** VisibleForTesting */ ProgressDialog getDialog() { return dialog; } private final DialogInterface.OnCancelListener dialogCancelListener = new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialogInterface) { writer.stopWriteTrack(); } }; private final TrackWriter.OnCompletionListener writerCompleteListener = new TrackWriter.OnCompletionListener() { @Override public void onComplete() { activity.dismissDialog(progressDialogId); if (onCompletionListener != null) { onCompletionListener.onComplete(); } } }; private final TrackWriter.OnWriteListener writerWriteListener = new TrackWriter.OnWriteListener() { @Override public void onWrite(int number, int max) { if (number % 500 == 0) { dialog.setIndeterminate(false); dialog.setMax(max); dialog.setProgress(Math.min(number, max)); } } }; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.util.FileUtils; import android.os.Environment; import android.util.Log; import java.io.File; /** * A class to clean up old temporary files. * @author Sandor Dornbush */ public class TempFileCleaner { private long currentTimeMillis; public static void clean() { (new TempFileCleaner(System.currentTimeMillis())).cleanImpl(); } // @VisibleForTesting TempFileCleaner(long time) { currentTimeMillis = time; } private void cleanImpl() { if (!Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { return; // Can't do anything now. } cleanTmpDirectory("csv"); cleanTmpDirectory("gpx"); cleanTmpDirectory("kml"); cleanTmpDirectory("tcx"); } private void cleanTmpDirectory(String name) { FileUtils fileUtils = new FileUtils(); String dirName = fileUtils.buildExternalDirectoryPath(name, "tmp"); cleanTmpDirectory(new File(dirName)); } // @VisibleForTesting int cleanTmpDirectory(File dir) { if (!dir.exists()) { return 0; } int count = 0; long oldest = currentTimeMillis - 1000 * 3600; for (File f : dir.listFiles()) { if (f.lastModified() < oldest) { if (!f.delete()) { Log.w(TAG, "Failed to delete file " + f.getAbsolutePath()); } count++; } } return count; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.file.TrackWriterFactory.TrackFileFormat; import com.google.android.apps.mytracks.util.FileUtils; import com.google.android.apps.mytracks.util.StringUtils; import android.location.Location; import android.os.Build; import java.io.OutputStream; import java.io.PrintWriter; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.Date; import java.util.Locale; /** * Log of one track. * * @author Sandor Dornbush */ public class GpxTrackWriter implements TrackFormatWriter { private final NumberFormat elevationFormatter; private final NumberFormat coordinateFormatter; private PrintWriter pw = null; private Track track; public GpxTrackWriter() { // GPX readers expect to see fractional numbers with US-style punctuation. // That is, they want periods for decimal points, rather than commas. elevationFormatter = NumberFormat.getInstance(Locale.US); elevationFormatter.setMaximumFractionDigits(1); elevationFormatter.setGroupingUsed(false); coordinateFormatter = NumberFormat.getInstance(Locale.US); coordinateFormatter.setMaximumFractionDigits(5); coordinateFormatter.setMaximumIntegerDigits(3); coordinateFormatter.setGroupingUsed(false); } private String formatLocation(Location l) { return "lat=\"" + coordinateFormatter.format(l.getLatitude()) + "\" lon=\"" + coordinateFormatter.format(l.getLongitude()) + "\""; } @SuppressWarnings("hiding") @Override public void prepare(Track track, OutputStream out) { this.track = track; this.pw = new PrintWriter(out); } @Override public String getExtension() { return TrackFileFormat.GPX.getExtension(); } @Override public void writeHeader() { if (pw != null) { pw.format("<?xml version=\"1.0\" encoding=\"%s\" standalone=\"yes\"?>\n", Charset.defaultCharset().name()); pw.println("<?xml-stylesheet type=\"text/xsl\" href=\"details.xsl\"?>"); pw.println("<gpx"); pw.println(" version=\"1.1\""); pw.format(" creator=\"My Tracks running on %s\"\n", Build.MODEL); pw.println(" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""); pw.println(" xmlns=\"http://www.topografix.com/GPX/1/1\""); pw.print(" xmlns:topografix=\"http://www.topografix.com/GPX/Private/" + "TopoGrafix/0/1\""); pw.print(" xsi:schemaLocation=\"http://www.topografix.com/GPX/1/1 "); pw.print("http://www.topografix.com/GPX/1/1/gpx.xsd "); pw.print("http://www.topografix.com/GPX/Private/TopoGrafix/0/1 "); pw.println("http://www.topografix.com/GPX/Private/TopoGrafix/0/1/" + "topografix.xsd\">"); // TODO: Author etc. } } @Override public void writeFooter() { if (pw != null) { pw.println("</gpx>"); } } @Override public void writeBeginTrack(Location firstPoint) { if (pw != null) { pw.println("<trk>"); pw.println("<name>" + StringUtils.stringAsCData(track.getName()) + "</name>"); pw.println("<desc>" + StringUtils.stringAsCData(track.getDescription()) + "</desc>"); pw.println("<number>" + track.getId() + "</number>"); pw.println("<extensions><topografix:color>c0c0c0</topografix:color></extensions>"); } } @Override public void writeEndTrack(Location lastPoint) { if (pw != null) { pw.println("</trk>"); } } @Override public void writeOpenSegment() { pw.println("<trkseg>"); } @Override public void writeCloseSegment() { pw.println("</trkseg>"); } @Override public void writeLocation(Location l) { if (pw != null) { pw.println("<trkpt " + formatLocation(l) + ">"); Date d = new Date(l.getTime()); pw.println("<ele>" + elevationFormatter.format(l.getAltitude()) + "</ele>"); pw.println("<time>" + FileUtils.FILE_TIMESTAMP_FORMAT.format(d) + "</time>"); pw.println("</trkpt>"); } } @Override public void close() { if (pw != null) { pw.close(); pw = null; } } @Override public void writeWaypoint(Waypoint waypoint) { if (pw != null) { Location l = waypoint.getLocation(); if (l != null) { pw.println("<wpt " + formatLocation(l) + ">"); pw.println("<ele>" + elevationFormatter.format(l.getAltitude()) + "</ele>"); pw.println("<time>" + FileUtils.FILE_TIMESTAMP_FORMAT.format(l.getTime()) + "</time>"); pw.println("<name>" + StringUtils.stringAsCData(waypoint.getName()) + "</name>"); pw.println("<desc>" + StringUtils.stringAsCData(waypoint.getDescription()) + "</desc>"); pw.println("</wpt>"); } } } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.data.Entry; import java.util.HashMap; import java.util.Map; /** * GData entry for a map feature. */ class MapFeatureEntry extends Entry { private String mPrivacy = null; private Map<String, String> mAttributes = new HashMap<String, String>(); public void setPrivacy(String privacy) { mPrivacy = privacy; } public String getPrivacy() { return mPrivacy; } public void setAttribute(String name, String value) { mAttributes.put(name, value); } public void removeAttribute(String name) { mAttributes.remove(name); } public Map<String, String> getAllAttributes() { return mAttributes; } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.StringUtils; import android.graphics.Color; import android.util.Log; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.io.StringWriter; /** * Converter from GData objects to MyMaps objects. */ class MyMapsGDataConverter { private final XmlSerializer xmlSerializer; public MyMapsGDataConverter() throws XmlPullParserException { xmlSerializer = XmlPullParserFactory.newInstance().newSerializer(); } public static MyMapsMapMetadata getMapMetadataForEntry( MapFeatureEntry entry) { MyMapsMapMetadata metadata = new MyMapsMapMetadata(); if ("public".equals(entry.getPrivacy())) { metadata.setSearchable(true); } else { metadata.setSearchable(false); } metadata.setTitle(entry.getTitle()); String desc = entry.getContent(); if (desc.length() > 12) { metadata.setDescription(desc.substring(9, desc.length() - 3)); } String editUri = entry.getEditUri(); if (editUri != null) { metadata.setGDataEditUri(editUri); } return metadata; } public static String getMapidForEntry(Entry entry) { return MapsClient.getMapIdFromMapEntryId(entry.getId()); } public static Entry getMapEntryForMetadata(MyMapsMapMetadata metadata) { MapFeatureEntry entry = new MapFeatureEntry(); entry.setEditUri(metadata.getGDataEditUri()); entry.setTitle(metadata.getTitle()); entry.setContent(metadata.getDescription()); entry.setPrivacy(metadata.getSearchable() ? "public" : "unlisted"); entry.setAuthor("android"); entry.setEmail("nobody@google.com"); return entry; } public MapFeatureEntry getEntryForFeature(MyMapsFeature feature) { MapFeatureEntry entry = new MapFeatureEntry(); entry.setTitle(feature.getTitle()); entry.setAuthor("android"); entry.setEmail("nobody@google.com"); entry.setCategoryScheme("http://schemas.google.com/g/2005#kind"); entry.setCategory("http://schemas.google.com/g/2008#mapfeature"); entry.setEditUri(""); if (!StringUtils.isEmpty(feature.getAndroidId())) { entry.setAttribute("_androidId", feature.getAndroidId()); } try { StringWriter writer = new StringWriter(); xmlSerializer.setOutput(writer); xmlSerializer.startTag(null, "Placemark"); xmlSerializer.attribute(null, "xmlns", "http://earth.google.com/kml/2.2"); xmlSerializer.startTag(null, "Style"); if (feature.getType() == MyMapsFeature.MARKER) { xmlSerializer.startTag(null, "IconStyle"); xmlSerializer.startTag(null, "Icon"); xmlSerializer.startTag(null, "href"); xmlSerializer.text(feature.getIconUrl()); xmlSerializer.endTag(null, "href"); xmlSerializer.endTag(null, "Icon"); xmlSerializer.endTag(null, "IconStyle"); } else { xmlSerializer.startTag(null, "LineStyle"); xmlSerializer.startTag(null, "color"); int color = feature.getColor(); // Reverse the color because KML is ABGR and Android is ARGB xmlSerializer.text(Integer.toHexString( Color.argb(Color.alpha(color), Color.blue(color), Color.green(color), Color.red(color)))); xmlSerializer.endTag(null, "color"); xmlSerializer.startTag(null, "width"); xmlSerializer.text(Integer.toString(feature.getLineWidth())); xmlSerializer.endTag(null, "width"); xmlSerializer.endTag(null, "LineStyle"); if (feature.getType() == MyMapsFeature.SHAPE) { xmlSerializer.startTag(null, "PolyStyle"); xmlSerializer.startTag(null, "color"); int fcolor = feature.getFillColor(); // Reverse the color because KML is ABGR and Android is ARGB xmlSerializer.text(Integer.toHexString(Color.argb(Color.alpha(fcolor), Color.blue(fcolor), Color.green(fcolor), Color.red(fcolor)))); xmlSerializer.endTag(null, "color"); xmlSerializer.startTag(null, "fill"); xmlSerializer.text("1"); xmlSerializer.endTag(null, "fill"); xmlSerializer.startTag(null, "outline"); xmlSerializer.text("1"); xmlSerializer.endTag(null, "outline"); xmlSerializer.endTag(null, "PolyStyle"); } } xmlSerializer.endTag(null, "Style"); xmlSerializer.startTag(null, "name"); xmlSerializer.text(feature.getTitle()); xmlSerializer.endTag(null, "name"); xmlSerializer.startTag(null, "description"); xmlSerializer.cdsect(feature.getDescription()); xmlSerializer.endTag(null, "description"); StringBuilder pointBuilder = new StringBuilder(); for (int i = 0; i < feature.getPointCount(); ++i) { if (i > 0) { pointBuilder.append('\n'); } pointBuilder.append(feature.getPoint(i).getLongitudeE6() / 1e6); pointBuilder.append(','); pointBuilder.append(feature.getPoint(i).getLatitudeE6() / 1e6); pointBuilder.append(",0.000000"); } String pointString = pointBuilder.toString(); if (feature.getType() == MyMapsFeature.MARKER) { xmlSerializer.startTag(null, "Point"); xmlSerializer.startTag(null, "coordinates"); xmlSerializer.text(pointString); xmlSerializer.endTag(null, "coordinates"); xmlSerializer.endTag(null, "Point"); } else if (feature.getType() == MyMapsFeature.LINE) { xmlSerializer.startTag(null, "LineString"); xmlSerializer.startTag(null, "tessellate"); xmlSerializer.text("1"); xmlSerializer.endTag(null, "tessellate"); xmlSerializer.startTag(null, "coordinates"); xmlSerializer.text(pointString); xmlSerializer.endTag(null, "coordinates"); xmlSerializer.endTag(null, "LineString"); } else { xmlSerializer.startTag(null, "Polygon"); xmlSerializer.startTag(null, "outerBoundaryIs"); xmlSerializer.startTag(null, "LinearRing"); xmlSerializer.startTag(null, "tessellate"); xmlSerializer.text("1"); xmlSerializer.endTag(null, "tessellate"); xmlSerializer.startTag(null, "coordinates"); xmlSerializer.text(pointString + "\n" + Double.toString(feature.getPoint(0).getLongitudeE6() / 1e6) + "," + Double.toString(feature.getPoint(0).getLatitudeE6() / 1e6) + ",0.000000"); xmlSerializer.endTag(null, "coordinates"); xmlSerializer.endTag(null, "LinearRing"); xmlSerializer.endTag(null, "outerBoundaryIs"); xmlSerializer.endTag(null, "Polygon"); } xmlSerializer.endTag(null, "Placemark"); xmlSerializer.flush(); entry.setContent(writer.toString()); Log.d("My Google Maps", "Generated kml:\n" + entry.getContent()); Log.d("My Google Maps", "Edit URI: " + entry.getEditUri()); } catch (IOException e) { e.printStackTrace(); } return entry; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.xml.XmlGDataParser; import com.google.wireless.gdata.parser.xml.XmlParserFactory; import com.google.wireless.gdata.serializer.GDataSerializer; import com.google.wireless.gdata.serializer.xml.XmlEntryGDataSerializer; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import org.xmlpull.v1.XmlPullParserException; /** * Factory of Xml parsers for gdata maps data. */ class XmlMapsGDataParserFactory implements GDataParserFactory { private XmlParserFactory xmlFactory; public XmlMapsGDataParserFactory(XmlParserFactory xmlFactory) { this.xmlFactory = xmlFactory; } @Override public GDataParser createParser(InputStream is) throws ParseException { is = maybeLogCommunication(is); try { return new XmlGDataParser(is, xmlFactory.createParser()); } catch (XmlPullParserException e) { e.printStackTrace(); return null; } } @SuppressWarnings("unchecked") @Override public GDataParser createParser(Class cls, InputStream is) throws ParseException { is = maybeLogCommunication(is); try { return createParserForClass(cls, is); } catch (XmlPullParserException e) { e.printStackTrace(); return null; } } private InputStream maybeLogCommunication(InputStream is) throws ParseException { if (MapsClient.LOG_COMMUNICATION) { StringBuilder builder = new StringBuilder(); byte[] buffer = new byte[2048]; try { for (int n = is.read(buffer); n >= 0; n = is.read(buffer)) { String part = new String(buffer, 0, n); builder.append(part); Log.d("Response part", part); } } catch (IOException e) { throw new ParseException("Could not read stream", e); } String whole = builder.toString(); Log.d("Response", whole); is = new ByteArrayInputStream(whole.getBytes()); } return is; } private GDataParser createParserForClass( Class<? extends Entry> cls, InputStream is) throws ParseException, XmlPullParserException { if (cls == MapFeatureEntry.class) { return new XmlMapsGDataParser(is, xmlFactory.createParser()); } else { return new XmlGDataParser(is, xmlFactory.createParser()); } } @Override public GDataSerializer createSerializer(Entry en) { if (en instanceof MapFeatureEntry) { return new XmlMapsGDataSerializer(xmlFactory, (MapFeatureEntry) en); } else { return new XmlEntryGDataSerializer(xmlFactory, en); } } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.Feed; import com.google.wireless.gdata.data.XmlUtils; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.xml.XmlGDataParser; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Parser for XML gdata maps data. */ class XmlMapsGDataParser extends XmlGDataParser { public XmlMapsGDataParser(InputStream is, XmlPullParser xpp) throws ParseException { super(is, xpp); } @Override protected Feed createFeed() { return new Feed(); } @Override protected Entry createEntry() { return new MapFeatureEntry(); } @Override protected void handleExtraElementInFeed(Feed feed) { // Do nothing } @Override protected void handleExtraLinkInEntry( String rel, String type, String href, Entry entry) throws XmlPullParserException, IOException { if (!(entry instanceof MapFeatureEntry)) { throw new IllegalArgumentException("Expected MapFeatureEntry!"); } if (rel.endsWith("#view")) { return; } super.handleExtraLinkInEntry(rel, type, href, entry); } /** * Parses the current entry in the XML document. Assumes that the parser is * currently pointing just after an &lt;entry&gt;. * * @param plainEntry The entry that will be filled. * @throws XmlPullParserException Thrown if the XML cannot be parsed. * @throws IOException Thrown if the underlying inputstream cannot be read. */ @Override protected void handleEntry(Entry plainEntry) throws XmlPullParserException, IOException, ParseException { XmlPullParser parser = getParser(); if (!(plainEntry instanceof MapFeatureEntry)) { throw new IllegalArgumentException("Expected MapFeatureEntry!"); } MapFeatureEntry entry = (MapFeatureEntry) plainEntry; int eventType = parser.getEventType(); entry.setPrivacy("public"); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_TAG: String name = parser.getName(); if ("entry".equals(name)) { // stop parsing here. return; } else if ("id".equals(name)) { entry.setId(XmlUtils.extractChildText(parser)); } else if ("title".equals(name)) { entry.setTitle(XmlUtils.extractChildText(parser)); } else if ("link".equals(name)) { String rel = parser.getAttributeValue(null /* ns */, "rel"); String type = parser.getAttributeValue(null /* ns */, "type"); String href = parser.getAttributeValue(null /* ns */, "href"); if ("edit".equals(rel)) { entry.setEditUri(href); } else if ("alternate".equals(rel) && "text/html".equals(type)) { entry.setHtmlUri(href); } else { handleExtraLinkInEntry(rel, type, href, entry); } } else if ("summary".equals(name)) { entry.setSummary(XmlUtils.extractChildText(parser)); } else if ("content".equals(name)) { StringBuilder contentBuilder = new StringBuilder(); int parentDepth = parser.getDepth(); while (parser.getEventType() != XmlPullParser.END_DOCUMENT) { int etype = parser.next(); switch (etype) { case XmlPullParser.START_TAG: contentBuilder.append('<'); contentBuilder.append(parser.getName()); contentBuilder.append('>'); break; case XmlPullParser.TEXT: contentBuilder.append("<![CDATA["); contentBuilder.append(parser.getText()); contentBuilder.append("]]>"); break; case XmlPullParser.END_TAG: if (parser.getDepth() > parentDepth) { contentBuilder.append("</"); contentBuilder.append(parser.getName()); contentBuilder.append('>'); } break; } if (etype == XmlPullParser.END_TAG && parser.getDepth() == parentDepth) { break; } } entry.setContent(contentBuilder.toString()); } else if ("category".equals(name)) { String category = parser.getAttributeValue(null /* ns */, "term"); if (category != null && category.length() > 0) { entry.setCategory(category); } String categoryScheme = parser.getAttributeValue(null /* ns */, "scheme"); if (categoryScheme != null && category.length() > 0) { entry.setCategoryScheme(categoryScheme); } } else if ("published".equals(name)) { entry.setPublicationDate(XmlUtils.extractChildText(parser)); } else if ("updated".equals(name)) { entry.setUpdateDate(XmlUtils.extractChildText(parser)); } else if ("deleted".equals(name)) { entry.setDeleted(true); } else if ("draft".equals(name)) { String draft = XmlUtils.extractChildText(parser); entry.setPrivacy("yes".equals(draft) ? "unlisted" : "public"); } else if ("customProperty".equals(name)) { String attrName = parser.getAttributeValue(null, "name"); String attrValue = XmlUtils.extractChildText(parser); entry.setAttribute(attrName, attrValue); } else if ("deleted".equals(name)) { entry.setDeleted(true); } else { handleExtraElementInEntry(entry); } break; default: break; } eventType = parser.next(); } } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.client.GDataServiceClient; import android.util.Log; /** * Client to talk to Google Maps via GData. */ class MapsClient extends GDataServiceClient { private static final boolean DEBUG = false; public static final boolean LOG_COMMUNICATION = false; private static final String MAPS_BASE_FEED_URL = "http://maps.google.com/maps/feeds/"; private static final String MAPS_MAP_FEED_PATH = "maps/default/full"; private static final String MAPS_FEATURE_FEED_PATH_BEFORE_MAPID = "features/"; private static final String MAPS_FEATURE_FEED_PATH_AFTER_MAPID = "/full"; private static final String MAPS_VERSION_FEED_PATH_FORMAT = "%smaps/%s/versions/%s/full/%s"; private static final String MAP_ENTRY_ID_BEFORE_USER_ID = "maps/feeds/maps/"; private static final String MAP_ENTRY_ID_BETWEEN_USER_ID_AND_MAP_ID = "/"; private static final String V2_ONLY_PARAM = "?v=2.0"; public MapsClient(GDataClient dataClient, GDataParserFactory dataParserFactory) { super(dataClient, dataParserFactory); } @Override public String getServiceName() { return MyMapsConstants.SERVICE_NAME; } public static String buildMapUrl(String mapId) { return MyMapsConstants.MAPSHOP_BASE_URL + "?msa=0&msid=" + mapId; } public static String getMapsFeed() { if (DEBUG) { Log.d("Maps Client", "Requesting map feed:"); } return MAPS_BASE_FEED_URL + MAPS_MAP_FEED_PATH + V2_ONLY_PARAM; } public static String getFeaturesFeed(String mapid) { StringBuilder feed = new StringBuilder(); feed.append(MAPS_BASE_FEED_URL); feed.append(MAPS_FEATURE_FEED_PATH_BEFORE_MAPID); feed.append(mapid); feed.append(MAPS_FEATURE_FEED_PATH_AFTER_MAPID); feed.append(V2_ONLY_PARAM); return feed.toString(); } public static String getMapIdFromMapEntryId(String entryId) { String userId = null; String mapId = null; if (DEBUG) { Log.d("Maps GData Client", "Getting mapid from entry id: " + entryId); } int userIdStart = entryId.indexOf(MAP_ENTRY_ID_BEFORE_USER_ID) + MAP_ENTRY_ID_BEFORE_USER_ID.length(); int userIdEnd = entryId.indexOf(MAP_ENTRY_ID_BETWEEN_USER_ID_AND_MAP_ID, userIdStart); if (userIdStart >= 0 && userIdEnd < entryId.length() && userIdStart <= userIdEnd) { userId = entryId.substring(userIdStart, userIdEnd); } int mapIdStart = entryId.indexOf(MAP_ENTRY_ID_BETWEEN_USER_ID_AND_MAP_ID, userIdEnd) + MAP_ENTRY_ID_BETWEEN_USER_ID_AND_MAP_ID.length(); if (mapIdStart >= 0 && mapIdStart < entryId.length()) { mapId = entryId.substring(mapIdStart); } if (userId == null) { userId = ""; } if (mapId == null) { mapId = ""; } if (DEBUG) { Log.d("Maps GData Client", "Got user id: " + userId); Log.d("Maps GData Client", "Got map id: " + mapId); } return userId + "." + mapId; } public static String getVersionFeed(String versionUserId, String versionClient, String currentVersion) { return String.format(MAPS_VERSION_FEED_PATH_FORMAT, MAPS_BASE_FEED_URL, versionUserId, versionClient, currentVersion); } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; /** * Constants for My Maps. */ public class MyMapsConstants { static final String TAG = "MapsApi"; static final String MAPSHOP_BASE_URL = "https://maps.google.com/maps/ms"; public static final String SERVICE_NAME = "local"; /** * Private constructor to prevent instantiation. */ private MyMapsConstants() { } }
Java
// Copyright 2011 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.maps.GeoPoint; import com.google.android.maps.mytracks.R; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import android.content.Context; import android.location.Location; import android.text.TextUtils; import android.util.Log; import java.io.IOException; import java.util.Collection; import org.xmlpull.v1.XmlPullParserException; /** * Single interface which abstracts all access to the Google Maps service. * * @author Rodrigo Damazio */ public class MapsFacade { /** * Interface for receiving data back from getMapsList. * All calls to the interface will happen before getMapsList returns. */ public interface MapsListCallback { void onReceivedMapListing(String mapId, String title, String description, boolean isPublic); } private static final String END_ICON_URL = "http://maps.google.com/mapfiles/ms/micons/red-dot.png"; private static final String START_ICON_URL = "http://maps.google.com/mapfiles/ms/micons/green-dot.png"; private final Context context; private final MyMapsGDataWrapper wrapper; private final MyMapsGDataConverter gdataConverter; private final String authToken; public MapsFacade(Context context, AuthManager auth) { this.context = context; this.authToken = auth.getAuthToken(); wrapper = new MyMapsGDataWrapper(context, auth); wrapper.setRetryOnAuthFailure(true); try { gdataConverter = new MyMapsGDataConverter(); } catch (XmlPullParserException e) { throw new IllegalStateException("Unable to create maps data converter", e); } } public static String buildMapUrl(String mapId) { return MapsClient.buildMapUrl(mapId); } /** * Returns a list of all maps for the current user. * * @param callback callback to call for each map returned * @return true on success, false otherwise */ public boolean getMapsList(final MapsListCallback callback) { return wrapper.runQuery(new MyMapsGDataWrapper.QueryFunction() { @Override public void query(MapsClient client) throws IOException, Exception { GDataParser listParser = client.getParserForFeed( MapFeatureEntry.class, MapsClient.getMapsFeed(), authToken); listParser.init(); while (listParser.hasMoreData()) { MapFeatureEntry entry = (MapFeatureEntry) listParser.readNextEntry(null); MyMapsMapMetadata metadata = MyMapsGDataConverter.getMapMetadataForEntry(entry); String mapId = MyMapsGDataConverter.getMapidForEntry(entry); callback.onReceivedMapListing( mapId, metadata.getTitle(), metadata.getDescription(), metadata.getSearchable()); } listParser.close(); listParser = null; } }); } /** * Creates a new map for the current user. * * @param title title of the map * @param category category of the map * @param description description for the map * @param isPublic whether the map should be public * @param mapIdBuilder builder to append the map ID to * @return true on success, false otherwise */ public boolean createNewMap( final String title, final String category, final String description, final boolean isPublic, final StringBuilder mapIdBuilder) { if (mapIdBuilder.length() > 0) { throw new IllegalArgumentException("mapIdBuilder should be empty"); } return wrapper.runQuery(new MyMapsGDataWrapper.QueryFunction() { @Override public void query(MapsClient client) throws IOException, Exception { Log.d(MyMapsConstants.TAG, "Creating a new map."); String mapFeed = MapsClient.getMapsFeed(); Log.d(MyMapsConstants.TAG, "Map feed is " + mapFeed); MyMapsMapMetadata metaData = new MyMapsMapMetadata(); metaData.setTitle(title); metaData.setDescription(description + " - " + category + " - " + StringUtils.getCreatedByMyTracks(context, false)); metaData.setSearchable(isPublic); Entry entry = MyMapsGDataConverter.getMapEntryForMetadata(metaData); Log.d(MyMapsConstants.TAG, "Title: " + entry.getTitle()); Entry map = client.createEntry(mapFeed, authToken, entry); String mapId = MapsClient.getMapIdFromMapEntryId(map.getId()); mapIdBuilder.append(mapId); Log.d(MyMapsConstants.TAG, "New map id is: " + mapId); } }); } /** * Uploads a single start or end marker to the given map. * * @param mapId ID of the map to upload to * @param trackName name of the track being started/ended * @param trackDescription description of the track being started/ended * @param loc the location of the marker * @param isStart true to add a start marker, false to add an end marker * @return true on success, false otherwise */ public boolean uploadMarker(final String mapId, final String trackName, final String trackDescription, final Location loc, final boolean isStart) { return wrapper.runQuery(new MyMapsGDataWrapper.QueryFunction() { @Override public void query(MapsClient client) throws IOException, Exception { String featureFeed = MapsClient.getFeaturesFeed(mapId); GeoPoint geoPoint = getGeoPoint(loc); insertMarker(client, featureFeed, trackName, trackDescription, geoPoint, isStart); } }); } /** * Inserts a place mark. Second try if 1st try fails. Will throw exception on * 2nd failure. */ private void insertMarker(MapsClient client, String featureFeed, String trackName, String trackDescription, GeoPoint geoPoint, boolean isStart) throws IOException, Exception { MyMapsFeature feature = buildMyMapsPlacemarkFeature(trackName, trackDescription, geoPoint, isStart); Entry entry = gdataConverter.getEntryForFeature(feature); Log.d(MyMapsConstants.TAG, "SendToMyMaps: Creating placemark " + entry.getTitle()); try { client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success!"); } catch (IOException e) { Log.w(MyMapsConstants.TAG, "SendToMyMaps: createEntry 1st try failed. Trying again."); // Retry once (often IOException is thrown on a timeout): client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success on 2nd try!"); } } /** * Builds a placemark MyMapsFeature from a track. * * @param trackName the track * @param trackDescription the track description * @param geoPoint the geo point * @param isStart true if it's the start of the track, or false for end * @return a MyMapsFeature */ private MyMapsFeature buildMyMapsPlacemarkFeature( String trackName, String trackDescription, GeoPoint geoPoint, boolean isStart) { String iconUrl; if (isStart) { iconUrl = START_ICON_URL; } else { iconUrl = END_ICON_URL; } String title = trackName + " " + (isStart ? context.getString(R.string.marker_label_start) : context.getString(R.string.marker_label_end)); String description = isStart ? "" : trackDescription; return buildMyMapsPlacemarkFeature(title, description, iconUrl, geoPoint); } /** * Builds a MyMapsFeature from a waypoint. * * @param title the title * @param description the description * @param iconUrl the icon url * @param geoPoint the waypoint * @return a MyMapsFeature */ private static MyMapsFeature buildMyMapsPlacemarkFeature( String title, String description, String iconUrl, GeoPoint geoPoint) { MyMapsFeature myMapsFeature = new MyMapsFeature(); myMapsFeature.generateAndroidId(); myMapsFeature.setType(MyMapsFeature.MARKER); myMapsFeature.setIconUrl(iconUrl); myMapsFeature.setDescription(description); myMapsFeature.addPoint(geoPoint); if (TextUtils.isEmpty(title)) { // Features must have a name (otherwise GData upload may fail): myMapsFeature.setTitle("-"); } else { myMapsFeature.setTitle(title); } myMapsFeature.setDescription(description.replaceAll("\n", "<br>")); return myMapsFeature; } /** * Uploads a series of waypoints to the given map. * * @param mapId ID of the map to upload to * @param waypoints the waypoints to upload * @return true on success, false otherwise */ public boolean uploadWaypoints( final String mapId, final Iterable<Waypoint> waypoints) { return wrapper.runQuery(new MyMapsGDataWrapper.QueryFunction() { public void query(MapsClient client) { // TODO(rdamazio): Stream through the waypoints in chunks. // I am leaving the number of waypoints very high which should not be a // problem because we don't try to load them into objects all at the // same time. String featureFeed = MapsClient.getFeaturesFeed(mapId); try { for (Waypoint waypoint : waypoints) { MyMapsFeature feature = buildMyMapsPlacemarkFeature( waypoint.getName(), waypoint.getDescription(), waypoint.getIcon(), getGeoPoint(waypoint.getLocation())); Entry entry = gdataConverter.getEntryForFeature(feature); Log.d(MyMapsConstants.TAG, "SendToMyMaps: Creating waypoint."); try { client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success!"); } catch (IOException e) { Log.w(MyMapsConstants.TAG, "SendToMyMaps: createEntry 1st try failed. Retrying."); // Retry once (often IOException is thrown on a timeout): client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success on 2nd try!"); } } } catch (ParseException e) { Log.w(MyMapsConstants.TAG, "ParseException caught.", e); } catch (HttpException e) { Log.w(MyMapsConstants.TAG, "HttpException caught.", e); } catch (IOException e) { Log.w(MyMapsConstants.TAG, "IOException caught.", e); } } }); } /** * Uploads a series of points to the given map. * * @param mapId ID of the map to upload to * @param trackName the name of the track * @param locations the locations to upload * @return true on success, false otherwise */ public boolean uploadTrackPoints( final String mapId, final String trackName, final Collection<Location> locations) { return wrapper.runQuery(new MyMapsGDataWrapper.QueryFunction() { @Override public void query(MapsClient client) throws IOException, Exception { String featureFeed = MapsClient.getFeaturesFeed(mapId); Log.d(MyMapsConstants.TAG, "Feature feed url: " + featureFeed); uploadTrackPoints(client, featureFeed, trackName, locations); } }); } private boolean uploadTrackPoints( MapsClient client, String featureFeed, String trackName, Collection<Location> locations) throws IOException, Exception { Entry entry = null; int numLocations = locations.size(); if (numLocations < 2) { // Need at least two points for a polyline: Log.w(MyMapsConstants.TAG, "Not uploading too few points"); return true; } // Put the line: entry = gdataConverter.getEntryForFeature( buildMyMapsLineFeature(trackName, locations)); Log.d(MyMapsConstants.TAG, "SendToMyMaps: Creating line " + entry.getTitle()); try { client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success!"); } catch (IOException e) { Log.w(MyMapsConstants.TAG, "SendToMyMaps: createEntry 1st try failed. Trying again."); // Retry once (often IOException is thrown on a timeout): client.createEntry(featureFeed, authToken, entry); Log.d(MyMapsConstants.TAG, "SendToMyMaps: createEntry success on 2nd try!"); } return true; } /** * Builds a MyMapsFeature from a track. * * @param trackName the track name * @param locations locations on the track * @return a MyMapsFeature */ private static MyMapsFeature buildMyMapsLineFeature(String trackName, Iterable<Location> locations) { MyMapsFeature myMapsFeature = new MyMapsFeature(); myMapsFeature.generateAndroidId(); myMapsFeature.setType(MyMapsFeature.LINE); if (TextUtils.isEmpty(trackName)) { // Features must have a name (otherwise GData upload may fail): myMapsFeature.setTitle("-"); } else { myMapsFeature.setTitle(trackName); } myMapsFeature.setColor(0x80FF0000); for (Location loc : locations) { myMapsFeature.addPoint(getGeoPoint(loc)); } return myMapsFeature; } /** * Cleans up after a series of uploads. * This closes the connection to Maps and resets retry counters. */ public void cleanUp() { wrapper.cleanUp(); } private static GeoPoint getGeoPoint(Location location) { return new GeoPoint((int) (location.getLatitude() * 1E6), (int) (location.getLongitude() * 1E6)); } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.android.maps.GeoPoint; /** * A rectangle in geographical space. */ class GeoRect { public int top; public int left; public int bottom; public int right; public GeoRect() { top = 0; left = 0; bottom = 0; right = 0; } public GeoRect(GeoPoint center, int latSpan, int longSpan) { top = center.getLatitudeE6() - latSpan / 2; left = center.getLongitudeE6() - longSpan / 2; bottom = center.getLatitudeE6() + latSpan / 2; right = center.getLongitudeE6() + longSpan / 2; } public GeoPoint getCenter() { return new GeoPoint(top / 2 + bottom / 2, left / 2 + right / 2); } public int getLatSpan() { return bottom - top; } public int getLongSpan() { return right - left; } public boolean contains(GeoPoint geoPoint) { if (geoPoint.getLatitudeE6() >= top && geoPoint.getLatitudeE6() <= bottom && geoPoint.getLongitudeE6() >= left && geoPoint.getLongitudeE6() <= right) { return true; } return false; } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.android.maps.GeoPoint; import java.util.Random; import java.util.Vector; /** * MyMapsFeature contains all of the data associated with a feature in My Maps, * where a feature is a marker, line, or shape. Some of the data is stored in a * {@link MyMapsFeatureMetadata} object so that it can be more efficiently * transmitted to other activities. */ class MyMapsFeature { private static final long serialVersionUID = 8439035544430497236L; /** A marker feature displays an icon at a single point on the map. */ public static final int MARKER = 0; /** * A line feature displays a line connecting a set of points on the map. */ public static final int LINE = 1; /** * A shape feature displays a border defined by connecting a set of points, * including connecting the last to the first, and displays the area * confined by this border. */ public static final int SHAPE = 2; /** The local feature id for this feature, if needed. */ private String androidId; /** * The latitudes of the points of this feature in order, specified in * millionths of a degree north. */ private final Vector<Integer> latitudeE6 = new Vector<Integer>(); /** * The longitudes of the points of this feature in order, specified in * millionths of a degree east. */ private final Vector<Integer> longitudeE6 = new Vector<Integer>(); /** The metadata of this feature in a format efficient for transmission. */ private MyMapsFeatureMetadata featureInfo = new MyMapsFeatureMetadata(); private final Random random = new Random(); /** * Initializes a valid but empty feature. It will default to a * {@link #MARKER} with a blue placemark with a dot as an icon at the * location (0, 0). */ public MyMapsFeature() { } /** * Adds a new point to the end of this feature. * * @param point The new point to add */ public void addPoint(GeoPoint point) { latitudeE6.add(point.getLatitudeE6()); longitudeE6.add(point.getLongitudeE6()); } /** * Generates a new local id for this feature based on the current time and * a random number. */ void generateAndroidId() { long time = System.currentTimeMillis(); int rand = random.nextInt(10000); androidId = time + "." + rand; } /** * Retrieves the current local id for this feature if one is available. * * @return The local id for this feature */ String getAndroidId() { return androidId; } /** * Retrieves the current (html) description of this feature. The description * is stored in the feature metadata. * * @return The description of this feature */ public String getDescription() { return featureInfo.getDescription(); } /** * Sets the description of this feature. That description is stored in the * feature metadata. * * @param description The new description of this feature */ public void setDescription(String description) { featureInfo.setDescription(description); } /** * Retrieves the point at the given index for this feature. * * @param index The index of the point desired * @return A {@link GeoPoint} representing the point or null if that point * doesn't exist */ public GeoPoint getPoint(int index) { if (latitudeE6.size() <= index) { return null; } return new GeoPoint(latitudeE6.get(index), longitudeE6.get(index)); } /** * Counts the number of points in this feature and return that count. * * @return The number of points in this feature */ public int getPointCount() { return latitudeE6.size(); } /** * Retrieves the title of this feature. That title is stored in the feature * metadata. * * @return the current title of this feature */ public String getTitle() { return featureInfo.getTitle(); } /** * Retrieves the type of this feature. That type is stored in the feature * metadata. * * @return One of {@link #MARKER}, {@link #LINE}, or {@link #SHAPE} * identifying the type of this feature */ public int getType() { return featureInfo.getType(); } /** * Retrieves the current color of this feature as an ARGB color integer. * That color is stored in the feature metadata. * * @return The ARGB color of this feature */ public int getColor() { return featureInfo.getColor(); } /** * Retrieves the current line width of this feature. That line width is * stored in the feature metadata. * * @return The line width of this feature */ public int getLineWidth() { return featureInfo.getLineWidth(); } /** * Retrieves the current fill color of this feature as an ARGB color * integer. That color is stored in the feature metadata. * * @return The ARGB fill color of this feature */ public int getFillColor() { return featureInfo.getFillColor(); } /** * Retrieves the current icon url of this feature. That icon url is stored * in the feature metadata. * * @return The icon url for this feature */ public String getIconUrl() { return featureInfo.getIconUrl(); } /** * Sets the title of this feature. That title is stored in the feature * metadata. * * @param title The new title of this feature */ public void setTitle(String title) { featureInfo.setTitle(title); } /** * Sets the type of this feature. That type is stored in the feature * metadata. * * @param type The new type of the feature. That type must be one of * {@link #MARKER}, {@link #LINE}, or {@link #SHAPE} */ public void setType(int type) { featureInfo.setType(type); } /** * Sets the ARGB color of this feature. That color is stored in the feature * metadata. * * @param color The new ARGB color of this feature */ public void setColor(int color) { featureInfo.setColor(color); } /** * Sets the icon url of this feature. That icon url is stored in the feature * metadata. * * @param url The new icon url of the feature */ public void setIconUrl(String url) { featureInfo.setIconUrl(url); } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; /** * Metadata about a maps feature. */ class MyMapsFeatureMetadata { private static final String BLUE_DOT_URL = "http://maps.google.com/mapfiles/ms/micons/blue-dot.png"; private static final int DEFAULT_COLOR = 0x800000FF; private static final int DEFAULT_FILL_COLOR = 0xC00000FF; private String title; private String description; private int type; private int color; private int lineWidth; private int fillColor; private String iconUrl; public MyMapsFeatureMetadata() { title = ""; description = ""; type = MyMapsFeature.MARKER; color = DEFAULT_COLOR; lineWidth = 5; fillColor = DEFAULT_FILL_COLOR; iconUrl = BLUE_DOT_URL; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getColor() { return color; } public void setColor(int color) { this.color = color; } public int getLineWidth() { return lineWidth; } public void setLineWidth(int width) { lineWidth = width; } public int getFillColor() { return fillColor; } public void setFillColor(int color) { fillColor = color; } public String getIconUrl() { return iconUrl; } public void setIconUrl(String url) { iconUrl = url; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.android.apps.mytracks.io.AuthManager; import com.google.android.apps.mytracks.io.AuthManager.AuthCallback; import com.google.android.apps.mytracks.io.gdata.GDataClientFactory; import com.google.android.common.gdata.AndroidXmlParserFactory; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.parser.xml.SimplePullParser.ParseException; import com.google.wireless.gdata2.ConflictDetectedException; import com.google.wireless.gdata2.client.AuthenticationException; import android.content.Context; import android.util.Log; import java.io.IOException; /** * MyMapsGDataWrapper provides a wrapper around GData operations that maintains * the GData client, and provides a method to run gdata queries with proper * error handling. After a query is run, the wrapper can be queried about the * error that occurred. */ class MyMapsGDataWrapper { /** * A QueryFunction is passed in when executing a query. The query function * of the class is called with the GData client as a parameter. The * function should execute whatever operations it desires on the client * without concern for whether the client will throw an error. */ interface QueryFunction { public abstract void query(MapsClient client) throws AuthenticationException, IOException, ParseException, ConflictDetectedException, Exception; } // The types of error that may be encountered /** No error occurred. */ public static final int ERROR_NO_ERROR = 0; /** There was an authentication error, the auth token may be invalid. */ public static final int ERROR_AUTH = 1; /** There was an internal error on the server side. */ public static final int ERROR_INTERNAL = 2; /** There was an error connecting to the server. */ public static final int ERROR_CONNECTION = 3; /** The item queried did not exit. */ public static final int ERROR_NOT_FOUND = 4; /** There was an error parsing or serializing locally. */ public static final int ERROR_LOCAL = 5; /** There was a conflict, update the entry and try again. */ public static final int ERROR_CONFLICT = 6; /** * A query was run after cleaning up the wrapper, so the client was invalid. */ public static final int ERROR_CLEANED_UP = 7; /** An unknown error occurred. */ public static final int ERROR_UNKNOWN = 100; private final GDataClient androidGdataClient; private final AuthManager auth; private final MapsClient client; private String errorMessage; private int errorType; private boolean retryOnAuthFailure; private int retriesPending; private boolean cleanupCalled; public MyMapsGDataWrapper(Context context, AuthManager auth) { androidGdataClient = GDataClientFactory.getGDataClient(context); this.auth = auth; client = new MapsClient(androidGdataClient, new XmlMapsGDataParserFactory( new AndroidXmlParserFactory())); errorType = ERROR_NO_ERROR; errorMessage = null; retryOnAuthFailure = false; retriesPending = 0; cleanupCalled = false; } public boolean runQuery(final QueryFunction query) { if (client == null) { errorType = ERROR_CLEANED_UP; errorMessage = "GData Wrapper has already been cleaned up!"; return false; } try { query.query(client); errorType = ERROR_NO_ERROR; errorMessage = null; return true; } catch (AuthenticationException e) { Log.e(MyMapsConstants.TAG, "Exception", e); errorType = ERROR_AUTH; errorMessage = e.getMessage(); } catch (HttpException e) { Log.e(MyMapsConstants.TAG, "HttpException", e); errorMessage = e.getMessage(); if (errorMessage != null && errorMessage.contains("401")) { errorType = ERROR_AUTH; } else { errorType = ERROR_CONNECTION; } } catch (IOException e) { Log.e(MyMapsConstants.TAG, "Exception", e); errorMessage = e.getMessage(); if (errorMessage != null && errorMessage.contains("503")) { errorType = ERROR_INTERNAL; } else { errorType = ERROR_CONNECTION; } } catch (ParseException e) { Log.e(MyMapsConstants.TAG, "Exception", e); errorType = ERROR_LOCAL; errorMessage = e.getMessage(); } catch (ConflictDetectedException e) { Log.e(MyMapsConstants.TAG, "Exception", e); errorType = ERROR_CONFLICT; errorMessage = e.getMessage(); } catch (Exception e) { Log.e(MyMapsConstants.TAG, "Exception", e); errorType = ERROR_UNKNOWN; errorMessage = e.getMessage(); e.printStackTrace(); } Log.d(MyMapsConstants.TAG, "GData error encountered: " + errorMessage); if (errorType == ERROR_AUTH && auth != null) { AuthCallback whenFinished = null; if (retryOnAuthFailure) { retriesPending++; whenFinished = new AuthCallback() { @Override public void onAuthResult(boolean success) { retriesPending--; retryOnAuthFailure = false; runQuery(query); if (cleanupCalled && retriesPending == 0) { cleanUp(); } } }; } auth.invalidateAndRefresh(whenFinished); } return false; } public int getErrorType() { return errorType; } public String getErrorMessage() { return errorMessage; } // cleanUp must be called when done using this wrapper to close the client. // Note that the cleanup will be delayed if auth failure retries were // requested and there is a pending retry. public void cleanUp() { if (retriesPending == 0 && !cleanupCalled) { androidGdataClient.close(); } cleanupCalled = true; } public void setRetryOnAuthFailure(boolean retry) { retryOnAuthFailure = retry; } }
Java
// Copyright 2009 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; /** * Metadata about a "my maps" map. */ class MyMapsMapMetadata { private String title; private String description; private String gdataEditUri; private boolean searchable; public MyMapsMapMetadata() { title = ""; description = ""; gdataEditUri = ""; searchable = false; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean getSearchable() { return searchable; } public void setSearchable(boolean searchable) { this.searchable = searchable; } public String getGDataEditUri() { return gdataEditUri; } public void setGDataEditUri(String editUri) { this.gdataEditUri = editUri; } }
Java
// Copyright 2010 Google Inc. All Rights Reserved. package com.google.android.apps.mytracks.io.mymaps; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.xml.XmlGDataParser; import com.google.wireless.gdata.parser.xml.XmlParserFactory; import com.google.wireless.gdata.serializer.xml.XmlEntryGDataSerializer; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlSerializer; /** * Serializer of maps data for GData. */ class XmlMapsGDataSerializer extends XmlEntryGDataSerializer { private static final String APP_NAMESPACE = "http://www.w3.org/2007/app"; private MapFeatureEntry entry; private XmlParserFactory factory; private OutputStream stream; public XmlMapsGDataSerializer(XmlParserFactory factory, MapFeatureEntry entry) { super(factory, entry); this.factory = factory; this.entry = entry; } @Override public void serialize(OutputStream out, int format) throws IOException, ParseException { XmlSerializer serializer = null; try { serializer = factory.createSerializer(); } catch (XmlPullParserException e) { throw new ParseException("Unable to create XmlSerializer.", e); } ByteArrayOutputStream printStream; if (MapsClient.LOG_COMMUNICATION) { printStream = new ByteArrayOutputStream(); serializer.setOutput(printStream, "UTF-8"); } else { serializer.setOutput(out, "UTF-8"); } serializer.startDocument("UTF-8", Boolean.FALSE); declareEntryNamespaces(serializer); serializer.startTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry"); if (MapsClient.LOG_COMMUNICATION) { stream = printStream; } else { stream = out; } serializeEntryContents(serializer, format); serializer.endTag(XmlGDataParser.NAMESPACE_ATOM_URI, "entry"); serializer.endDocument(); serializer.flush(); if (MapsClient.LOG_COMMUNICATION) { Log.d("Request", printStream.toString()); out.write(printStream.toByteArray()); stream = out; } } private final void declareEntryNamespaces(XmlSerializer serializer) throws IOException { serializer.setPrefix( "" /* default ns */, XmlGDataParser.NAMESPACE_ATOM_URI); serializer.setPrefix( XmlGDataParser.NAMESPACE_GD, XmlGDataParser.NAMESPACE_GD_URI); declareExtraEntryNamespaces(serializer); } private final void serializeEntryContents(XmlSerializer serializer, int format) throws IOException { if (format != FORMAT_CREATE) { serializeId(serializer, entry.getId()); } serializeTitle(serializer, entry.getTitle()); if (format != FORMAT_CREATE) { serializeLink(serializer, "edit" /* rel */, entry.getEditUri(), null /* type */); serializeLink(serializer, "alternate" /* rel */, entry.getHtmlUri(), "text/html" /* type */); } serializeSummary(serializer, entry.getSummary()); serializeContent(serializer, entry.getContent()); serializeAuthor(serializer, entry.getAuthor(), entry.getEmail()); serializeCategory(serializer, entry.getCategory(), entry.getCategoryScheme()); if (format == FORMAT_FULL) { serializePublicationDate(serializer, entry.getPublicationDate()); } if (format != FORMAT_CREATE) { serializeUpdateDate(serializer, entry.getUpdateDate()); } serializeExtraEntryContents(serializer, format); } private static void serializeId(XmlSerializer serializer, String id) throws IOException { if (StringUtils.isEmpty(id)) { return; } serializer.startTag(null /* ns */, "id"); serializer.text(id); serializer.endTag(null /* ns */, "id"); } private static void serializeTitle(XmlSerializer serializer, String title) throws IOException { if (StringUtils.isEmpty(title)) { return; } serializer.startTag(null /* ns */, "title"); serializer.text(title); serializer.endTag(null /* ns */, "title"); } public static void serializeLink(XmlSerializer serializer, String rel, String href, String type) throws IOException { if (StringUtils.isEmpty(href)) { return; } serializer.startTag(null /* ns */, "link"); serializer.attribute(null /* ns */, "rel", rel); serializer.attribute(null /* ns */, "href", href); if (!StringUtils.isEmpty(type)) { serializer.attribute(null /* ns */, "type", type); } serializer.endTag(null /* ns */, "link"); } private static void serializeSummary(XmlSerializer serializer, String summary) throws IOException { if (StringUtils.isEmpty(summary)) { return; } serializer.startTag(null /* ns */, "summary"); serializer.text(summary); serializer.endTag(null /* ns */, "summary"); } private void serializeContent(XmlSerializer serializer, String content) throws IOException { if (content == null) { return; } serializer.startTag(null /* ns */, "content"); if (content.contains("</Placemark>")) { serializer.attribute( null /* ns */, "type", "application/vnd.google-earth.kml+xml"); serializer.flush(); stream.write(content.getBytes()); } else { serializer.text(content); } serializer.endTag(null /* ns */, "content"); } private static void serializeAuthor(XmlSerializer serializer, String author, String email) throws IOException { if (StringUtils.isEmpty(author) || StringUtils.isEmpty(email)) { return; } serializer.startTag(null /* ns */, "author"); serializer.startTag(null /* ns */, "name"); serializer.text(author); serializer.endTag(null /* ns */, "name"); serializer.startTag(null /* ns */, "email"); serializer.text(email); serializer.endTag(null /* ns */, "email"); serializer.endTag(null /* ns */, "author"); } private static void serializeCategory(XmlSerializer serializer, String category, String categoryScheme) throws IOException { if (StringUtils.isEmpty(category) && StringUtils.isEmpty(categoryScheme)) { return; } serializer.startTag(null /* ns */, "category"); if (!StringUtils.isEmpty(category)) { serializer.attribute(null /* ns */, "term", category); } if (!StringUtils.isEmpty(categoryScheme)) { serializer.attribute(null /* ns */, "scheme", categoryScheme); } serializer.endTag(null /* ns */, "category"); } private static void serializePublicationDate(XmlSerializer serializer, String publicationDate) throws IOException { if (StringUtils.isEmpty(publicationDate)) { return; } serializer.startTag(null /* ns */, "published"); serializer.text(publicationDate); serializer.endTag(null /* ns */, "published"); } private static void serializeUpdateDate(XmlSerializer serializer, String updateDate) throws IOException { if (StringUtils.isEmpty(updateDate)) { return; } serializer.startTag(null /* ns */, "updated"); serializer.text(updateDate); serializer.endTag(null /* ns */, "updated"); } @Override protected void serializeExtraEntryContents(XmlSerializer serializer, int format) throws IOException { Map<String, String> attrs = entry.getAllAttributes(); for (Map.Entry<String, String> attr : attrs.entrySet()) { serializer.startTag("http://schemas.google.com/g/2005", "customProperty"); serializer.attribute(null, "name", attr.getKey()); serializer.text(attr.getValue()); serializer.endTag("http://schemas.google.com/g/2005", "customProperty"); } String privacy = entry.getPrivacy(); if (!StringUtils.isEmpty(privacy)) { serializer.setPrefix("app", APP_NAMESPACE); if ("public".equals(privacy)) { serializer.startTag(APP_NAMESPACE, "control"); serializer.startTag(APP_NAMESPACE, "draft"); serializer.text("no"); serializer.endTag(APP_NAMESPACE, "draft"); serializer.endTag(APP_NAMESPACE, "control"); } if ("unlisted".equals(privacy)) { serializer.startTag(APP_NAMESPACE, "control"); serializer.startTag(APP_NAMESPACE, "draft"); serializer.text("yes"); serializer.endTag(APP_NAMESPACE, "draft"); serializer.endTag(APP_NAMESPACE, "control"); } } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.apps.mytracks.Constants.TAG; import android.app.Activity; import android.os.Build; import android.os.Bundle; import android.util.Log; /** * A factory for getting the platform specific AuthManager. * * @author Sandor Dornbush */ public class AuthManagerFactory { private AuthManagerFactory() { } /** * Returns whether the modern AuthManager should be used */ public static boolean useModernAuthManager() { return Integer.parseInt(Build.VERSION.SDK) >= 7; } /** * Get a right {@link AuthManager} for the platform. * @return A new AuthManager */ public static AuthManager getAuthManager(Activity activity, int code, Bundle extras, boolean requireGoogle, String service) { if (useModernAuthManager()) { Log.i(TAG, "Creating modern auth manager: " + service); return new ModernAuthManager(activity, service); } else { Log.i(TAG, "Creating legacy auth manager: " + service); return new AuthManagerOld(activity, code, extras, requireGoogle, service); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.ProgressIndicator; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.gdata.GDataWrapper; import com.google.android.apps.mytracks.io.gdata.GDataWrapper.QueryFunction; import com.google.android.apps.mytracks.io.sendtogoogle.SendType; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.ApiFeatures; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.SystemUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.MethodOverride; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.util.Strings; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Vector; /** * A helper class used to transmit tracks to Google Fusion Tables. * A new instance should be used for each upload. * * @author Leif Hendrik Wilden */ public class SendToFusionTables implements Runnable { private static final String CONTENT_TYPE = "application/x-www-form-urlencoded"; /** * Listener invoked when sending to fusion tables completes. */ public interface OnSendCompletedListener { void onSendCompleted(String tableId, boolean success); } /** The GData service id for Fusion Tables. */ public static final String SERVICE_ID = "fusiontables"; /** The path for viewing a map visualization of a table. */ private static final String FUSIONTABLES_MAP = "https://www.google.com/fusiontables/embedviz?" + "viz=MAP&q=select+col0,+col1,+col2,+col3+from+%s+&h=false&" + "lat=%f&lng=%f&z=%d&t=1&l=col2"; /** Standard base feed url for Fusion Tables. */ private static final String FUSIONTABLES_BASE_FEED_URL = "https://www.google.com/fusiontables/api/query"; private static final int MAX_POINTS_PER_UPLOAD = 2048; private static final String GDATA_VERSION = "2"; // This class reports upload status to the user as a completion percentage // using a progress bar. Progress is defined as follows: // // 0% Getting track metadata // 5% Creating Fusion Table (GData to FT server) // 10%-90% Uploading the track data to Fusion Tables // 95% Uploading waypoints // 100% Done private static final int PROGRESS_INITIALIZATION = 0; private static final int PROGRESS_FUSION_TABLE_CREATE = 5; private static final int PROGRESS_UPLOAD_DATA_MIN = 10; private static final int PROGRESS_UPLOAD_DATA_MAX = 90; private static final int PROGRESS_UPLOAD_WAYPOINTS = 95; private static final int PROGRESS_COMPLETE = 100; private final Activity context; private final AuthManager auth; private final long trackId; private final ProgressIndicator progressIndicator; private final OnSendCompletedListener onCompletion; private final StringUtils stringUtils; private final MyTracksProviderUtils providerUtils; // Progress status private int totalLocationsRead; private int totalLocationsPrepared; private int totalLocationsUploaded; private int totalLocations; private int totalSegmentsUploaded; private HttpRequestFactory httpRequestFactory; private String tableId; private static String MARKER_TYPE_START = "large_green"; private static String MARKER_TYPE_END = "large_red"; private static String MARKER_TYPE_WAYPOINT = "large_yellow"; public SendToFusionTables(Activity context, AuthManager auth, long trackId, ProgressIndicator progressIndicator, OnSendCompletedListener onCompletion) { this.context = context; this.auth = auth; this.trackId = trackId; this.progressIndicator = progressIndicator; this.onCompletion = onCompletion; this.stringUtils = new StringUtils(context); this.providerUtils = MyTracksProviderUtils.Factory.get(context); HttpTransport transport = ApiFeatures.getInstance().getApiAdapter().getHttpTransport(); httpRequestFactory = transport.createRequestFactory(new MethodOverride()); } @Override public void run() { Log.d(Constants.TAG, "Sending to Fusion tables: trackId = " + trackId); doUpload(); } public static String getMapVisualizationUrl(Track track) { if (track == null || track.getStatistics() == null || track.getTableId() == null) { Log.w(TAG, "Unable to get track URL"); return null; } // TODO(leifhendrik): Determine correct bounding box and zoom level that will show the entire track. TripStatistics stats = track.getStatistics(); double latE6 = stats.getBottom() + (stats.getTop() - stats.getBottom()) / 2; double lonE6 = stats.getLeft() + (stats.getRight() - stats.getLeft()) / 2; int z = 15; // We explicitly format with Locale.US because we need the latitude and // longitude to be formatted in a locale-independent manner. Specifically, // we need the decimal separator to be a period rather than a comma. return String.format(Locale.US, FUSIONTABLES_MAP, track.getTableId(), latE6 / 1.E6, lonE6 / 1.E6, z); } private void doUpload() { boolean success = true; try { progressIndicator.setProgressValue(PROGRESS_INITIALIZATION); progressIndicator.setProgressMessage( context.getString(R.string.send_google_progress_reading_track)); // Get the track meta-data Track track = providerUtils.getTrack(trackId); if (track == null) { Log.w(Constants.TAG, "Cannot get track."); return; } String originalDescription = track.getDescription(); // Create a new table: progressIndicator.setProgressValue(PROGRESS_FUSION_TABLE_CREATE); String creatingFormat = context.getString(R.string.send_google_progress_creating); String serviceName = context.getString(SendType.FUSION_TABLES.getServiceName()); progressIndicator.setProgressMessage(String.format(creatingFormat, serviceName)); if (!createNewTable(track) || !makeTableUnlisted()) { return; } progressIndicator.setProgressValue(PROGRESS_UPLOAD_DATA_MIN); String sendingFormat = context.getString(R.string.send_google_progress_sending); progressIndicator.setProgressMessage(String.format(sendingFormat, serviceName)); // Upload all of the segments of the track plus start/end markers if (!uploadAllTrackPoints(track, originalDescription)) { return; } progressIndicator.setProgressValue(PROGRESS_UPLOAD_WAYPOINTS); // Upload all the waypoints. if (!uploadWaypoints(track)) { return; } Log.d(Constants.TAG, "SendToFusionTables: Done: " + success); progressIndicator.setProgressValue(PROGRESS_COMPLETE); } finally { final boolean finalSuccess = success; context.runOnUiThread(new Runnable() { public void run() { if (onCompletion != null) { onCompletion.onSendCompleted(tableId, finalSuccess); } } }); } } /** * Creates a new table. * If successful sets {@link #tableId}. * * @return true in case of success. */ private boolean createNewTable(Track track) { Log.d(Constants.TAG, "Creating a new fusion table."); String query = "CREATE TABLE '" + sqlEscape(track.getName()) + "' (name:STRING,description:STRING,geometry:LOCATION,marker:STRING)"; return runUpdate(query); } private boolean makeTableUnlisted() { Log.d(Constants.TAG, "Setting visibility to unlisted."); String query = "UPDATE TABLE " + tableId + " SET VISIBILITY = UNLISTED"; return runUpdate(query); } /** * Formats given values SQL style. Escapes single quotes with a backslash. * * @param values the values to format * @return the values formatted as: ('value1','value2',...,'value_n'). */ private static String values(String... values) { StringBuilder builder = new StringBuilder("("); for (int i = 0; i < values.length; i++) { if (i > 0) { builder.append(','); } builder.append('\''); builder.append(sqlEscape(values[i])); builder.append('\''); } builder.append(')'); return builder.toString(); } private static String sqlEscape(String value) { return value.replaceAll("'", "''"); } /** * Creates a new row representing a marker. * * @param name the marker name * @param description the marker description * @param location the marker location * @return true in case of success. */ private boolean createNewPoint(String name, String description, Location location, String marker) { Log.d(Constants.TAG, "Creating a new row with a point."); String query = "INSERT INTO " + tableId + " (name,description,geometry,marker) VALUES " + values(name, description, getKmlPoint(location), marker); return runUpdate(query); } /** * Creates a new row representing a line segment. * * @param track the track/segment to draw * @return true in case of success. */ private boolean createNewLineString(Track track) { Log.d(Constants.TAG, "Creating a new row with a point."); String query = "INSERT INTO " + tableId + " (name,description,geometry) VALUES " + values(track.getName(), track.getDescription(), getKmlLineString(track)); return runUpdate(query); } private boolean uploadAllTrackPoints(final Track track, String originalDescription) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = true; if (preferences != null) { metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true); } Cursor locationsCursor = providerUtils.getLocationsCursor(track.getId(), 0, -1, false); try { if (locationsCursor == null || !locationsCursor.moveToFirst()) { Log.w(Constants.TAG, "Unable to get any points to upload"); return false; } totalLocationsRead = 0; totalLocationsPrepared = 0; totalLocationsUploaded = 0; totalLocations = locationsCursor.getCount(); totalSegmentsUploaded = 0; // Limit the number of elevation readings. Ideally we would want around 250. int elevationSamplingFrequency = Math.max(1, (int) (totalLocations / 250.0)); Log.d(Constants.TAG, "Using elevation sampling factor: " + elevationSamplingFrequency + " on " + totalLocations); double totalDistance = 0; Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; do { if (totalLocationsRead % 100 == 0) { updateTrackDataUploadProgress(); } Location loc = providerUtils.createLocation(locationsCursor); locations.add(loc); if (totalLocationsRead == 0) { // Put a marker at the first point of the first valid segment: String name = track.getName() + " " + context.getString(R.string.marker_label_start); createNewPoint(name, "", loc, MARKER_TYPE_START); } // Add to the elevation profile. if (loc != null && LocationUtils.isValidLocation(loc)) { // All points go into the smoothing buffer... elevationBuffer.setNext(metricUnits ? loc.getAltitude() : loc.getAltitude() * UnitConversions.M_TO_FT); if (lastLocation != null) { double dist = lastLocation.distanceTo(loc); totalDistance += dist; } // ...but only a few points are really used to keep the url short. if (totalLocationsRead % elevationSamplingFrequency == 0) { distances.add(totalDistance); elevations.add(elevationBuffer.getAverage()); } } // If the location was not valid, it's a segment split, so make sure the // distance between the previous segment and the new one is not accounted // for in the next iteration. lastLocation = loc; // Every now and then, upload the accumulated points if (totalLocationsRead % MAX_POINTS_PER_UPLOAD == MAX_POINTS_PER_UPLOAD - 1) { if (!prepareAndUploadPoints(track, locations)) { return false; } } totalLocationsRead++; } while (locationsCursor.moveToNext()); // Do a final upload with what's left if (!prepareAndUploadPoints(track, locations)) { return false; } // Put an end marker at the last point of the last valid segment: if (lastLocation != null) { track.setDescription("<p>" + originalDescription + "</p><p>" + stringUtils.generateTrackDescription(track, distances, elevations) + "</p>"); String name = track.getName() + " " + context.getString(R.string.marker_label_end); return createNewPoint(name, track.getDescription(), lastLocation, MARKER_TYPE_END); } return true; } finally { if (locationsCursor != null) { locationsCursor.close(); } } } /** * Appends the given location to the string in the format: * longitude,latitude[,altitude] * * @param location the location to be added * @param builder the string builder to use */ private void appendCoordinate(Location location, StringBuilder builder) { builder .append(location.getLongitude()) .append(",") .append(location.getLatitude()); if (location.hasAltitude()) { builder.append(","); builder.append(location.getAltitude()); } } /** * Gets a KML Point tag for the given location. * * @param location The location. * @return the kml. */ private String getKmlPoint(Location location) { StringBuilder builder = new StringBuilder("<Point><coordinates>"); appendCoordinate(location, builder); builder.append("</coordinates></Point>"); return builder.toString(); } /** * Returns a KML LineString. * * @param track the track. * @return the KML LineString. */ private String getKmlLineString(Track track) { StringBuilder builder = new StringBuilder("<LineString><coordinates>"); for (Location location : track.getLocations()) { appendCoordinate(location, builder); builder.append(' '); } builder.append("</coordinates></LineString>"); return builder.toString(); } private boolean prepareAndUploadPoints(Track track, List<Location> locations) { updateTrackDataUploadProgress(); int numLocations = locations.size(); if (numLocations < 2) { Log.d(Constants.TAG, "Not preparing/uploading too few points"); totalLocationsUploaded += numLocations; return true; } // Prepare/pre-process the points ArrayList<Track> splitTracks = prepareLocations(track, locations); // Start uploading them for (Track splitTrack : splitTracks) { if (totalSegmentsUploaded > 1) { splitTrack.setName(splitTrack.getName() + " " + String.format( context.getString(R.string.send_google_track_part_label), totalSegmentsUploaded)); } totalSegmentsUploaded++; Log.d(Constants.TAG, "SendToFusionTables: Prepared feature for upload w/ " + splitTrack.getLocations().size() + " points."); // Transmit tracks via GData feed: // ------------------------------- Log.d(Constants.TAG, "SendToFusionTables: Uploading to table " + tableId + " w/ auth " + auth); if (!uploadTrackPoints(splitTrack)) { Log.e(Constants.TAG, "Uploading failed"); return false; } } locations.clear(); totalLocationsUploaded += numLocations; updateTrackDataUploadProgress(); return true; } /** * Prepares a buffer of locations for transmission to google fusion tables. * * @param track the original track with meta data * @param locations locations on the track * @return an array of tracks each with a sub section of the points in the * original buffer */ private ArrayList<Track> prepareLocations( Track track, Iterable<Location> locations) { ArrayList<Track> splitTracks = new ArrayList<Track>(); // Create segments from each full track: Track segment = new Track(); TripStatistics segmentStats = segment.getStatistics(); TripStatistics trackStats = track.getStatistics(); segment.setId(track.getId()); segment.setName(track.getName()); segment.setDescription(/* track.getDescription() */ ""); segment.setCategory(track.getCategory()); segmentStats.setStartTime(trackStats.getStartTime()); segmentStats.setStopTime(trackStats.getStopTime()); boolean startNewTrackSegment = false; for (Location loc : locations) { if (totalLocationsPrepared % 100 == 0) { updateTrackDataUploadProgress(); } if (loc.getLatitude() > 90) { startNewTrackSegment = true; } if (startNewTrackSegment) { // Close up the last segment. prepareTrackSegment(segment, splitTracks); Log.d(Constants.TAG, "MyTracksSendToFusionTables: Starting new track segment..."); startNewTrackSegment = false; segment = new Track(); segment.setId(track.getId()); segment.setName(track.getName()); segment.setDescription(/* track.getDescription() */ ""); segment.setCategory(track.getCategory()); } if (loc.getLatitude() <= 90) { segment.addLocation(loc); if (segmentStats.getStartTime() < 0) { segmentStats.setStartTime(loc.getTime()); } } totalLocationsPrepared++; } prepareTrackSegment(segment, splitTracks); return splitTracks; } /** * Prepares a track segment for sending to google fusion tables. * The main steps are: * - correcting end time * - decimating locations * - splitting into smaller tracks. * * The final track pieces will be put in the array list splitTracks. * * @param segment the original segment of the track * @param splitTracks an array of smaller track segments */ private void prepareTrackSegment( Track segment, ArrayList<Track> splitTracks) { TripStatistics segmentStats = segment.getStatistics(); if (segmentStats.getStopTime() < 0 && segment.getLocations().size() > 0) { segmentStats.setStopTime(segment.getLocations().size() - 1); } /* * Decimate to 2 meter precision. Fusion tables doesn't like too many * points: */ LocationUtils.decimate(segment, 2.0); /* If the track still has > 2500 points, split it in pieces: */ final int maxPoints = 2500; if (segment.getLocations().size() > maxPoints) { splitTracks.addAll(LocationUtils.split(segment, maxPoints)); } else if (segment.getLocations().size() >= 2) { splitTracks.add(segment); } } private boolean uploadTrackPoints(Track splitTrack) { int numLocations = splitTrack.getLocations().size(); if (numLocations < 2) { // Need at least two points for a polyline: Log.w(Constants.TAG, "Not uploading too few points"); return true; } return createNewLineString(splitTrack); } /** * Uploads all of the waypoints associated with this track to a table. * * @param track The track to upload waypoints for. * * @return True on success. */ private boolean uploadWaypoints(final Track track) { // TODO: Stream through the waypoints in chunks. // I am leaving the number of waypoints very high which should not be a // problem because we don't try to load them into objects all at the // same time. boolean success = true; Cursor c = null; try { c = providerUtils.getWaypointsCursor( track.getId(), 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (c != null) { if (c.moveToFirst()) { // This will skip the 1st waypoint (it carries the stats for the // last segment). while (c.moveToNext()) { Waypoint wpt = providerUtils.createWaypoint(c); Log.d(Constants.TAG, "SendToFusionTables: Creating waypoint."); success = createNewPoint(wpt.getName(), wpt.getDescription(), wpt.getLocation(), MARKER_TYPE_WAYPOINT); if (!success) { break; } } } } if (!success) { Log.w(Constants.TAG, "SendToFusionTables: upload waypoints failed."); } return success; } finally { if (c != null) { c.close(); } } } private void updateTrackDataUploadProgress() { // The percent of the total that represents the completed part of this // segment. We calculate it as an absolute percentage, and then scale it // to fit the completion percentage range alloted to track data upload. double totalPercentage = (totalLocationsRead + totalLocationsPrepared + totalLocationsUploaded) / (totalLocations * 3.0); double scaledPercentage = totalPercentage * (PROGRESS_UPLOAD_DATA_MAX - PROGRESS_UPLOAD_DATA_MIN) + PROGRESS_UPLOAD_DATA_MIN; progressIndicator.setProgressValue((int) scaledPercentage); } /** * Runs an update query. Handles authentication. * * @param query The given SQL like query * @return true in case of success */ private boolean runUpdate(final String query) { GDataWrapper<HttpRequestFactory> wrapper = new GDataWrapper<HttpRequestFactory>(); wrapper.setAuthManager(auth); wrapper.setRetryOnAuthFailure(true); wrapper.setClient(httpRequestFactory); Log.d(Constants.TAG, "GData connection prepared: " + this.auth); wrapper.runQuery(new QueryFunction<HttpRequestFactory>() { @Override public void query(HttpRequestFactory factory) throws IOException, GDataWrapper.ParseException, GDataWrapper.HttpException, GDataWrapper.AuthenticationException { GenericUrl url = new GenericUrl(FUSIONTABLES_BASE_FEED_URL); String sql = "sql=" + URLEncoder.encode(query, "UTF-8"); ByteArrayInputStream inputStream = new ByteArrayInputStream(Strings.toBytesUtf8(sql)); InputStreamContent isc = new InputStreamContent(null, inputStream ); HttpRequest request = factory.buildPostRequest(url, isc); GoogleHeaders headers = new GoogleHeaders(); headers.setApplicationName("Google-MyTracks-" + SystemUtils.getMyTracksVersion(context)); headers.gdataVersion = GDATA_VERSION; headers.setGoogleLogin(auth.getAuthToken()); headers.setContentType(CONTENT_TYPE); request.setHeaders(headers); Log.d(Constants.TAG, "Running update query " + url.toString() + ": " + sql); HttpResponse response; try { response = request.execute(); } catch (HttpResponseException e) { throw new GDataWrapper.HttpException(e.getResponse().getStatusCode(), e.getResponse().getStatusMessage()); } boolean success = response.isSuccessStatusCode(); if (success) { byte[] result = new byte[1024]; int read = response.getContent().read(result); String s = new String(result, 0, read, "UTF8"); String[] lines = s.split(Strings.LINE_SEPARATOR); if (lines[0].equals("tableid")) { tableId = lines[1]; Log.d(Constants.TAG, "tableId = " + tableId); } else { Log.w(Constants.TAG, "Unrecognized response: " + lines[0]); } } else { Log.d(Constants.TAG, "Query failed: " + response.getStatusMessage() + " (" + response.getStatusCode() + ")"); throw new GDataWrapper.HttpException( response.getStatusCode(), response.getStatusMessage()); } } }); return wrapper.getErrorType() == GDataWrapper.ERROR_NO_ERROR; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.apps.mytracks.Constants.ACCOUNT_TYPE; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.AccountChooser; import android.accounts.Account; import android.accounts.AccountManager; import android.accounts.AccountManagerCallback; import android.accounts.AccountManagerFuture; import android.accounts.AuthenticatorException; import android.accounts.OperationCanceledException; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import java.io.IOException; /** * AuthManager keeps track of the current auth token for a user. The advantage * over just passing around a String is that this class can renew the auth * token if necessary, and it will change for all classes using this * AuthManager. */ public class ModernAuthManager implements AuthManager { /** The activity that will handle auth result callbacks. */ private final Activity activity; /** The name of the service to authorize for. */ private final String service; /** The most recently fetched auth token or null if none is available. */ private String authToken; private final AccountManager accountManager; private AuthCallback authCallback; private Account lastAccount; /** * AuthManager requires many of the same parameters as * {@link com.google.android.googlelogindist.GoogleLoginServiceHelper * #getCredentials(Activity, int, Bundle, boolean, String, boolean)}. * The activity must have a handler in {@link Activity#onActivityResult} that * calls {@link #authResult(int, Intent)} if the request code is the code * given here. * * @param activity An activity with a handler in * {@link Activity#onActivityResult} that calls * {@link #authResult(int, Intent)} when {@literal code} is the request * code * @param service The name of the service to authenticate as */ public ModernAuthManager(Activity activity, String service) { this.activity = activity; this.service = service; this.accountManager = AccountManager.get(activity); } /** * Call this to do the initial login. The user will be asked to login if * they haven't already. The {@link Runnable} provided will be executed * when the auth token is successfully fetched. * * @param runnable A {@link Runnable} to execute when the auth token * has been successfully fetched and is available via * {@link #getAuthToken()} */ public void doLogin(AuthCallback runnable, Object o) { this.authCallback = runnable; if (!(o instanceof Account)) { throw new IllegalArgumentException("ModernAuthManager requires an account."); } Account account = (Account) o; doLogin(account); } private void doLogin(Account account) { // Keep the account in case we need to retry. this.lastAccount = account; // NOTE: Many Samsung phones have a crashing bug in // AccountManager#getAuthToken(Account, String, boolean, AccountManagerCallback<Bundle>) // so we use the other version of the method. // More details here: // http://forum.xda-developers.com/showthread.php?p=15155487 // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;f=core/java/android/accounts/AccountManagerService.java accountManager.getAuthToken(account, service, null, activity, new AccountManagerCallback<Bundle>() { public void run(AccountManagerFuture<Bundle> future) { try { authToken = future.getResult().getString( AccountManager.KEY_AUTHTOKEN); Log.i(TAG, "Got auth token"); } catch (OperationCanceledException e) { Log.e(TAG, "Auth token operation Canceled", e); } catch (IOException e) { Log.e(TAG, "Auth token IO exception", e); } catch (AuthenticatorException e) { Log.e(TAG, "Authentication Failed", e); } runAuthCallback(); } }, null /* handler */); } /** * The {@link Activity} passed into the constructor should call this * function when it gets {@link Activity#onActivityResult} with the request * code passed into the constructor. The resultCode and results should * come directly from the {@link Activity#onActivityResult} function. This * function will return true if an auth token was successfully fetched or * the process is not finished. * * @param resultCode The result code passed in to the {@link Activity}'s * {@link Activity#onActivityResult} function * @param results The data passed in to the {@link Activity}'s * {@link Activity#onActivityResult} function */ public void authResult(int resultCode, Intent results) { boolean retry = false; if (results == null) { Log.e(TAG, "No auth token!!"); } else { authToken = results.getStringExtra(AccountManager.KEY_AUTHTOKEN); retry = results.getBooleanExtra("retry", false); } if (authToken == null && retry) { Log.i(TAG, "Retrying to get auth result"); doLogin(lastAccount); return; } runAuthCallback(); } /** * Returns the current auth token. Response may be null if no valid auth * token has been fetched. * * @return The current auth token or null if no auth token has been * fetched */ public String getAuthToken() { return authToken; } /** * Invalidates the existing auth token and request a new one. The callback * provided will be executed when the new auth token is successfully fetched. * * @param callback A callback to execute when a new auth token is successfully * fetched */ public void invalidateAndRefresh(final AuthCallback callback) { this.authCallback = callback; activity.runOnUiThread(new Runnable() { public void run() { accountManager.invalidateAuthToken(ACCOUNT_TYPE, authToken); authToken = null; AccountChooser accountChooser = new AccountChooser(); accountChooser.chooseAccount(activity, new AccountChooser.AccountHandler() { @Override public void onAccountSelected(Account account) { if (account != null) { doLogin(account); } else { runAuthCallback(); } } }); } }); } private void runAuthCallback() { lastAccount = null; if (authCallback != null) { (new Thread() { @Override public void run() { authCallback.onAuthResult(authToken != null); authCallback = null; } }).start(); } } @Override public Object getAccountObject(String accountName, String accountType) { return new Account(accountName, accountType); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import static com.google.android.apps.mytracks.Constants.TAG; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.ProgressIndicator; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.mymaps.MapsFacade; import com.google.android.apps.mytracks.io.sendtogoogle.SendType; import com.google.android.apps.mytracks.stats.DoubleBuffer; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.StringUtils; import com.google.android.apps.mytracks.util.UnitConversions; import com.google.android.maps.mytracks.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.location.Location; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.Vector; /** * A helper class used to transmit tracks to Google MyMaps. * A new instance should be used for each upload. * * IMPORTANT: while this code is Apache-licensed, please notice that usage of * the Google Maps servers through this API is only allowed for the My Tracks * application. Other applications looking to upload maps data should look * into using the Fusion Tables API. * * @author Leif Hendrik Wilden */ public class SendToMyMaps implements Runnable { public static final String NEW_MAP_ID = "new"; private static final int MAX_POINTS_PER_UPLOAD = 2048; private final Activity context; private final AuthManager auth; private final long trackId; private final ProgressIndicator progressIndicator; private final OnSendCompletedListener onCompletion; private final StringUtils stringUtils; private final MyTracksProviderUtils providerUtils; private String mapId; private MapsFacade mapsClient; // Progress status private int totalLocationsRead; private int totalLocationsPrepared; private int totalLocationsUploaded; private int totalLocations; private int totalSegmentsUploaded; public interface OnSendCompletedListener { void onSendCompleted(String mapId, boolean success); } public SendToMyMaps(Activity context, String mapId, AuthManager auth, long trackId, ProgressIndicator progressIndicator, OnSendCompletedListener onCompletion) { this.context = context; this.mapId = mapId; this.auth = auth; this.trackId = trackId; this.progressIndicator = progressIndicator; this.onCompletion = onCompletion; this.stringUtils = new StringUtils(context); this.providerUtils = MyTracksProviderUtils.Factory.get(context); } @Override public void run() { Log.d(TAG, "Sending to MyMaps: trackId = " + trackId); doUpload(); } private void doUpload() { boolean success = true; try { progressIndicator.setProgressMessage( context.getString(R.string.send_google_progress_reading_track)); // Get the track meta-data Track track = providerUtils.getTrack(trackId); if (track == null) { Log.w(Constants.TAG, "Cannot get track."); return; } String originalDescription = track.getDescription(); track.setDescription("<p>" + track.getDescription() + "</p><p>" + stringUtils.generateTrackDescription(track, null, null) + "</p>"); mapsClient = new MapsFacade(context, auth); // Create a new map if necessary: boolean isNewMap = mapId.equals(NEW_MAP_ID); if (isNewMap) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean mapPublic = true; if (preferences != null) { mapPublic = preferences.getBoolean( context.getString(R.string.default_map_public_key), true); } String creatingFormat = context.getString(R.string.send_google_progress_creating); String serviceName = context.getString(SendType.MYMAPS.getServiceName()); progressIndicator.setProgressMessage(String.format(creatingFormat, serviceName)); StringBuilder mapIdBuilder = new StringBuilder(); success = mapsClient.createNewMap( track.getName(), track.getCategory(), originalDescription, mapPublic, mapIdBuilder); mapId = mapIdBuilder.toString(); } // Upload all of the segments of the track plus start/end markers if (success) { success = uploadAllTrackPoints(track, originalDescription); } // Put waypoints. if (success) { Cursor c = providerUtils.getWaypointsCursor( track.getId(), 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (c != null) { try { if (c.getCount() > 1 && c.moveToFirst()) { // This will skip the 1st waypoint (it carries the stats for the // last segment). ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>(c.getCount() - 1); while (c.moveToNext()) { Waypoint wpt = providerUtils.createWaypoint(c); waypoints.add(wpt); } success = mapsClient.uploadWaypoints(mapId, waypoints); } } finally { c.close(); } } else { success = false; } if (!success) { Log.w(TAG, "SendToMyMaps: upload waypoints failed."); } } Log.d(TAG, "SendToMyMaps: Done: " + success); progressIndicator.setProgressValue(100); } finally { if (mapsClient != null) { mapsClient.cleanUp(); } final boolean finalSuccess = success; context.runOnUiThread(new Runnable() { public void run() { if (onCompletion != null) { onCompletion.onSendCompleted(mapId, finalSuccess); } } }); } } private boolean uploadAllTrackPoints( final Track track, String originalDescription) { SharedPreferences preferences = context.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); boolean metricUnits = true; if (preferences != null) { metricUnits = preferences.getBoolean(context.getString(R.string.metric_units_key), true); } Cursor locationsCursor = providerUtils.getLocationsCursor(track.getId(), 0, -1, false); try { if (locationsCursor == null || !locationsCursor.moveToFirst()) { Log.w(TAG, "Unable to get any points to upload"); return false; } totalLocationsRead = 0; totalLocationsPrepared = 0; totalLocationsUploaded = 0; totalLocations = locationsCursor.getCount(); totalSegmentsUploaded = 0; // Limit the number of elevation readings. Ideally we would want around 250. int elevationSamplingFrequency = Math.max(1, (int) (totalLocations / 250.0)); Log.d(TAG, "Using elevation sampling factor: " + elevationSamplingFrequency + " on " + totalLocations); double totalDistance = 0; Vector<Double> distances = new Vector<Double>(); Vector<Double> elevations = new Vector<Double>(); DoubleBuffer elevationBuffer = new DoubleBuffer(Constants.ELEVATION_SMOOTHING_FACTOR); List<Location> locations = new ArrayList<Location>(MAX_POINTS_PER_UPLOAD); progressIndicator.setProgressMessage( context.getString(R.string.send_google_progress_reading_track)); Location lastLocation = null; do { if (totalLocationsRead % 100 == 0) { updateProgress(); } Location loc = providerUtils.createLocation(locationsCursor); locations.add(loc); if (totalLocationsRead == 0) { // Put a marker at the first point of the first valid segment: mapsClient.uploadMarker(mapId, track.getName(), track.getDescription(), loc, true); } // Add to the elevation profile. if (loc != null && LocationUtils.isValidLocation(loc)) { // All points go into the smoothing buffer... elevationBuffer.setNext(metricUnits ? loc.getAltitude() : loc.getAltitude() * UnitConversions.M_TO_FT); if (lastLocation != null) { double dist = lastLocation.distanceTo(loc); totalDistance += dist; } // ...but only a few points are really used to keep the url short. if (totalLocationsRead % elevationSamplingFrequency == 0) { distances.add(totalDistance); elevations.add(elevationBuffer.getAverage()); } } // If the location was not valid, it's a segment split, so make sure the // distance between the previous segment and the new one is not accounted // for in the next iteration. lastLocation = loc; // Every now and then, upload the accumulated points if (totalLocationsRead % MAX_POINTS_PER_UPLOAD == MAX_POINTS_PER_UPLOAD - 1) { if (!prepareAndUploadPoints(track, locations)) { return false; } } totalLocationsRead++; } while (locationsCursor.moveToNext()); // Do a final upload with what's left if (!prepareAndUploadPoints(track, locations)) { return false; } // Put an end marker at the last point of the last valid segment: if (lastLocation != null) { track.setDescription("<p>" + originalDescription + "</p><p>" + stringUtils.generateTrackDescription( track, distances, elevations) + "</p>"); return mapsClient.uploadMarker(mapId, track.getName(), track.getDescription(), lastLocation, false); } return true; } finally { if (locationsCursor != null) { locationsCursor.close(); } } } private boolean prepareAndUploadPoints(Track track, List<Location> locations) { progressIndicator.setProgressMessage( context.getString(R.string.send_google_progress_preparing_track)); updateProgress(); int numLocations = locations.size(); if (numLocations < 2) { Log.d(TAG, "Not preparing/uploading too few points"); totalLocationsUploaded += numLocations; return true; } // Prepare/pre-process the points ArrayList<Track> splitTracks = prepareLocations(track, locations); // Start uploading them String sendingFormat = context.getString(R.string.send_google_progress_sending); String serviceName = context.getString(SendType.MYMAPS.getServiceName()); progressIndicator.setProgressMessage(String.format(sendingFormat, serviceName)); for (Track splitTrack : splitTracks) { if (totalSegmentsUploaded > 1) { splitTrack.setName(splitTrack.getName() + " " + String.format( context.getString(R.string.send_google_track_part_label), totalSegmentsUploaded)); } totalSegmentsUploaded++; Log.d(TAG, "SendToMyMaps: Prepared feature for upload w/ " + splitTrack.getLocations().size() + " points."); // Transmit tracks via GData feed: // ------------------------------- Log.d(TAG, "SendToMyMaps: Uploading to map " + mapId + " w/ auth " + auth); if (!mapsClient.uploadTrackPoints(mapId, splitTrack.getName(), splitTrack.getLocations())) { Log.e(TAG, "Uploading failed"); return false; } } locations.clear(); totalLocationsUploaded += numLocations; updateProgress(); return true; } /** * Prepares a buffer of locations for transmission to google maps. * * @param track the original track with meta data * @param locations a buffer of locations on the track * @return an array of tracks each with a sub section of the points in the * original buffer */ private ArrayList<Track> prepareLocations( Track track, Iterable<Location> locations) { ArrayList<Track> splitTracks = new ArrayList<Track>(); // Create segments from each full track: Track segment = new Track(); TripStatistics segmentStats = segment.getStatistics(); TripStatistics trackStats = track.getStatistics(); segment.setId(track.getId()); segment.setName(track.getName()); segment.setDescription(/* track.getDescription() */ ""); segment.setCategory(track.getCategory()); segmentStats.setStartTime(trackStats.getStartTime()); segmentStats.setStopTime(trackStats.getStopTime()); boolean startNewTrackSegment = false; for (Location loc : locations) { if (totalLocationsPrepared % 100 == 0) { updateProgress(); } if (loc.getLatitude() > 90) { startNewTrackSegment = true; } if (startNewTrackSegment) { // Close up the last segment. prepareTrackSegment(segment, splitTracks); Log.d(TAG, "MyTracksSendToMyMaps: Starting new track segment..."); startNewTrackSegment = false; segment = new Track(); segment.setId(track.getId()); segment.setName(track.getName()); segment.setDescription(/* track.getDescription() */ ""); segment.setCategory(track.getCategory()); } if (loc.getLatitude() <= 90) { segment.addLocation(loc); if (segmentStats.getStartTime() < 0) { segmentStats.setStartTime(loc.getTime()); } } totalLocationsPrepared++; } prepareTrackSegment(segment, splitTracks); return splitTracks; } /** * Prepares a track segment for sending to google maps. * The main steps are: * - correcting end time * - decimating locations * - splitting into smaller tracks. * * The final track pieces will be put in the array list splitTracks. * * @param segment the original segment of the track * @param splitTracks an array of smaller track segments */ private void prepareTrackSegment( Track segment, ArrayList<Track> splitTracks) { TripStatistics segmentStats = segment.getStatistics(); if (segmentStats.getStopTime() < 0 && segment.getLocations().size() > 0) { segmentStats.setStopTime(segment.getLocations().size() - 1); } /* * Decimate to 2 meter precision. Mapshop doesn't like too many * points: */ LocationUtils.decimate(segment, 2.0); /* It the track still has > 500 points, split it in pieces: */ if (segment.getLocations().size() > 500) { splitTracks.addAll(LocationUtils.split(segment, 500)); } else if (segment.getLocations().size() >= 2) { splitTracks.add(segment); } } /** * Sets the current upload progress. */ private void updateProgress() { // The percent of the total that represents the completed part of this // segment. int totalPercentage = (totalLocationsRead + totalLocationsPrepared + totalLocationsUploaded) * 100 / (totalLocations * 3); totalPercentage = Math.min(99, totalPercentage); progressIndicator.setProgressValue(totalPercentage); } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.io; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.ProgressIndicator; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.io.docs.DocsHelper; import com.google.android.apps.mytracks.io.gdata.GDataClientFactory; import com.google.android.apps.mytracks.io.gdata.GDataWrapper; import com.google.android.common.gdata.AndroidXmlParserFactory; import com.google.android.maps.mytracks.R; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.docs.DocumentsClient; import com.google.wireless.gdata.docs.SpreadsheetsClient; import com.google.wireless.gdata.docs.XmlDocsGDataParserFactory; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.util.Log; import java.io.IOException; /** * A helper class used to transmit tracks statistics to Google Docs/Trix. * * @author Sandor Dornbush */ public class SendToDocs { /** The GData service name for Google Spreadsheets (aka Trix) */ public static final String GDATA_SERVICE_NAME_TRIX = "wise"; /** The GData service name for the Google Docs Document List */ public static final String GDATA_SERVICE_NAME_DOCLIST = "writely"; private final Activity activity; private final AuthManager trixAuth; private final AuthManager docListAuth; private final ProgressIndicator progressIndicator; private final boolean metricUnits; private boolean success = true; private Runnable onCompletion = null; public SendToDocs(Activity activity, AuthManager trixAuth, AuthManager docListAuth, ProgressIndicator progressIndicator) { this.activity = activity; this.trixAuth = trixAuth; this.docListAuth = docListAuth; this.progressIndicator = progressIndicator; SharedPreferences preferences = activity.getSharedPreferences( Constants.SETTINGS_NAME, Context.MODE_PRIVATE); if (preferences != null) { metricUnits = preferences.getBoolean(activity.getString(R.string.metric_units_key), true); } else { metricUnits = true; } } public void sendToDocs(final long trackId) { Log.d(Constants.TAG, "Sending to Google Docs: trackId = " + trackId); new Thread("SendToGoogleDocs") { @Override public void run() { doUpload(trackId); } }.start(); } private void doUpload(long trackId) { success = false; try { if (trackId == -1) { Log.w(Constants.TAG, "Cannot get track id."); return; } // Get the track from the provider: Track track = MyTracksProviderUtils.Factory.get(activity).getTrack(trackId); if (track == null) { Log.w(Constants.TAG, "Cannot get track."); return; } // Transmit track stats via GData feed: // ------------------------------- Log.d(Constants.TAG, "SendToDocs: Uploading to spreadsheet"); success = uploadToDocs(track); Log.d(Constants.TAG, "SendToDocs: Done."); } finally { if (onCompletion != null) { activity.runOnUiThread(onCompletion); } } } public boolean wasSuccess() { return success; } public void setOnCompletion(Runnable onCompletion) { this.onCompletion = onCompletion; } /** * Uploads the statistics about a track to Google Docs using the docs GData * feed. * * @param track the track */ private boolean uploadToDocs(Track track) { GDataWrapper<GDataServiceClient> docListWrapper = new GDataWrapper<GDataServiceClient>(); docListWrapper.setAuthManager(docListAuth); docListWrapper.setRetryOnAuthFailure(true); GDataWrapper<GDataServiceClient> trixWrapper = new GDataWrapper<GDataServiceClient>(); trixWrapper.setAuthManager(trixAuth); trixWrapper.setRetryOnAuthFailure(true); DocsHelper docsHelper = new DocsHelper(); GDataClient androidClient = null; try { androidClient = GDataClientFactory.getGDataClient(activity); SpreadsheetsClient gdataClient = new SpreadsheetsClient(androidClient, new XmlDocsGDataParserFactory(new AndroidXmlParserFactory())); trixWrapper.setClient(gdataClient); Log.d(Constants.TAG, "GData connection prepared: " + this.docListAuth); String sheetTitle = "My Tracks"; if (track.getCategory() != null && !track.getCategory().equals("")) { sheetTitle += "-" + track.getCategory(); } DocumentsClient docsGdataClient = new DocumentsClient(androidClient, new XmlDocsGDataParserFactory(new AndroidXmlParserFactory())); docListWrapper.setClient(docsGdataClient); // First try to find the spreadsheet: String spreadsheetId = null; try { spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper, sheetTitle); } catch (IOException e) { Log.i(Constants.TAG, "Spreadsheet lookup failed.", e); return false; } if (spreadsheetId == null) { progressIndicator.setProgressValue(65); // Waiting a few seconds and trying again. Maybe the server just had a // hickup (unfortunately that happens quite a lot...). try { Thread.sleep(5000); } catch (InterruptedException e) { Log.e(Constants.TAG, "Sleep interrupted", e); } try { spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper, sheetTitle); } catch (IOException e) { Log.i(Constants.TAG, "2nd spreadsheet lookup failed.", e); return false; } } // We were unable to find an existing spreadsheet, so create a new one. progressIndicator.setProgressValue(70); if (spreadsheetId == null) { Log.i(Constants.TAG, "Creating new spreadsheet: " + sheetTitle); try { spreadsheetId = docsHelper.createSpreadsheet(activity, docListWrapper, sheetTitle); } catch (IOException e) { Log.i(Constants.TAG, "Failed to create new spreadsheet " + sheetTitle, e); return false; } progressIndicator.setProgressValue(80); if (spreadsheetId == null) { progressIndicator.setProgressValue(85); // The previous creation might have succeeded even though GData // reported an error. Seems to be a know bug, // see http://code.google.com/p/gdata-issues/issues/detail?id=929 // Try to find the created spreadsheet: Log.w(Constants.TAG, "Create might have failed. Trying to find created document."); try { Thread.sleep(5000); } catch (InterruptedException e) { Log.e(Constants.TAG, "Sleep interrupted", e); } try { spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper, sheetTitle); } catch (IOException e) { Log.i(Constants.TAG, "Failed create-failed lookup", e); return false; } if (spreadsheetId == null) { progressIndicator.setProgressValue(87); // Re-try try { Thread.sleep(5000); } catch (InterruptedException e) { Log.e(Constants.TAG, "Sleep interrupted", e); } try { spreadsheetId = docsHelper.requestSpreadsheetId(docListWrapper, sheetTitle); } catch (IOException e) { Log.i(Constants.TAG, "Failed create-failed relookup", e); return false; } } if (spreadsheetId == null) { Log.i(Constants.TAG, "Creating new spreadsheet really failed."); return false; } } } String worksheetId = null; try { worksheetId = docsHelper.getWorksheetId(trixWrapper, spreadsheetId); if (worksheetId == null) { throw new IOException("Worksheet ID lookup returned empty"); } } catch (IOException e) { Log.i(Constants.TAG, "Looking up worksheet id failed.", e); return false; } progressIndicator.setProgressValue(90); docsHelper.addTrackRow(activity, trixAuth, spreadsheetId, worksheetId, track, metricUnits); Log.i(Constants.TAG, "Done uploading to docs."); } catch (IOException e) { Log.e(Constants.TAG, "Unable to upload docs.", e); return false; } finally { if (androidClient != null) { androidClient.close(); } } return true; } }
Java
/* * Copyright 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.wireless.gdata.docs; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.client.GDataServiceClient; import com.google.wireless.gdata.client.HttpException; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.data.StringUtils; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.serializer.GDataSerializer; import com.google.wireless.gdata2.client.AuthenticationException; import java.io.IOException; import java.io.InputStream; /** * GDataServiceClient for accessing Google Spreadsheets. This client can access * and parse all of the Spreadsheets feed types: Spreadsheets feed, Worksheets * feed, List feed, and Cells feed. Read operations are supported on all feed * types, but only the List and Cells feeds support write operations. (This is a * limitation of the protocol, not this API. Such write access may be added to * the protocol in the future, requiring changes to this implementation.) * * Only 'private' visibility and 'full' projections are currently supported. */ public class SpreadsheetsClient extends GDataServiceClient { /** The name of the service, dictated to be 'wise' by the protocol. */ private static final String SERVICE = "wise"; /** Standard base feed url for spreadsheets. */ public static final String SPREADSHEETS_BASE_FEED_URL = "http://spreadsheets.google.com/feeds/spreadsheets/private/full"; /** * Represents an entry in a GData Spreadsheets meta-feed. */ public static class SpreadsheetEntry extends Entry { } /** * Represents an entry in a GData Worksheets meta-feed. */ public static class WorksheetEntry extends Entry { } /** * Creates a new SpreadsheetsClient. Uses the standard base URL for * spreadsheets feeds. * * @param client The GDataClient that should be used to authenticate requests, * retrieve feeds, etc */ public SpreadsheetsClient(GDataClient client, GDataParserFactory spreadsheetFactory) { super(client, spreadsheetFactory); } @Override public String getServiceName() { return SERVICE; } /** * Returns a parser for the specified feed type. * * @param feedEntryClass the Class of entry type that will be parsed, which * lets this method figure out which parser to create * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws AuthenticationException if the authToken is not valid * @throws ParseException if the response from the server could not be parsed */ private GDataParser getParserForTypedFeed( Class<? extends Entry> feedEntryClass, String feedUri, String authToken) throws AuthenticationException, ParseException, IOException { GDataClient gDataClient = getGDataClient(); GDataParserFactory gDataParserFactory = getGDataParserFactory(); try { InputStream is = gDataClient.getFeedAsStream(feedUri, authToken); return gDataParserFactory.createParser(feedEntryClass, is); } catch (HttpException e) { convertHttpExceptionForReads("Could not fetch parser feed.", e); return null; // never reached } } /** * Converts an HTTP exception that happened while reading into the equivalent * local exception. */ public void convertHttpExceptionForReads(String message, HttpException cause) throws AuthenticationException, IOException { switch (cause.getStatusCode()) { case HttpException.SC_FORBIDDEN: case HttpException.SC_UNAUTHORIZED: throw new AuthenticationException(message, cause); case HttpException.SC_GONE: default: throw new IOException(message + ": " + cause.getMessage()); } } @Override public Entry createEntry(String feedUri, String authToken, Entry entry) throws ParseException, IOException { GDataParserFactory factory = getGDataParserFactory(); GDataSerializer serializer = factory.createSerializer(entry); InputStream is; try { is = getGDataClient().createEntry(feedUri, authToken, serializer); } catch (HttpException e) { convertHttpExceptionForWrites(entry.getClass(), "Could not update entry.", e); return null; // never reached. } GDataParser parser = factory.createParser(entry.getClass(), is); try { return parser.parseStandaloneEntry(); } finally { parser.close(); } } /** * Fetches a GDataParser for the indicated feed. The parser can be used to * access the contents of URI. WARNING: because we cannot reliably infer the * feed type from the URI alone, this method assumes the default feed type! * This is probably NOT what you want. Please use the getParserFor[Type]Feed * methods. * * @param feedEntryClass * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws ParseException if the response from the server could not be parsed */ @SuppressWarnings("unchecked") @Override public GDataParser getParserForFeed( Class feedEntryClass, String feedUri, String authToken) throws ParseException, IOException { try { return getParserForTypedFeed(SpreadsheetEntry.class, feedUri, authToken); } catch (AuthenticationException e) { throw new IOException("Authentication Failure: " + e.getMessage()); } } /** * Returns a parser for a Worksheets meta-feed. * * @param feedUri the URI of the feed to be fetched and parsed * @param authToken the current authToken to use for the request * @return a parser for the indicated feed * @throws AuthenticationException if the authToken is not valid * @throws ParseException if the response from the server could not be parsed */ public GDataParser getParserForWorksheetsFeed( String feedUri, String authToken) throws AuthenticationException, ParseException, IOException { return getParserForTypedFeed(WorksheetEntry.class, feedUri, authToken); } /** * Updates an entry. The URI to be updated is taken from <code>entry</code>. * Note that only entries in List and Cells feeds can be updated, so * <code>entry</code> must be of the corresponding type; other types will * result in an exception. * * @param entry the entry to be updated; must include its URI * @param authToken the current authToken to be used for the operation * @return An Entry containing the re-parsed version of the entry returned by * the server in response to the update * @throws ParseException if the server returned an error, if the server's * response was unparseable (unlikely), or if <code>entry</code> is of * a read-only type * @throws IOException on network error */ @Override public Entry updateEntry(Entry entry, String authToken) throws ParseException, IOException { GDataParserFactory factory = getGDataParserFactory(); GDataSerializer serializer = factory.createSerializer(entry); String editUri = entry.getEditUri(); if (StringUtils.isEmpty(editUri)) { throw new ParseException("No edit URI -- cannot update."); } InputStream is; try { is = getGDataClient().updateEntry(editUri, authToken, serializer); } catch (HttpException e) { convertHttpExceptionForWrites(entry.getClass(), "Could not update entry.", e); return null; // never reached } GDataParser parser = factory.createParser(entry.getClass(), is); try { return parser.parseStandaloneEntry(); } finally { parser.close(); } } /** * Converts an HTTP exception which happened while writing to the equivalent * local exception. */ @SuppressWarnings("unchecked") private void convertHttpExceptionForWrites( Class entryClass, String message, HttpException cause) throws ParseException, IOException { switch (cause.getStatusCode()) { case HttpException.SC_CONFLICT: if (entryClass != null) { InputStream is = cause.getResponseStream(); if (is != null) { parseEntry(entryClass, cause.getResponseStream()); } } throw new IOException(message); case HttpException.SC_BAD_REQUEST: throw new ParseException(message + ": " + cause); case HttpException.SC_FORBIDDEN: case HttpException.SC_UNAUTHORIZED: throw new IOException(message); default: throw new IOException(message + ": " + cause.getMessage()); } } /** * Parses one entry from the input stream. */ @SuppressWarnings("unchecked") private Entry parseEntry(Class entryClass, InputStream is) throws ParseException, IOException { GDataParser parser = null; try { parser = getGDataParserFactory().createParser(entryClass, is); return parser.parseStandaloneEntry(); } finally { if (parser != null) { parser.close(); } } } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.wireless.gdata.docs; import com.google.wireless.gdata.client.GDataClient; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.client.GDataServiceClient; /** * GDataServiceClient for accessing Google Documents. This is not a full * implementation. */ public class DocumentsClient extends GDataServiceClient { /** The name of the service, dictated to be 'wise' by the protocol. */ private static final String SERVICE = "writely"; /** * Creates a new DocumentsClient. * * @param client The GDataClient that should be used to authenticate requests, * retrieve feeds, etc * @param parserFactory The GDataParserFactory that should be used to obtain * GDataParsers used by this client */ public DocumentsClient(GDataClient client, GDataParserFactory parserFactory) { super(client, parserFactory); } @Override public String getServiceName() { return SERVICE; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.wireless.gdata.docs; import com.google.wireless.gdata.client.GDataParserFactory; import com.google.wireless.gdata.data.Entry; import com.google.wireless.gdata.parser.GDataParser; import com.google.wireless.gdata.parser.ParseException; import com.google.wireless.gdata.parser.xml.XmlGDataParser; import com.google.wireless.gdata.parser.xml.XmlParserFactory; import com.google.wireless.gdata.serializer.GDataSerializer; import com.google.wireless.gdata.serializer.xml.XmlEntryGDataSerializer; import java.io.InputStream; import org.xmlpull.v1.XmlPullParserException; /** * Factory of Xml parsers for gdata maps data. */ public class XmlDocsGDataParserFactory implements GDataParserFactory { private XmlParserFactory xmlFactory; public XmlDocsGDataParserFactory(XmlParserFactory xmlFactory) { this.xmlFactory = xmlFactory; } @Override public GDataParser createParser(InputStream is) throws ParseException { try { return new XmlGDataParser(is, xmlFactory.createParser()); } catch (XmlPullParserException e) { e.printStackTrace(); return null; } } @SuppressWarnings("unchecked") @Override public GDataParser createParser(Class cls, InputStream is) throws ParseException { try { return createParserForClass(is); } catch (XmlPullParserException e) { e.printStackTrace(); return null; } } private GDataParser createParserForClass(InputStream is) throws ParseException, XmlPullParserException { return new XmlGDataParser(is, xmlFactory.createParser()); } @Override public GDataSerializer createSerializer(Entry en) { return new XmlEntryGDataSerializer(xmlFactory, en); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.os.Parcel; import android.os.Parcelable; /** * A request for the service to create a waypoint at the current location. * * @author Sandor Dornbush */ public class WaypointCreationRequest implements Parcelable { public static enum WaypointType { MARKER, STATISTICS; } private WaypointType type; private String name; private String description; private String iconUrl; public final static WaypointCreationRequest DEFAULT_MARKER = new WaypointCreationRequest(WaypointType.MARKER); public final static WaypointCreationRequest DEFAULT_STATISTICS = new WaypointCreationRequest(WaypointType.STATISTICS); private WaypointCreationRequest(WaypointType type) { this.type = type; } public WaypointCreationRequest(WaypointType type, String name, String description, String iconUrl) { this.type = type; this.name = name; this.description = description; this.iconUrl = iconUrl; } public static class Creator implements Parcelable.Creator<WaypointCreationRequest> { @Override public WaypointCreationRequest createFromParcel(Parcel source) { int i = source.readInt(); if (i > WaypointType.values().length) { throw new IllegalArgumentException("Could not find waypoint type: " + i); } WaypointCreationRequest request = new WaypointCreationRequest(WaypointType.values()[i]); request.description = source.readString(); request.iconUrl = source.readString(); request.name = source.readString(); return request; } public WaypointCreationRequest[] newArray(int size) { return new WaypointCreationRequest[size]; } } public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int arg1) { parcel.writeInt(type.ordinal()); parcel.writeString(description); parcel.writeString(iconUrl); parcel.writeString(name); } public WaypointType getType() { return type; } public String getName() { return name; } public String getDescription() { return description; } public String getIconUrl() { return iconUrl; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * A class representing a (GPS) Track. * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public class Track implements Parcelable { /** * Creator for a Track object. */ public static class Creator implements Parcelable.Creator<Track> { public Track createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Track track = new Track(); track.id = source.readLong(); track.name = source.readString(); track.description = source.readString(); track.mapId = source.readString(); track.category = source.readString(); track.startId = source.readLong(); track.stopId = source.readLong(); track.stats = source.readParcelable(classLoader); track.numberOfPoints = source.readInt(); for (int i = 0; i < track.numberOfPoints; ++i) { Location loc = source.readParcelable(classLoader); track.locations.add(loc); } track.tableId = source.readString(); return track; } public Track[] newArray(int size) { return new Track[size]; } } public static final Creator CREATOR = new Creator(); /** * The track points (which may not have been loaded). */ private ArrayList<Location> locations = new ArrayList<Location>(); /** * The number of location points (present even if the points themselves were * not loaded). */ private int numberOfPoints = 0; private long id = -1; private String name = ""; private String description = ""; private String mapId = ""; private String tableId = ""; private long startId = -1; private long stopId = -1; private String category = ""; private TripStatistics stats = new TripStatistics(); public Track() { } public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(mapId); dest.writeString(category); dest.writeLong(startId); dest.writeLong(stopId); dest.writeParcelable(stats, 0); dest.writeInt(numberOfPoints); for (int i = 0; i < numberOfPoints; ++i) { dest.writeParcelable(locations.get(i), 0); } dest.writeString(tableId); } // Getters and setters: //--------------------- public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getMapId() { return mapId; } public void setMapId(String mapId) { this.mapId = mapId; } public String getTableId() { return tableId; } public void setTableId(String tableId) { this.tableId = tableId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public int getNumberOfPoints() { return numberOfPoints; } public void setNumberOfPoints(int numberOfPoints) { this.numberOfPoints = numberOfPoints; } public void addLocation(Location l) { locations.add(l); } public ArrayList<Location> getLocations() { return locations; } public void setLocations(ArrayList<Location> locations) { this.locations = locations; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.location.Location; /** * This class extends the standard Android location with extra information. * * @author Sandor Dornbush */ public class MyTracksLocation extends Location { private Sensor.SensorDataSet sensorDataSet = null; /** * The id of this location from the provider. */ private int id = -1; public MyTracksLocation(Location location, Sensor.SensorDataSet sd) { super(location); this.sensorDataSet = sd; } public MyTracksLocation(String provider) { super(provider); } public Sensor.SensorDataSet getSensorDataSet() { return sensorDataSet; } public void setSensorData(Sensor.SensorDataSet sensorData) { this.sensorDataSet = sensorData; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void reset() { super.reset(); sensorDataSet = null; id = -1; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface WaypointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/waypoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.waypoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.waypoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String ICON = "icon"; public static final String TRACKID = "trackid"; public static final String TYPE = "type"; public static final String LENGTH = "length"; public static final String DURATION = "duration"; public static final String STARTTIME = "starttime"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the track points provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TrackPointsColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/trackpoints"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.trackpoint"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.trackpoint"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String TRACKID = "trackid"; public static final String LATITUDE = "latitude"; public static final String LONGITUDE = "longitude"; public static final String ALTITUDE = "elevation"; public static final String BEARING = "bearing"; public static final String TIME = "time"; public static final String ACCURACY = "accuracy"; public static final String SPEED = "speed"; public static final String SENSOR = "sensor"; }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import static com.google.android.apps.mytracks.lib.MyTracksLibConstants.TAG; import com.google.android.apps.mytracks.content.Sensor; import com.google.android.apps.mytracks.stats.TripStatistics; import com.google.protobuf.InvalidProtocolBufferException; import android.content.ContentResolver; import android.content.ContentValues; import android.database.Cursor; import android.location.Location; import android.net.Uri; import android.util.Log; import java.util.ArrayList; import java.util.List; import java.util.NoSuchElementException; /** * Helper class providing easy access to locations and tracks in the * MyTracksProvider. All static members. * * @author Leif Hendrik Wilden */ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final ContentResolver contentResolver; private int defaultCursorBatchSize = 2000; public MyTracksProviderUtilsImpl(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * Creates the ContentValues for a given location object. * * @param location a given location * @param trackId the id of the track it belongs to * @return a filled in ContentValues object */ private static ContentValues createContentValues( Location location, long trackId) { ContentValues values = new ContentValues(); values.put(TrackPointsColumns.TRACKID, trackId); values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); // This is an ugly hack for Samsung phones that don't properly populate the // time field. values.put(TrackPointsColumns.TIME, (location.getTime() == 0) ? System.currentTimeMillis() : location.getTime()); if (location.hasAltitude()) { values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(TrackPointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(TrackPointsColumns.SPEED, location.getSpeed()); } if (location instanceof MyTracksLocation) { MyTracksLocation mtLocation = (MyTracksLocation) location; if (mtLocation.getSensorDataSet() != null) { values.put(TrackPointsColumns.SENSOR, mtLocation.getSensorDataSet().toByteArray()); } } return values; } @Override public ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics stats = track.getStatistics(); // Values id < 0 indicate no id is available: if (track.getId() >= 0) { values.put(TracksColumns._ID, track.getId()); } values.put(TracksColumns.NAME, track.getName()); values.put(TracksColumns.DESCRIPTION, track.getDescription()); values.put(TracksColumns.MAPID, track.getMapId()); values.put(TracksColumns.TABLEID, track.getTableId()); values.put(TracksColumns.CATEGORY, track.getCategory()); values.put(TracksColumns.NUMPOINTS, track.getNumberOfPoints()); values.put(TracksColumns.STARTID, track.getStartId()); values.put(TracksColumns.STARTTIME, stats.getStartTime()); values.put(TracksColumns.STOPTIME, stats.getStopTime()); values.put(TracksColumns.STOPID, track.getStopId()); values.put(TracksColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(TracksColumns.TOTALTIME, stats.getTotalTime()); values.put(TracksColumns.MOVINGTIME, stats.getMovingTime()); values.put(TracksColumns.MAXLAT, stats.getTop()); values.put(TracksColumns.MINLAT, stats.getBottom()); values.put(TracksColumns.MAXLON, stats.getRight()); values.put(TracksColumns.MINLON, stats.getLeft()); values.put(TracksColumns.AVGSPEED, stats.getAverageSpeed()); values.put(TracksColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(TracksColumns.MAXSPEED, stats.getMaxSpeed()); values.put(TracksColumns.MINELEVATION, stats.getMinElevation()); values.put(TracksColumns.MAXELEVATION, stats.getMaxElevation()); values.put(TracksColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(TracksColumns.MINGRADE, stats.getMinGrade()); values.put(TracksColumns.MAXGRADE, stats.getMaxGrade()); return values; } private static ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); // Values id < 0 indicate no id is available: if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); } values.put(WaypointsColumns.NAME, waypoint.getName()); values.put(WaypointsColumns.DESCRIPTION, waypoint.getDescription()); values.put(WaypointsColumns.CATEGORY, waypoint.getCategory()); values.put(WaypointsColumns.ICON, waypoint.getIcon()); values.put(WaypointsColumns.TRACKID, waypoint.getTrackId()); values.put(WaypointsColumns.TYPE, waypoint.getType()); values.put(WaypointsColumns.LENGTH, waypoint.getLength()); values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); TripStatistics stats = waypoint.getStatistics(); if (stats != null) { values.put(WaypointsColumns.TOTALDISTANCE, stats.getTotalDistance()); values.put(WaypointsColumns.TOTALTIME, stats.getTotalTime()); values.put(WaypointsColumns.MOVINGTIME, stats.getMovingTime()); values.put(WaypointsColumns.AVGSPEED, stats.getAverageSpeed()); values.put(WaypointsColumns.AVGMOVINGSPEED, stats.getAverageMovingSpeed()); values.put(WaypointsColumns.MAXSPEED, stats.getMaxSpeed()); values.put(WaypointsColumns.MINELEVATION, stats.getMinElevation()); values.put(WaypointsColumns.MAXELEVATION, stats.getMaxElevation()); values.put(WaypointsColumns.ELEVATIONGAIN, stats.getTotalElevationGain()); values.put(WaypointsColumns.MINGRADE, stats.getMinGrade()); values.put(WaypointsColumns.MAXGRADE, stats.getMaxGrade()); values.put(WaypointsColumns.STARTTIME, stats.getStartTime()); } Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); values.put(WaypointsColumns.TIME, location.getTime()); if (location.hasAltitude()) { values.put(WaypointsColumns.ALTITUDE, location.getAltitude()); } if (location.hasBearing()) { values.put(WaypointsColumns.BEARING, location.getBearing()); } if (location.hasAccuracy()) { values.put(WaypointsColumns.ACCURACY, location.getAccuracy()); } if (location.hasSpeed()) { values.put(WaypointsColumns.SPEED, location.getSpeed()); } } return values; } @Override public Location createLocation(Cursor cursor) { Location location = new MyTracksLocation(""); fillLocation(cursor, location); return location; } /** * A cache of track column indices. */ private static class CachedTrackColumnIndices { public final int idxId; public final int idxLatitude; public final int idxLongitude; public final int idxAltitude; public final int idxTime; public final int idxBearing; public final int idxAccuracy; public final int idxSpeed; public final int idxSensor; public CachedTrackColumnIndices(Cursor cursor) { idxId = cursor.getColumnIndex(TrackPointsColumns._ID); idxLatitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LATITUDE); idxLongitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.LONGITUDE); idxAltitude = cursor.getColumnIndexOrThrow(TrackPointsColumns.ALTITUDE); idxTime = cursor.getColumnIndexOrThrow(TrackPointsColumns.TIME); idxBearing = cursor.getColumnIndexOrThrow(TrackPointsColumns.BEARING); idxAccuracy = cursor.getColumnIndexOrThrow(TrackPointsColumns.ACCURACY); idxSpeed = cursor.getColumnIndexOrThrow(TrackPointsColumns.SPEED); idxSensor = cursor.getColumnIndexOrThrow(TrackPointsColumns.SENSOR); } } private void fillLocation(Cursor cursor, CachedTrackColumnIndices columnIndices, Location location) { location.reset(); if (!cursor.isNull(columnIndices.idxLatitude)) { location.setLatitude(1. * cursor.getInt(columnIndices.idxLatitude) / 1E6); } if (!cursor.isNull(columnIndices.idxLongitude)) { location.setLongitude(1. * cursor.getInt(columnIndices.idxLongitude) / 1E6); } if (!cursor.isNull(columnIndices.idxAltitude)) { location.setAltitude(cursor.getFloat(columnIndices.idxAltitude)); } if (!cursor.isNull(columnIndices.idxTime)) { location.setTime(cursor.getLong(columnIndices.idxTime)); } if (!cursor.isNull(columnIndices.idxBearing)) { location.setBearing(cursor.getFloat(columnIndices.idxBearing)); } if (!cursor.isNull(columnIndices.idxSpeed)) { location.setSpeed(cursor.getFloat(columnIndices.idxSpeed)); } if (!cursor.isNull(columnIndices.idxAccuracy)) { location.setAccuracy(cursor.getFloat(columnIndices.idxAccuracy)); } if (location instanceof MyTracksLocation && !cursor.isNull(columnIndices.idxSensor)) { MyTracksLocation mtLocation = (MyTracksLocation) location; // TODO get the right buffer. Sensor.SensorDataSet sensorData; try { sensorData = Sensor.SensorDataSet.parseFrom(cursor.getBlob(columnIndices.idxSensor)); mtLocation.setSensorData(sensorData); } catch (InvalidProtocolBufferException e) { Log.w(TAG, "Failed to parse sensor data.", e); } } } @Override public void fillLocation(Cursor cursor, Location location) { CachedTrackColumnIndices columnIndicies = new CachedTrackColumnIndices(cursor); fillLocation(cursor, columnIndicies, location); } @Override public Track createTrack(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(TracksColumns._ID); int idxName = cursor.getColumnIndexOrThrow(TracksColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(TracksColumns.DESCRIPTION); int idxMapId = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int idxTableId = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int idxCategory = cursor.getColumnIndexOrThrow(TracksColumns.CATEGORY); int idxStartId = cursor.getColumnIndexOrThrow(TracksColumns.STARTID); int idxStartTime = cursor.getColumnIndexOrThrow(TracksColumns.STARTTIME); int idxStopTime = cursor.getColumnIndexOrThrow(TracksColumns.STOPTIME); int idxStopId = cursor.getColumnIndexOrThrow(TracksColumns.STOPID); int idxNumPoints = cursor.getColumnIndexOrThrow(TracksColumns.NUMPOINTS); int idxMaxlat = cursor.getColumnIndexOrThrow(TracksColumns.MAXLAT); int idxMinlat = cursor.getColumnIndexOrThrow(TracksColumns.MINLAT); int idxMaxlon = cursor.getColumnIndexOrThrow(TracksColumns.MAXLON); int idxMinlon = cursor.getColumnIndexOrThrow(TracksColumns.MINLON); int idxTotalDistance = cursor.getColumnIndexOrThrow(TracksColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(TracksColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(TracksColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(TracksColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(TracksColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(TracksColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(TracksColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(TracksColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(TracksColumns.MAXGRADE); Track track = new Track(); TripStatistics stats = track.getStatistics(); if (!cursor.isNull(idxId)) { track.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { track.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { track.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxMapId)) { track.setMapId(cursor.getString(idxMapId)); } if (!cursor.isNull(idxTableId)) { track.setTableId(cursor.getString(idxTableId)); } if (!cursor.isNull(idxCategory)) { track.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxStartId)) { track.setStartId(cursor.getInt(idxStartId)); } if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); } if (!cursor.isNull(idxStopTime)) { stats.setStopTime(cursor.getLong(idxStopTime)); } if (!cursor.isNull(idxStopId)) { track.setStopId(cursor.getInt(idxStopId)); } if (!cursor.isNull(idxNumPoints)) { track.setNumberOfPoints(cursor.getInt(idxNumPoints)); } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); } if (!cursor.isNull(idxMaxlat) && !cursor.isNull(idxMinlat) && !cursor.isNull(idxMaxlon) && !cursor.isNull(idxMinlon)) { int top = cursor.getInt(idxMaxlat); int bottom = cursor.getInt(idxMinlat); int right = cursor.getInt(idxMaxlon); int left = cursor.getInt(idxMinlon); stats.setBounds(left, top, right, bottom); } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); } return track; } @Override public Waypoint createWaypoint(Cursor cursor) { int idxId = cursor.getColumnIndexOrThrow(WaypointsColumns._ID); int idxName = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME); int idxDescription = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION); int idxCategory = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY); int idxIcon = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON); int idxTrackId = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID); int idxType = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE); int idxLength = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH); int idxDuration = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION); int idxStartTime = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME); int idxStartId = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID); int idxStopId = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID); int idxTotalDistance = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE); int idxTotalTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME); int idxMovingTime = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME); int idxMaxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED); int idxMinElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION); int idxMaxElevation = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION); int idxElevationGain = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int idxMinGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int idxMaxGrade = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); int idxLatitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE); int idxLongitude = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE); int idxAltitude = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE); int idxTime = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME); int idxBearing = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING); int idxAccuracy = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY); int idxSpeed = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED); Waypoint waypoint = new Waypoint(); if (!cursor.isNull(idxId)) { waypoint.setId(cursor.getLong(idxId)); } if (!cursor.isNull(idxName)) { waypoint.setName(cursor.getString(idxName)); } if (!cursor.isNull(idxDescription)) { waypoint.setDescription(cursor.getString(idxDescription)); } if (!cursor.isNull(idxCategory)) { waypoint.setCategory(cursor.getString(idxCategory)); } if (!cursor.isNull(idxIcon)) { waypoint.setIcon(cursor.getString(idxIcon)); } if (!cursor.isNull(idxTrackId)) { waypoint.setTrackId(cursor.getLong(idxTrackId)); } if (!cursor.isNull(idxType)) { waypoint.setType(cursor.getInt(idxType)); } if (!cursor.isNull(idxLength)) { waypoint.setLength(cursor.getDouble(idxLength)); } if (!cursor.isNull(idxDuration)) { waypoint.setDuration(cursor.getLong(idxDuration)); } if (!cursor.isNull(idxStartId)) { waypoint.setStartId(cursor.getLong(idxStartId)); } if (!cursor.isNull(idxStopId)) { waypoint.setStopId(cursor.getLong(idxStopId)); } TripStatistics stats = new TripStatistics(); boolean hasStats = false; if (!cursor.isNull(idxStartTime)) { stats.setStartTime(cursor.getLong(idxStartTime)); hasStats = true; } if (!cursor.isNull(idxTotalDistance)) { stats.setTotalDistance(cursor.getFloat(idxTotalDistance)); hasStats = true; } if (!cursor.isNull(idxTotalTime)) { stats.setTotalTime(cursor.getLong(idxTotalTime)); hasStats = true; } if (!cursor.isNull(idxMovingTime)) { stats.setMovingTime(cursor.getLong(idxMovingTime)); hasStats = true; } if (!cursor.isNull(idxMaxSpeed)) { stats.setMaxSpeed(cursor.getFloat(idxMaxSpeed)); hasStats = true; } if (!cursor.isNull(idxMinElevation)) { stats.setMinElevation(cursor.getFloat(idxMinElevation)); hasStats = true; } if (!cursor.isNull(idxMaxElevation)) { stats.setMaxElevation(cursor.getFloat(idxMaxElevation)); hasStats = true; } if (!cursor.isNull(idxElevationGain)) { stats.setTotalElevationGain(cursor.getFloat(idxElevationGain)); hasStats = true; } if (!cursor.isNull(idxMinGrade)) { stats.setMinGrade(cursor.getFloat(idxMinGrade)); hasStats = true; } if (!cursor.isNull(idxMaxGrade)) { stats.setMaxGrade(cursor.getFloat(idxMaxGrade)); hasStats = true; } if (hasStats) { waypoint.setStatistics(stats); } Location location = new Location(""); if (!cursor.isNull(idxLatitude) && !cursor.isNull(idxLongitude)) { location.setLatitude(1. * cursor.getInt(idxLatitude) / 1E6); location.setLongitude(1. * cursor.getInt(idxLongitude) / 1E6); } if (!cursor.isNull(idxAltitude)) { location.setAltitude(cursor.getFloat(idxAltitude)); } if (!cursor.isNull(idxTime)) { location.setTime(cursor.getLong(idxTime)); } if (!cursor.isNull(idxBearing)) { location.setBearing(cursor.getFloat(idxBearing)); } if (!cursor.isNull(idxSpeed)) { location.setSpeed(cursor.getFloat(idxSpeed)); } if (!cursor.isNull(idxAccuracy)) { location.setAccuracy(cursor.getFloat(idxAccuracy)); } waypoint.setLocation(location); return waypoint; } @Override public void deleteAllTracks() { contentResolver.delete(TracksColumns.CONTENT_URI, null, null); contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); } @Override public void deleteTrack(long trackId) { Track track = getTrack(trackId); if (track != null) { contentResolver.delete(TrackPointsColumns.CONTENT_URI, "_id>=" + track.getStartId() + " AND _id<=" + track.getStopId(), null); } contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=" + trackId, null); contentResolver.delete( TracksColumns.CONTENT_URI, "_id=" + trackId, null); } @Override public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { final Waypoint deletedWaypoint = getWaypoint(waypointId); if (deletedWaypoint != null && deletedWaypoint.getType() == Waypoint.TYPE_STATISTICS) { final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(deletedWaypoint); if (nextWaypoint != null) { Log.d(TAG, "Correcting marker " + nextWaypoint.getId() + " after deleted marker " + deletedWaypoint.getId()); nextWaypoint.getStatistics().merge(deletedWaypoint.getStatistics()); nextWaypoint.setDescription( descriptionGenerator.generateWaypointDescription(nextWaypoint)); if (!updateWaypoint(nextWaypoint)) { Log.w(TAG, "Update of marker was unsuccessful."); } } else { Log.d(TAG, "No statistics marker after the deleted one was found."); } } contentResolver.delete( WaypointsColumns.CONTENT_URI, "_id=" + waypointId, null); } @Override public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { final String selection = WaypointsColumns._ID + ">" + waypoint.getId() + " AND " + WaypointsColumns.TRACKID + "=" + waypoint.getTrackId() + " AND " + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; final String sortOrder = WaypointsColumns._ID + " LIMIT 1"; Cursor cursor = null; try { cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, selection, null /*selectionArgs*/, sortOrder); if (cursor != null && cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public boolean updateWaypoint(Waypoint waypoint) { try { final int rows = contentResolver.update( WaypointsColumns.CONTENT_URI, createContentValues(waypoint), "_id=" + waypoint.getId(), null /*selectionArgs*/); return rows == 1; } catch (RuntimeException e) { Log.e(TAG, "Caught unexpected exception.", e); } return false; } /** * Finds a locations from the provider by the given selection. * * @param select a selection argument that identifies a unique location * @return the fist location matching, or null if not found */ private Location findLocationBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createLocation(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpeceted exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } /** * Finds a track from the provider by the given selection. * * @param select a selection argument that identifies a unique track * @return the first track matching, or null if not found */ private Track findTrackBy(String select) { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, select, null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public Location getLastLocation() { return findLocationBy("_id=(select max(_id) from trackpoints)"); } @Override public Waypoint getFirstWaypoint(long trackId) { if (trackId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1"); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public Waypoint getWaypoint(long waypointId) { if (waypointId < 0) { return null; } Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, null /*projection*/, "_id=" + waypointId, null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return createWaypoint(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return null; } @Override public long getLastLocationId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( TrackPointsColumns.CONTENT_URI, projection, "_id=(select max(_id) from trackpoints WHERE trackid=" + trackId + ")", null /*selectionArgs*/, null /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getFirstWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, "trackid=" + trackId, null /*selectionArgs*/, "_id LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public long getLastWaypointId(long trackId) { if (trackId < 0) { return -1; } final String[] projection = {"_id"}; Cursor cursor = contentResolver.query( WaypointsColumns.CONTENT_URI, projection, WaypointsColumns.TRACKID + "=" + trackId, null /*selectionArgs*/, "_id DESC LIMIT 1" /*sortOrder*/); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { cursor.close(); } } return -1; } @Override public Track getLastTrack() { Cursor cursor = null; try { cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, "_id=(select max(_id) from tracks)", null, null); if (cursor != null && cursor.moveToNext()) { return createTrack(cursor); } } catch (RuntimeException e) { Log.w(TAG, "Caught an unexpected exception.", e); } finally { if (cursor != null) { cursor.close(); } } return null; } @Override public long getLastTrackId() { String[] proj = { TracksColumns._ID }; Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, proj, "_id=(select max(_id) from tracks)", null, null); if (cursor != null) { try { if (cursor.moveToFirst()) { return cursor.getLong( cursor.getColumnIndexOrThrow(TracksColumns._ID)); } } finally { cursor.close(); } } return -1; } @Override public Location getLocation(long id) { if (id < 0) { return null; } String selection = TrackPointsColumns._ID + "=" + id; return findLocationBy(selection); } @Override public Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } String selection; if (minTrackPointId >= 0) { selection = String.format("%s=%d AND %s%s%d", TrackPointsColumns.TRACKID, trackId, TrackPointsColumns._ID, descending ? "<=" : ">=", minTrackPointId); } else { selection = String.format("%s=%d", TrackPointsColumns.TRACKID, trackId); } String sortOrder = "_id " + (descending ? "DESC" : "ASC"); if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } return contentResolver.query(TrackPointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { if (trackId < 0) { return null; } String selection; if (minWaypointId > 0) { selection = String.format("%s=%d AND %s>=%d", WaypointsColumns.TRACKID, trackId, WaypointsColumns._ID, minWaypointId); } else { selection = String.format("%s=%d", WaypointsColumns.TRACKID, trackId); } String sortOrder = "_id ASC"; if (maxWaypoints > 0) { sortOrder += " LIMIT " + maxWaypoints; } return contentResolver.query( WaypointsColumns.CONTENT_URI, null, selection, null, sortOrder); } @Override public Track getTrack(long id) { if (id < 0) { return null; } String select = TracksColumns._ID + "=" + id; return findTrackBy(select); } @Override public List<Track> getAllTracks() { Cursor cursor = getTracksCursor(null); ArrayList<Track> tracks = new ArrayList<Track>(); if (cursor != null) { tracks.ensureCapacity(cursor.getCount()); if (cursor.moveToFirst()) { do { tracks.add(createTrack(cursor)); } while(cursor.moveToNext()); } cursor.close(); } return tracks; } @Override public Cursor getTracksCursor(String selection) { Cursor cursor = contentResolver.query( TracksColumns.CONTENT_URI, null, selection, null, "_id"); return cursor; } @Override public Uri insertTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrack"); return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); } @Override public Uri insertTrackPoint(Location location, long trackId) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertTrackPoint"); return contentResolver.insert(TrackPointsColumns.CONTENT_URI, createContentValues(location, trackId)); } @Override public int bulkInsertTrackPoints(Location[] locations, int length, long trackId) { if (length == -1) { length = locations.length; } ContentValues[] values = new ContentValues[length]; for (int i = 0; i < length; i++) { values[i] = createContentValues(locations[i], trackId); } return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); } @Override public Uri insertWaypoint(Waypoint waypoint) { Log.d(TAG, "MyTracksProviderUtilsImpl.insertWaypoint"); waypoint.setId(-1); return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); } @Override public boolean trackExists(long id) { if (id < 0) { return false; } Cursor cursor = null; try { final String[] projection = { TracksColumns._ID }; cursor = contentResolver.query( TracksColumns.CONTENT_URI, projection, TracksColumns._ID + "=" + id/*selection*/, null/*selectionArgs*/, null/*sortOrder*/); if (cursor != null && cursor.moveToNext()) { return true; } } finally { if (cursor != null) { cursor.close(); } } return false; } @Override public void updateTrack(Track track) { Log.d(TAG, "MyTracksProviderUtilsImpl.updateTrack"); contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), "_id=" + track.getId(), null); } @Override public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("Expecting non-null locationFactory"); } return new LocationIterator() { private long lastTrackPointId = startTrackPointId; private Cursor cursor = getCursor(startTrackPointId); private final CachedTrackColumnIndices columnIndices = cursor != null ? new CachedTrackColumnIndices(cursor) : null; private Cursor getCursor(long trackPointId) { return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } private boolean advanceCursorToNextBatch() { long pointId = lastTrackPointId + (descending ? -1 : 1); Log.d(TAG, "Advancing cursor point ID: " + pointId); cursor.close(); cursor = getCursor(pointId); return cursor != null; } @Override public long getLocationId() { return lastTrackPointId; } @Override public boolean hasNext() { if (cursor == null) { return false; } if (cursor.isAfterLast()) { return false; } if (cursor.isLast()) { // If the current batch size was less that max, we can safely return, otherwise // we need to advance to the next batch. return cursor.getCount() == defaultCursorBatchSize && advanceCursorToNextBatch() && !cursor.isAfterLast(); } return true; } @Override public Location next() { if (cursor == null || !(cursor.moveToNext() || advanceCursorToNextBatch() || cursor.moveToNext())) { throw new NoSuchElementException(); } lastTrackPointId = cursor.getLong(columnIndices.idxId); Location location = locationFactory.createLocation(); fillLocation(cursor, columnIndices, location); return location; } @Override public void close() { if (cursor != null) { cursor.close(); cursor = null; } } @Override public void remove() { throw new UnsupportedOperationException(); } }; } // @VisibleForTesting void setDefaultCursorBatchSize(int defaultCursorBatchSize) { this.defaultCursorBatchSize = defaultCursorBatchSize; } }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.net.Uri; import android.provider.BaseColumns; /** * Defines the URI for the tracks provider and the available column names * and content types. * * @author Leif Hendrik Wilden */ public interface TracksColumns extends BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://com.google.android.maps.mytracks/tracks"); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.google.track"; public static final String CONTENT_ITEMTYPE = "vnd.android.cursor.item/vnd.google.track"; public static final String DEFAULT_SORT_ORDER = "_id"; /* All columns */ public static final String NAME = "name"; public static final String DESCRIPTION = "description"; public static final String CATEGORY = "category"; public static final String STARTID = "startid"; public static final String STOPID = "stopid"; public static final String STARTTIME = "starttime"; public static final String STOPTIME = "stoptime"; public static final String NUMPOINTS = "numpoints"; public static final String TOTALDISTANCE = "totaldistance"; public static final String TOTALTIME = "totaltime"; public static final String MOVINGTIME = "movingtime"; public static final String AVGSPEED = "avgspeed"; public static final String AVGMOVINGSPEED = "avgmovingspeed"; public static final String MAXSPEED = "maxspeed"; public static final String MINELEVATION = "minelevation"; public static final String MAXELEVATION = "maxelevation"; public static final String ELEVATIONGAIN = "elevationgain"; public static final String MINGRADE = "mingrade"; public static final String MAXGRADE = "maxgrade"; public static final String MINLAT = "minlat"; public static final String MAXLAT = "maxlat"; public static final String MINLON = "minlon"; public static final String MAXLON = "maxlon"; public static final String MAPID = "mapid"; public static final String TABLEID = "tableid"; }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; import android.net.Uri; import java.util.Iterator; import java.util.List; /** * Utility to access data from the mytracks content provider. * * @author Rodrigo Damazio */ public interface MyTracksProviderUtils { /** * Authority (first part of URI) for the MyTracks content provider: */ public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** * Deletes all tracks (including track points) from the provider. */ void deleteAllTracks(); /** * Deletes a track with the given track id. * * @param trackId the unique track id */ void deleteTrack(long trackId); /** * Deletes a way point with the given way point id. * This will also correct the next statistics way point after the deleted one * to reflect the deletion. * The generator is needed to stitch together statistics waypoints. * * @param waypointId the unique way point id * @param descriptionGenerator the class to generate descriptions */ void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Finds the next statistics waypoint after the given waypoint. * * @param waypoint a given waypoint * @return the next statistics waypoint, or null if none found. */ Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); /** * Updates the waypoint in the provider. * * @param waypoint * @return true if successful */ boolean updateWaypoint(Waypoint waypoint); /** * Finds the last recorded location from the location provider. * * @return the last location, or null if no locations available */ Location getLastLocation(); /** * Finds the first recorded waypoint for a given track from the location * provider. * This is a special waypoint that holds the stats for current segment. * * @param trackId the id of the track the waypoint belongs to * @return the first waypoint, or null if no waypoints available */ Waypoint getFirstWaypoint(long trackId); /** * Finds the given waypoint from the location provider. * * @param waypointId * @return the waypoint, or null if it does not exist */ Waypoint getWaypoint(long waypointId); /** * Finds the last recorded location id from the track points provider. * * @param trackId find last location on this track * @return the location id, or -1 if no locations available */ long getLastLocationId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getFirstWaypointId(long trackId); /** * Finds the id of the 1st waypoint for a given track. * The 1st waypoint is special as it contains the stats for the current * segment. * * @param trackId find last location on this track * @return the waypoint id, or -1 if no waypoints are available */ long getLastWaypointId(long trackId); /** * Finds the last recorded track from the track provider. * * @return the last track, or null if no tracks available */ Track getLastTrack(); /** * Finds the last recorded track id from the tracks provider. * * @return the track id, or -1 if no tracks available */ long getLastTrackId(); /** * Finds a location by given unique id. * * @param id the desired id * @return a Location object, or null if not found */ Location getLocation(long id); /** * Creates a cursor over the locations in the track points provider which * iterates over a given range of unique ids. * Caller gets to own the returned cursor. Don't forget to close it. * * @param trackId the id of the track for which to get the points * @param minTrackPointId the minimum id for the track points * @param maxLocations maximum number of locations retrieved * @param descending if true the results will be returned in descending id * order (latest location first) * @return A cursor over the selected range of locations */ Cursor getLocationsCursor(long trackId, long minTrackPointId, int maxLocations, boolean descending); /** * Creates a cursor over the waypoints of a track. * Caller gets to own the returned cursor. Don't forget to close it. * * @param trackId the id of the track for which to get the points * @param minWaypointId the minimum id for the track points * @param maxWaypoints the maximum number of waypoints to return * @return A cursor over the selected range of locations */ Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); /** * Finds a track by given unique track id. * Note that the returned track object does not have any track points attached. * Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} to load * the track points. * * @param id desired unique track id * @return a Track object, or null if not found */ Track getTrack(long id); /** * Retrieves all tracks without track points. If no tracks exist, an empty * list will be returned. Use {@link #getLocationIterator(long, long, boolean, LocationFactory)} * to load the track points. * * @return a list of all the recorded tracks */ List<Track> getAllTracks(); /** * Creates a cursor over the tracks provider with a given selection. * Caller gets to own the returned cursor. Don't forget to close it. * * @param selection a given selection * @return a cursor of the selected tracks */ Cursor getTracksCursor(String selection); /** * Inserts a track in the tracks provider. * Note: This does not insert any track points. * Use {@link #insertTrackPoint(Location, long)} to insert them. * * @param track the track to insert * @return the content provider URI for the inserted track */ Uri insertTrack(Track track); /** * Inserts a track point in the tracks provider. * * @param location the location to insert * @return the content provider URI for the inserted track point */ Uri insertTrackPoint(Location location, long trackId); /** * Inserts multiple track points in a single operation. * * @param locations an array of locations to insert * @param length the number of locations (from the beginning of the array) * to actually insert, or -1 for all of them * @param trackId the ID of the track to insert the points into * @return the number of points inserted */ int bulkInsertTrackPoints(Location[] locations, int length, long trackId); /** * Inserts a waypoint in the provider. * * @param waypoint the waypoint to insert * @return the content provider URI for the inserted track */ Uri insertWaypoint(Waypoint waypoint); /** * Tests if a track with given id exists. * * @param id the unique id * @return true if track exists */ boolean trackExists(long id); /** * Updates a track in the content provider. * Note: This will not update any track points. * * @param track a given track */ void updateTrack(Track track); /** * Creates a Track object from a given cursor. * * @param cursor a cursor pointing at a db or provider with tracks * @return a new Track object */ Track createTrack(Cursor cursor); /** * Creates the ContentValues for a given Track object. * * Note: If the track has an id<0 the id column will not be filled. * * @param track a given track object * @return a filled in ContentValues object */ ContentValues createContentValues(Track track); /** * Creates a location object from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @return a new location object */ Location createLocation(Cursor cursor); /** * Fill a location object with values from a given cursor. * * @param cursor a cursor pointing at a db or provider with locations * @param location a location object to be overwritten */ void fillLocation(Cursor cursor, Location location); /** * Creates a waypoint object from a given cursor. * * @param cursor a cursor pointing at a db or provider with waypoints. * @return a new waypoint object */ Waypoint createWaypoint(Cursor cursor); /** * A lightweight wrapper around the original {@link Cursor} with a method to clean up. */ interface LocationIterator extends Iterator<Location> { /** * Returns ID of the most recently retrieved track point through a call to {@link #next()}. * * @return the ID of the most recent track point ID. */ long getLocationId(); /** * Should be called in case the underlying iterator hasn't reached the last record. * Calling it if it has reached the last record is a no-op. */ void close(); } /** * A factory for creating new {@class Location}s. */ interface LocationFactory { /** * Creates a new {@link Location} object to be populated from the underlying database record. * It's up to the implementing class to decide whether to create a new instance or reuse * existing to optimize for speed. * * @return a {@link Location} to be populated from the database. */ Location createLocation(); } /** * The default {@class Location}s factory, which creates a new location of 'gps' type. */ LocationFactory DEFAULT_LOCATION_FACTORY = new LocationFactory() { @Override public Location createLocation() { return new Location("gps"); } }; /** * A location factory which uses two location instances (one for the current location, * and one for the previous), useful when we need to keep the last location. */ public class DoubleBufferedLocationFactory implements LocationFactory { private final Location locs[] = new MyTracksLocation[] { new MyTracksLocation("gps"), new MyTracksLocation("gps") }; private int lastLoc = 0; @Override public Location createLocation() { lastLoc = (lastLoc + 1) % locs.length; return locs[lastLoc]; } } /** * Creates a new read-only iterator over all track points for the given track. It provides * a lightweight way of iterating over long tracks without failing due to the underlying cursor * limitations. Since it's a read-only iterator, {@link Iterator#remove()} always throws * {@class UnsupportedOperationException}. * * Each call to {@link LocationIterator#next()} may advance to the next DB record, and if so, * the iterator calls {@link LocationFactory#createLocation()} and populates it with information * retrieved from the record. * * When done with iteration, you must call {@link LocationIterator#close()} to make sure that all * resources are properly deallocated. * * Example use: * <code> * ... * LocationIterator it = providerUtils.getLocationIterator( * 1, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); * try { * for (Location loc : it) { * ... // Do something useful with the location. * } * } finally { * it.close(); * } * ... * </code> * * @param trackId the ID of a track to retrieve locations for. * @param startTrackPointId the ID of the first track point to load, or -1 to start from * the first point. * @param descending if true the results will be returned in descending ID * order (latest location first). * @param locationFactory the factory for creating new locations. * * @return the read-only iterator over the given track's points. */ LocationIterator getLocationIterator(long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); /** * A factory which can produce instances of {@link MyTracksProviderUtils}, * and can be overridden in tests (a.k.a. poor man's guice). */ public static class Factory { private static Factory instance = new Factory(); /** * Creates and returns an instance of {@link MyTracksProviderUtils} which * uses the given context to access its data. */ public static MyTracksProviderUtils get(Context context) { return instance.newForContext(context); } /** * Returns the global instance of this factory. */ public static Factory getInstance() { return instance; } /** * Overrides the global instance for this factory, to be used for testing. * If used, don't forget to set it back to the original value after the * test is run. */ public static void overrideInstance(Factory factory) { instance = factory; } /** * Creates an instance of {@link MyTracksProviderUtils}. */ protected MyTracksProviderUtils newForContext(Context context) { return new MyTracksProviderUtilsImpl(context.getContentResolver()); } } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import java.util.Vector; /** * An interface for an object that can generate descriptions of waypoints. * * @author Sandor Dornbush */ public interface DescriptionGenerator { /** * Generate a description of the waypoint. */ public String generateWaypointDescription(Waypoint waypoint); /** * Generates a description for a track (with information about the * statistics). * * @param track the track * @return a track description */ public String generateTrackDescription(Track track, Vector<Double> distances, Vector<Double> elevations); }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.content; import com.google.android.apps.mytracks.stats.TripStatistics; import android.location.Location; import android.os.Parcel; import android.os.Parcelable; /** * A way point. It has a location, meta data such as name, description, * category, and icon, plus it can store track statistics for a "sub-track". * * TODO: hashCode and equals * * @author Leif Hendrik Wilden * @author Rodrigo Damazio */ public final class Waypoint implements Parcelable { /** * Creator for a Waypoint object */ public static class Creator implements Parcelable.Creator<Waypoint> { public Waypoint createFromParcel(Parcel source) { ClassLoader classLoader = getClass().getClassLoader(); Waypoint waypoint = new Waypoint(); waypoint.id = source.readLong(); waypoint.name = source.readString(); waypoint.description = source.readString(); waypoint.category = source.readString(); waypoint.icon = source.readString(); waypoint.trackId = source.readLong(); waypoint.type = source.readInt(); waypoint.startId = source.readLong(); waypoint.stopId = source.readLong(); byte hasStats = source.readByte(); if (hasStats > 0) { waypoint.stats = source.readParcelable(classLoader); } byte hasLocation = source.readByte(); if (hasLocation > 0) { waypoint.location = source.readParcelable(classLoader); } return waypoint; } public Waypoint[] newArray(int size) { return new Waypoint[size]; } } public static final Creator CREATOR = new Creator(); public static final int TYPE_WAYPOINT = 0; public static final int TYPE_STATISTICS = 1; private long id = -1; private String name = ""; private String description = ""; private String category = ""; private String icon = ""; private long trackId = -1; private int type = 0; private Location location; /** Start track point id */ private long startId = -1; /** Stop track point id */ private long stopId = -1; private TripStatistics stats; /** The length of the track, without smoothing. */ private double length; /** The total duration of the track (not from the last waypoint) */ private long duration; public void writeToParcel(Parcel dest, int flags) { dest.writeLong(id); dest.writeString(name); dest.writeString(description); dest.writeString(category); dest.writeString(icon); dest.writeLong(trackId); dest.writeInt(type); dest.writeLong(startId); dest.writeLong(stopId); dest.writeByte(stats == null ? (byte) 0 : (byte) 1); if (stats != null) { dest.writeParcelable(stats, 0); } dest.writeByte(location == null ? (byte) 0 : (byte) 1); if (location != null) { dest.writeParcelable(location, 0); } } // Getters and setters: //--------------------- public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Location getLocation() { return location; } public void setTrackId(long trackId) { this.trackId = trackId; } public int describeContents() { return 0; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getTrackId() { return trackId; } public int getType() { return type; } public void setType(int type) { this.type = type; } public long getStartId() { return startId; } public void setStartId(long startId) { this.startId = startId; } public long getStopId() { return stopId; } public void setStopId(long stopId) { this.stopId = stopId; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public void setLocation(Location location) { this.location = location; } public TripStatistics getStatistics() { return stats; } public void setStatistics(TripStatistics stats) { this.stats = stats; } // WARNING: These fields are used for internal state keeping. You probably // want to look at getStatistics instead. public double getLength() { return length; } public void setLength(double length) { this.length = length; } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } }
Java
/* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; /** * A helper class that tracks a minimum and a maximum of a variable. * * @author Sandor Dornbush */ public class ExtremityMonitor { /** * The smallest value seen so far. */ private double min; /** * The largest value seen so far. */ private double max; public ExtremityMonitor() { reset(); } /** * Updates the min and the max with the new value. * * @param value the new value for the monitor * @return true if an extremity was found */ public boolean update(double value) { boolean changed = false; if (value < min) { min = value; changed = true; } if (value > max) { max = value; changed = true; } return changed; } /** * Gets the minimum value seen. * * @return The minimum value passed into the update() function */ public double getMin() { return min; } /** * Gets the maximum value seen. * * @return The maximum value passed into the update() function */ public double getMax() { return max; } /** * Resets this object to it's initial state where the min and max are unknown. */ public void reset() { min = Double.POSITIVE_INFINITY; max = Double.NEGATIVE_INFINITY; } /** * Sets the minimum and maximum values. */ public void set(double min, double max) { this.min = min; this.max = max; } /** * Sets the minimum value. */ public void setMin(double min) { this.min = min; } /** * Sets the maximum value. */ public void setMax(double max) { this.max = max; } public boolean hasData() { return min != Double.POSITIVE_INFINITY && max != Double.NEGATIVE_INFINITY; } @Override public String toString() { return "Min: " + min + " Max: " + max; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.stats; import android.os.Parcel; import android.os.Parcelable; /** * Statistical data about a trip. * The data in this class should be filled out by TripStatisticsBuilder. * * TODO: hashCode and equals * * @author Rodrigo Damazio */ public class TripStatistics implements Parcelable { /** * The start time for the trip. This is system time which might not match gps * time. */ private long startTime = -1; /** * The stop time for the trip. This is the system time which might not match * gps time. */ private long stopTime = -1; /** * The total time that we believe the user was traveling in milliseconds. */ private long movingTime; /** * The total time of the trip in milliseconds. * This is only updated when new points are received, so it may be stale. */ private long totalTime; /** * The total distance in meters that the user traveled on this trip. */ private double totalDistance; /** * The total elevation gained on this trip in meters. */ private double totalElevationGain; /** * The maximum speed in meters/second reported that we believe to be a valid * speed. */ private double maxSpeed; /** * The min and max latitude values seen in this trip. */ private final ExtremityMonitor latitudeExtremities = new ExtremityMonitor(); /** * The min and max longitude values seen in this trip. */ private final ExtremityMonitor longitudeExtremities = new ExtremityMonitor(); /** * The min and max elevation seen on this trip in meters. */ private final ExtremityMonitor elevationExtremities = new ExtremityMonitor(); /** * The minimum and maximum grade calculations on this trip. */ private final ExtremityMonitor gradeExtremities = new ExtremityMonitor(); /** * Default constructor. */ public TripStatistics() { } /** * Copy constructor. * * @param other another statistics data object to copy from */ public TripStatistics(TripStatistics other) { this.maxSpeed = other.maxSpeed; this.movingTime = other.movingTime; this.startTime = other.startTime; this.stopTime = other.stopTime; this.totalDistance = other.totalDistance; this.totalElevationGain = other.totalElevationGain; this.totalTime = other.totalTime; this.latitudeExtremities.set(other.latitudeExtremities.getMin(), other.latitudeExtremities.getMax()); this.longitudeExtremities.set(other.longitudeExtremities.getMin(), other.longitudeExtremities.getMax()); this.elevationExtremities.set(other.elevationExtremities.getMin(), other.elevationExtremities.getMax()); this.gradeExtremities.set(other.gradeExtremities.getMin(), other.gradeExtremities.getMax()); } /** * Combines these statistics with those from another object. * This assumes that the time periods covered by each do not intersect. * * @param other the other waypoint */ public void merge(TripStatistics other) { startTime = Math.min(startTime, other.startTime); stopTime = Math.max(stopTime, other.stopTime); totalTime += other.totalTime; movingTime += other.movingTime; totalDistance += other.totalDistance; totalElevationGain += other.totalElevationGain; maxSpeed = Math.max(maxSpeed, other.maxSpeed); latitudeExtremities.update(other.latitudeExtremities.getMax()); latitudeExtremities.update(other.latitudeExtremities.getMin()); longitudeExtremities.update(other.longitudeExtremities.getMax()); longitudeExtremities.update(other.longitudeExtremities.getMin()); elevationExtremities.update(other.elevationExtremities.getMax()); elevationExtremities.update(other.elevationExtremities.getMin()); gradeExtremities.update(other.gradeExtremities.getMax()); gradeExtremities.update(other.gradeExtremities.getMin()); } /** * Gets the time that this track started. * * @return The number of milliseconds since epoch to the time when this track * started */ public long getStartTime() { return startTime; } /** * Gets the time that this track stopped. * * @return The number of milliseconds since epoch to the time when this track * stopped */ public long getStopTime() { return stopTime; } /** * Gets the total time that this track has been active. * This statistic is only updated when a new point is added to the statistics, * so it may be off. If you need to calculate the proper total time, use * {@link #getStartTime} with the current time. * * @return The total number of milliseconds the track was active */ public long getTotalTime() { return totalTime; } /** * Gets the total distance the user traveled. * * @return The total distance traveled in meters */ public double getTotalDistance() { return totalDistance; } /** * Gets the the average speed the user traveled. * This calculation only takes into account the displacement until the last * point that was accounted for in statistics. * * @return The average speed in m/s */ public double getAverageSpeed() { return totalDistance / ((double) totalTime / 1000); } /** * Gets the the average speed the user traveled when they were actively * moving. * * @return The average moving speed in m/s */ public double getAverageMovingSpeed() { return totalDistance / ((double) movingTime / 1000); } /** * Gets the the maximum speed for this track. * * @return The maximum speed in m/s */ public double getMaxSpeed() { return maxSpeed; } /** * Gets the moving time. * * @return The total number of milliseconds the user was moving */ public long getMovingTime() { return movingTime; } /** * Gets the total elevation gain for this trip. This is calculated as the sum * of all positive differences in the smoothed elevation. * * @return The elevation gain in meters for this trip */ public double getTotalElevationGain() { return totalElevationGain; } /** * Returns the leftmost position (lowest longitude) of the track, in signed * decimal degrees. */ public int getLeft() { return (int) (longitudeExtremities.getMin() * 1E6); } /** * Returns the rightmost position (highest longitude) of the track, in signed * decimal degrees. */ public int getRight() { return (int) (longitudeExtremities.getMax() * 1E6); } /** * Returns the bottommost position (lowest latitude) of the track, in meters. */ public int getBottom() { return (int) (latitudeExtremities.getMin() * 1E6); } /** * Returns the topmost position (highest latitude) of the track, in meters. */ public int getTop() { return (int) (latitudeExtremities.getMax() * 1E6); } /** * Gets the minimum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be more than the current elevation. * * @return The smallest elevation reading for this trip in meters */ public double getMinElevation() { return elevationExtremities.getMin(); } /** * Gets the maximum elevation seen on this trip. This is calculated from the * smoothed elevation so this can actually be less than the current elevation. * * @return The largest elevation reading for this trip in meters */ public double getMaxElevation() { return elevationExtremities.getMax(); } /** * Gets the maximum grade for this trip. * * @return The maximum grade for this trip as a fraction */ public double getMaxGrade() { return gradeExtremities.getMax(); } /** * Gets the minimum grade for this trip. * * @return The minimum grade for this trip as a fraction */ public double getMinGrade() { return gradeExtremities.getMin(); } // Setters - to be used when restoring state or loading from the DB /** * Sets the start time for this trip. * * @param startTime the start time, in milliseconds since the epoch */ public void setStartTime(long startTime) { this.startTime = startTime; } /** * Sets the stop time for this trip. * * @param stopTime the stop time, in milliseconds since the epoch */ public void setStopTime(long stopTime) { this.stopTime = stopTime; } /** * Sets the total moving time. * * @param movingTime the moving time in milliseconds */ public void setMovingTime(long movingTime) { this.movingTime = movingTime; } /** * Sets the total trip time. * * @param totalTime the total trip time in milliseconds */ public void setTotalTime(long totalTime) { this.totalTime = totalTime; } /** * Sets the total trip distance. * * @param totalDistance the trip distance in meters */ public void setTotalDistance(double totalDistance) { this.totalDistance = totalDistance; } /** * Sets the total elevation variation during the trip. * * @param totalElevationGain the elevation variation in meters */ public void setTotalElevationGain(double totalElevationGain) { this.totalElevationGain = totalElevationGain; } /** * Sets the maximum speed reached during the trip. * * @param maxSpeed the maximum speed in meters per second */ public void setMaxSpeed(double maxSpeed) { this.maxSpeed = maxSpeed; } /** * Sets the minimum elevation reached during the trip. * * @param elevation the minimum elevation in meters */ public void setMinElevation(double elevation) { elevationExtremities.setMin(elevation); } /** * Sets the maximum elevation reached during the trip. * * @param elevation the maximum elevation in meters */ public void setMaxElevation(double elevation) { elevationExtremities.setMax(elevation); } /** * Sets the minimum grade obtained during the trip. * * @param grade the grade as a fraction (-1.0 would mean vertical downwards) */ public void setMinGrade(double grade) { gradeExtremities.setMin(grade); } /** * Sets the maximum grade obtained during the trip). * * @param grade the grade as a fraction (1.0 would mean vertical upwards) */ public void setMaxGrade(double grade) { gradeExtremities.setMax(grade); } /** * Sets the bounding box for this trip. * The unit for all parameters is signed decimal degrees (degrees * 1E6). * * @param leftE6 the westmost longitude reached * @param topE6 the northmost latitude reached * @param rightE6 the eastmost longitude reached * @param bottomE6 the southmost latitude reached */ public void setBounds(int leftE6, int topE6, int rightE6, int bottomE6) { latitudeExtremities.set(bottomE6 / 1E6, topE6 / 1E6); longitudeExtremities.set(leftE6 / 1E6, rightE6 / 1E6); } // Data manipulation methods /** * Adds to the current total distance. * * @param distance the distance to add in meters */ void addTotalDistance(double distance) { totalDistance += distance; } /** * Adds to the total elevation variation. * * @param gain the elevation variation in meters */ void addTotalElevationGain(double gain) { totalElevationGain += gain; } /** * Adds to the total moving time of the trip. * * @param time the time in milliseconds */ void addMovingTime(long time) { movingTime += time; } /** * Accounts for a new latitude value for the bounding box. * * @param latitude the latitude value in signed decimal degrees */ void updateLatitudeExtremities(double latitude) { latitudeExtremities.update(latitude); } /** * Accounts for a new longitude value for the bounding box. * * @param longitude the longitude value in signed decimal degrees */ void updateLongitudeExtremities(double longitude) { longitudeExtremities.update(longitude); } /** * Accounts for a new elevation value for the bounding box. * * @param elevation the elevation value in meters */ void updateElevationExtremities(double elevation) { elevationExtremities.update(elevation); } /** * Accounts for a new grade value. * * @param grade the grade value as a fraction */ void updateGradeExtremities(double grade) { gradeExtremities.update(grade); } // String conversion @Override public String toString() { return "TripStatistics { Start Time: " + getStartTime() + "; Total Time: " + getTotalTime() + "; Moving Time: " + getMovingTime() + "; Total Distance: " + getTotalDistance() + "; Elevation Gain: " + getTotalElevationGain() + "; Min Elevation: " + getMinElevation() + "; Max Elevation: " + getMaxElevation() + "; Average Speed: " + getAverageMovingSpeed() + "; Min Grade: " + getMinGrade() + "; Max Grade: " + getMaxGrade() + "}"; } // Parcelable interface and creator /** * Creator of statistics data from parcels. */ public static class Creator implements Parcelable.Creator<TripStatistics> { @Override public TripStatistics createFromParcel(Parcel source) { TripStatistics data = new TripStatistics(); data.startTime = source.readLong(); data.movingTime = source.readLong(); data.totalTime = source.readLong(); data.totalDistance = source.readDouble(); data.totalElevationGain = source.readDouble(); data.maxSpeed = source.readDouble(); double minLat = source.readDouble(); double maxLat = source.readDouble(); data.latitudeExtremities.set(minLat, maxLat); double minLong = source.readDouble(); double maxLong = source.readDouble(); data.longitudeExtremities.set(minLong, maxLong); double minElev = source.readDouble(); double maxElev = source.readDouble(); data.elevationExtremities.set(minElev, maxElev); double minGrade = source.readDouble(); double maxGrade = source.readDouble(); data.gradeExtremities.set(minGrade, maxGrade); return data; } @Override public TripStatistics[] newArray(int size) { return new TripStatistics[size]; } } /** * Creator of {@link TripStatistics} from parcels. */ public static final Creator CREATOR = new Creator(); @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeLong(startTime); dest.writeLong(movingTime); dest.writeLong(totalTime); dest.writeDouble(totalDistance); dest.writeDouble(totalElevationGain); dest.writeDouble(maxSpeed); dest.writeDouble(latitudeExtremities.getMin()); dest.writeDouble(latitudeExtremities.getMax()); dest.writeDouble(longitudeExtremities.getMin()); dest.writeDouble(longitudeExtremities.getMax()); dest.writeDouble(elevationExtremities.getMin()); dest.writeDouble(elevationExtremities.getMax()); dest.writeDouble(gradeExtremities.getMin()); dest.writeDouble(gradeExtremities.getMax()); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.lib; /** * Constants for the My Tracks common library. * These constants should ideally not be used by third-party applications. * * @author Rodrigo Damazio */ public class MyTracksLibConstants { public static final String TAG = "MyTracksLib"; private MyTracksLibConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.Context; import android.telephony.PhoneStateListener; import android.telephony.SignalStrength; import android.telephony.TelephonyManager; import android.util.Log; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerEclair extends SignalStrengthListenerCupcake { private SignalStrength signalStrength = null; public SignalStrengthListenerEclair(Context ctx, SignalStrengthCallback callback) { super(ctx, callback); } @Override protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTHS; } @SuppressWarnings("hiding") @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { Log.d(TAG, "Signal Strength Modern: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ @Override protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: return "1xRTT"; case TelephonyManager.NETWORK_TYPE_CDMA: return "CDMA"; case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_EVDO_0: return "EVDO 0"; case TelephonyManager.NETWORK_TYPE_EVDO_A: return "EVDO A"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_HSDPA: return "HSDPA"; case TelephonyManager.NETWORK_TYPE_HSPA: return "HSPA"; case TelephonyManager.NETWORK_TYPE_HSUPA: return "HSUPA"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ @Override protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public String getStrengthAsString() { if (signalStrength == null) { return "Strength: " + getContext().getString(R.string.unknown) + "\n"; } StringBuffer sb = new StringBuffer(); if (signalStrength.isGsm()) { appendSignal(signalStrength.getGsmSignalStrength(), R.string.gsm_strength, sb); maybeAppendSignal(signalStrength.getGsmBitErrorRate(), R.string.error_rate, sb); } else { appendSignal(signalStrength.getCdmaDbm(), R.string.cdma_strength, sb); appendSignal(signalStrength.getCdmaEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoDbm(), R.string.evdo_strength, sb); appendSignal(signalStrength.getEvdoEcio() / 10.0, R.string.ecio, sb); appendSignal(signalStrength.getEvdoSnr(), R.string.signal_to_noise_ratio, sb); } return sb.toString(); } private void maybeAppendSignal( int signal, int signalFormat, StringBuffer sb) { if (signal > 0) { sb.append(getContext().getString(signalFormat, signal)); } } private void appendSignal(int signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } private void appendSignal(double signal, int signalFormat, StringBuffer sb) { sb.append(getContext().getString(signalFormat, signal)); sb.append("\n"); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Build; /** * Constants for the signal sampler. * * @author Rodrigo Damazio */ public class SignalStrengthConstants { public static final String START_SAMPLING = "com.google.android.apps.mytracks.signalstrength.START"; public static final String STOP_SAMPLING = "com.google.android.apps.mytracks.signalstrength.STOP"; public static final int ANDROID_API_LEVEL = Integer.parseInt( Build.VERSION.SDK); public static final String TAG = "SignalStrengthSampler"; private SignalStrengthConstants() {} }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.START_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.STOP_SAMPLING; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import com.google.android.apps.mytracks.content.WaypointCreationRequest; import com.google.android.apps.mytracks.services.ITrackRecordingService; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.IBinder; import android.os.RemoteException; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import java.util.List; /** * Serivce which actually reads signal strength and sends it to My Tracks. * * @author Rodrigo Damazio */ public class SignalStrengthService extends Service implements ServiceConnection, SignalStrengthCallback, OnSharedPreferenceChangeListener { private ComponentName mytracksServiceComponent; private SharedPreferences preferences; private SignalStrengthListenerFactory signalListenerFactory; private SignalStrengthListener signalListener; private ITrackRecordingService mytracksService; private long lastSamplingTime; private long samplingPeriod; @Override public void onCreate() { super.onCreate(); mytracksServiceComponent = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); preferences = PreferenceManager.getDefaultSharedPreferences(this); signalListenerFactory = new SignalStrengthListenerFactory(); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { String action = intent.getAction(); if (START_SAMPLING.equals(action)) { startSampling(); } else { stopSampling(); } } private void startSampling() { // TODO: Start foreground if (!isMytracksRunning()) { Log.w(TAG, "My Tracks not running!"); return; } Log.d(TAG, "Starting sampling"); Intent intent = new Intent(); intent.setComponent(mytracksServiceComponent); if (!bindService(intent, SignalStrengthService.this, 0)) { Log.e(TAG, "Couldn't bind to service."); return; } } private boolean isMytracksRunning() { ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { if (serviceInfo.pid != 0 && serviceInfo.service.equals(mytracksServiceComponent)) { return true; } } return false; } @Override public void onServiceConnected(ComponentName name, IBinder service) { synchronized (this) { mytracksService = ITrackRecordingService.Stub.asInterface(service); Log.d(TAG, "Bound to My Tracks"); boolean recording = false; try { recording = mytracksService.isRecording(); } catch (RemoteException e) { Log.e(TAG, "Failed to talk to my tracks", e); } if (!recording) { Log.w(TAG, "My Tracks is not recording, bailing"); stopSampling(); return; } // We're ready to send waypoints, so register for signal sampling signalListener = signalListenerFactory.create(this, this); signalListener.register(); // Register for preference changes samplingPeriod = Long.parseLong(preferences.getString( getString(R.string.settings_min_signal_sampling_period_key), "-1")); preferences.registerOnSharedPreferenceChangeListener(this); // Tell the user we've started. Toast.makeText(this, R.string.started_sampling, Toast.LENGTH_SHORT).show(); } } @Override public void onSignalStrengthSampled(String description, String icon) { long now = System.currentTimeMillis(); if (now - lastSamplingTime < samplingPeriod * 60 * 1000) { return; } try { long waypointId; synchronized (this) { if (mytracksService == null) { Log.d(TAG, "No my tracks service to send to"); return; } // Create a waypoint. WaypointCreationRequest request = new WaypointCreationRequest(WaypointCreationRequest.WaypointType.MARKER, "Signal Strength", description, icon); waypointId = mytracksService.insertWaypoint(request); } if (waypointId >= 0) { Log.d(TAG, "Added signal marker"); lastSamplingTime = now; } else { Log.e(TAG, "Cannot insert waypoint marker?"); } } catch (RemoteException e) { Log.e(TAG, "Cannot talk to my tracks service", e); } } private void stopSampling() { Log.d(TAG, "Stopping sampling"); synchronized (this) { // Unregister from preference change updates preferences.unregisterOnSharedPreferenceChangeListener(this); // Unregister from receiving signal updates if (signalListener != null) { signalListener.unregister(); signalListener = null; } // Unbind from My Tracks if (mytracksService != null) { unbindService(this); mytracksService = null; } // Reset the last sampling time lastSamplingTime = 0; // Tell the user we've stopped Toast.makeText(this, R.string.stopped_sampling, Toast.LENGTH_SHORT).show(); // Stop stopSelf(); } } @Override public void onServiceDisconnected(ComponentName name) { Log.i(TAG, "Disconnected from My Tracks"); synchronized (this) { mytracksService = null; } } @Override public void onDestroy() { stopSampling(); super.onDestroy(); } @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { if (getString(R.string.settings_min_signal_sampling_period_key).equals(key)) { samplingPeriod = Long.parseLong(sharedPreferences.getString(key, "-1")); } } @Override public IBinder onBind(Intent intent) { return null; } public static void startService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(START_SAMPLING); context.startService(intent); } public static void stopService(Context context) { Intent intent = new Intent(); intent.setClass(context, SignalStrengthService.class); intent.setAction(STOP_SAMPLING); context.startService(intent); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; /** * Broadcast listener which gets notified when we start or stop recording a track. * * @author Rodrigo Damazio */ public class RecordingStateReceiver extends BroadcastReceiver { @Override public void onReceive(Context ctx, Intent intent) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx); String action = intent.getAction(); if (ctx.getString(R.string.track_started_broadcast_action).equals(action)) { boolean autoStart = preferences.getBoolean( ctx.getString(R.string.settings_auto_start_key), false); if (!autoStart) { Log.d(TAG, "Not auto-starting signal sampling"); return; } startService(ctx); } else if (ctx.getString(R.string.track_stopped_broadcast_action).equals(action)) { boolean autoStop = preferences.getBoolean( ctx.getString(R.string.settings_auto_stop_key), true); if (!autoStop) { Log.d(TAG, "Not auto-stopping signal sampling"); return; } stopService(ctx); } else { Log.e(TAG, "Unknown action received: " + action); } } // @VisibleForTesting protected void stopService(Context ctx) { SignalStrengthService.stopService(ctx); } // @VisibleForTesting protected void startService(Context ctx) { SignalStrengthService.startService(ctx); } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.TAG; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.telephony.CellLocation; import android.telephony.NeighboringCellInfo; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; import java.util.List; /** * A class to monitor the network signal strength. * * TODO: i18n * * @author Sandor Dornbush */ public class SignalStrengthListenerCupcake extends PhoneStateListener implements SignalStrengthListener { private static final Uri APN_URI = Uri.parse("content://telephony/carriers"); private final Context context; private final SignalStrengthCallback callback; private TelephonyManager manager; private int signalStrength = -1; public SignalStrengthListenerCupcake(Context context, SignalStrengthCallback callback) { this.context = context; this.callback = callback; } @Override public void register() { manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); if (manager == null) { Log.e(TAG, "Cannot get telephony manager."); } else { manager.listen(this, getListenEvents()); } } protected int getListenEvents() { return PhoneStateListener.LISTEN_SIGNAL_STRENGTH; } @SuppressWarnings("hiding") @Override public void onSignalStrengthChanged(int signalStrength) { Log.d(TAG, "Signal Strength: " + signalStrength); this.signalStrength = signalStrength; notifySignalSampled(); } protected void notifySignalSampled() { int networkType = manager.getNetworkType(); callback.onSignalStrengthSampled(getDescription(), getIcon(networkType)); } /** * Gets a human readable description for the network type. * * @param type The integer constant for the network type * @return A human readable description of the network type */ protected String getTypeAsString(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_EDGE: return "EDGE"; case TelephonyManager.NETWORK_TYPE_GPRS: return "GPRS"; case TelephonyManager.NETWORK_TYPE_UMTS: return "UMTS"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "UNKNOWN"; } } /** * Builds a description for the current signal strength. * * @return A human readable description of the network state */ private String getDescription() { StringBuilder sb = new StringBuilder(); sb.append(getStrengthAsString()); sb.append("Network Type: "); sb.append(getTypeAsString(manager.getNetworkType())); sb.append('\n'); sb.append("Operator: "); sb.append(manager.getNetworkOperatorName()); sb.append(" / "); sb.append(manager.getNetworkOperator()); sb.append('\n'); sb.append("Roaming: "); sb.append(manager.isNetworkRoaming()); sb.append('\n'); appendCurrentApns(sb); List<NeighboringCellInfo> infos = manager.getNeighboringCellInfo(); Log.i(TAG, "Found " + infos.size() + " cells."); if (infos.size() > 0) { sb.append("Neighbors: "); for (NeighboringCellInfo info : infos) { sb.append(info.toString()); sb.append(' '); } sb.append('\n'); } CellLocation cell = manager.getCellLocation(); if (cell != null) { sb.append("Cell: "); sb.append(cell.toString()); sb.append('\n'); } return sb.toString(); } private void appendCurrentApns(StringBuilder output) { ContentResolver contentResolver = context.getContentResolver(); Cursor cursor = contentResolver.query( APN_URI, new String[] { "name", "apn" }, "current=1", null, null); if (cursor == null) { return; } try { String name = null; String apn = null; while (cursor.moveToNext()) { int nameIdx = cursor.getColumnIndex("name"); int apnIdx = cursor.getColumnIndex("apn"); if (apnIdx < 0 || nameIdx < 0) { continue; } name = cursor.getString(nameIdx); apn = cursor.getString(apnIdx); output.append("APN: "); if (name != null) { output.append(name); } if (apn != null) { output.append(" ("); output.append(apn); output.append(")\n"); } } } finally { cursor.close(); } } /** * Gets the url for the waypoint icon for the current network type. * * @param type The network type * @return A url to a image to use as the waypoint icon */ protected String getIcon(int type) { switch (type) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: return "http://maps.google.com/mapfiles/ms/micons/green.png"; case TelephonyManager.NETWORK_TYPE_UMTS: return "http://maps.google.com/mapfiles/ms/micons/blue.png"; case TelephonyManager.NETWORK_TYPE_UNKNOWN: default: return "http://maps.google.com/mapfiles/ms/micons/red.png"; } } @Override public void unregister() { if (manager != null) { manager.listen(this, PhoneStateListener.LISTEN_NONE); manager = null; } } public String getStrengthAsString() { return "Strength: " + signalStrength + "\n"; } protected Context getContext() { return context; } public SignalStrengthCallback getSignalStrengthCallback() { return callback; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import static com.google.android.apps.mytracks.signalstrength.SignalStrengthConstants.*; import com.google.android.apps.mytracks.signalstrength.SignalStrengthListener.SignalStrengthCallback; import android.content.Context; import android.util.Log; /** * Factory for producing a proper {@link SignalStrengthListenerCupcake} according to the * current API level. * * @author Rodrigo Damazio */ public class SignalStrengthListenerFactory { public SignalStrengthListener create(Context context, SignalStrengthCallback callback) { if (hasModernSignalStrength()) { Log.d(TAG, "TrackRecordingService using modern signal strength api."); return new SignalStrengthListenerEclair(context, callback); } else { Log.w(TAG, "TrackRecordingService using legacy signal strength api."); return new SignalStrengthListenerCupcake(context, callback); } } // @VisibleForTesting protected boolean hasModernSignalStrength() { return ANDROID_API_LEVEL >= 7; } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; /** * Main signal strength sampler activity, which displays preferences. * * @author Rodrigo Damazio */ public class SignalStrengthPreferences extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); // Attach service control funciontality findPreference(getString(R.string.settings_control_start_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.startService(SignalStrengthPreferences.this); return true; } }); findPreference(getString(R.string.settings_control_stop_key)) .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { SignalStrengthService.stopService(SignalStrengthPreferences.this); return true; } }); // TODO: Check that my tracks is installed - if not, give a warning and // offer to go to the android market. } }
Java
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.signalstrength; /** * Interface for the service that reads signal strength. * * @author Rodrigo Damazio */ public interface SignalStrengthListener { /** * Interface for getting notified about a new sampled signal strength. */ public interface SignalStrengthCallback { void onSignalStrengthSampled( String description, String icon); } /** * Starts listening to signal strength. */ void register(); /** * Stops listening to signal strength. */ void unregister(); }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.samples.api; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * A receiver to receive MyTracks notifications. * * @author Jimmy Shih */ public class MyTracksReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); long trackId = intent.getLongExtra(context.getString(R.string.track_id_broadcast_extra), -1L); Toast.makeText(context, action + " " + trackId, Toast.LENGTH_LONG).show(); } }
Java
/* * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.apps.mytracks.samples.api; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.services.ITrackRecordingService; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import java.util.Calendar; import java.util.List; /** * An activity to access MyTracks content provider and service. * * Note you must first install MyTracks before installing this app. * * You also need to enable third party application access inside MyTracks * MyTracks -> menu -> Settings -> Sharing -> Allow access * * @author Jimmy Shih */ public class MainActivity extends Activity { private static final String TAG = MainActivity.class.getSimpleName(); // utils to access the MyTracks content provider private MyTracksProviderUtils myTracksProviderUtils; // display output from the MyTracks content provider private TextView outputTextView; // MyTracks service private ITrackRecordingService myTracksService; // intent to access the MyTracks service private Intent intent; // connection to the MyTracks service private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName className, IBinder service) { myTracksService = ITrackRecordingService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName className) { myTracksService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // for the MyTracks content provider myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this); outputTextView = (TextView) findViewById(R.id.output); Button addWaypointsButton = (Button) findViewById(R.id.add_waypoints_button); addWaypointsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<Track> tracks = myTracksProviderUtils.getAllTracks(); Calendar now = Calendar.getInstance(); for (Track track : tracks) { Waypoint waypoint = new Waypoint(); waypoint.setTrackId(track.getId()); waypoint.setName(now.getTime().toLocaleString()); waypoint.setDescription(now.getTime().toLocaleString()); myTracksProviderUtils.insertWaypoint(waypoint); } } }); // for the MyTracks service intent = new Intent(); ComponentName componentName = new ComponentName( getString(R.string.mytracks_service_package), getString(R.string.mytracks_service_class)); intent.setComponent(componentName); Button startRecordingButton = (Button) findViewById(R.id.start_recording_button); startRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.startNewTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); Button stopRecordingButton = (Button) findViewById(R.id.stop_recording_button); stopRecordingButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (myTracksService != null) { try { myTracksService.endCurrentTrack(); } catch (RemoteException e) { Log.e(TAG, "RemoteException", e); } } } }); } @Override protected void onStart() { super.onStart(); // use the MyTracks content provider to get all the tracks List<Track> tracks = myTracksProviderUtils.getAllTracks(); for (Track track : tracks) { outputTextView.append(track.getId() + " "); } // start and bind the MyTracks service startService(intent); bindService(intent, serviceConnection, 0); } @Override protected void onStop() { super.onStop(); // unbind and stop the MyTracks service if (myTracksService != null) { unbindService(serviceConnection); } stopService(intent); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboListActivity; public abstract class FlurryEnabledListActivity extends RoboListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryApiKey; import java.util.Map; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.content.Context; import com.flurry.android.FlurryAgent; import com.google.inject.Inject; public class Analytics { private Context mContext; @Inject public Analytics(Context context) { mContext = context; } public void start() { if (isEnabled()) { FlurryAgent.onStartSession(mContext, cFlurryApiKey); } } public void stop() { if (isEnabled()) { FlurryAgent.onEndSession(mContext); } } public void onEvent(String eventId, Map<String, String> parameters) { if (isEnabled()) { FlurryAgent.onEvent(eventId, parameters); } } public void onEvent(String eventId) { if (isEnabled()) { FlurryAgent.onEvent(eventId); } } public void onError(String errorId, String message, String errorClass) { if (isEnabled()) { FlurryAgent.onError(errorId, message, errorClass); } } public void onPageView(Context context) { if (isEnabled()) { FlurryAgent.onPageView(); } } private boolean isEnabled() { return Preferences.isAnalyticsEnabled(mContext); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboExpandableListActivity; public abstract class FlurryEnabledExpandableListActivity extends RoboExpandableListActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboPreferenceActivity; public abstract class FlurryEnabledPreferenceActivity extends RoboPreferenceActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import com.google.inject.Inject; import roboguice.activity.RoboActivity; public abstract class FlurryEnabledActivity extends RoboActivity { @Inject protected Analytics mAnalytics; @Override public void onStart() { super.onStart(); mAnalytics.start(); } @Override public void onStop() { super.onStop(); mAnalytics.stop(); } }
Java
package org.dodgybits.shuffle.android.core.activity.flurry; import android.content.Intent; import com.google.inject.Inject; import roboguice.service.RoboService; public abstract class FlurryEnabledService extends RoboService { @Inject protected Analytics mAnalytics; @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); mAnalytics.start(); } @Override public void onDestroy() { super.onDestroy(); mAnalytics.stop(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import static org.dodgybits.shuffle.android.core.util.Constants.cPackage; import static org.dodgybits.shuffle.android.core.util.Constants.cStringType; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import roboguice.inject.InjectView; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.AdapterView.OnItemSelectedListener; public class HelpActivity extends FlurryEnabledActivity { public static final String cHelpPage = "helpPage"; @InjectView(R.id.help_screen) Spinner mHelpSpinner; @InjectView(R.id.help_text) TextView mHelpContent; @InjectView(R.id.previous_button) Button mPrevious; @InjectView(R.id.next_button) Button mNext; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.help); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.help_screens, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mHelpSpinner.setAdapter(adapter); mHelpSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { public void onNothingSelected(AdapterView<?> arg0) { // do nothing } public void onItemSelected(AdapterView<?> parent, View v, int position, long id) { int resId = HelpActivity.this.getResources().getIdentifier( "help" + position, cStringType, cPackage); mHelpContent.setText(HelpActivity.this.getText(resId)); updateNavigationButtons(); } }); mPrevious.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position - 1); } }); mNext.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int position = mHelpSpinner.getSelectedItemPosition(); mHelpSpinner.setSelection(position + 1); } }); setSelectionFromBundle(getIntent().getExtras()); } private void setSelectionFromBundle(Bundle bundle) { int position = 0; if (bundle != null) { position = bundle.getInt(cHelpPage, 0); } mHelpSpinner.setSelection(position); } private void updateNavigationButtons() { int position = mHelpSpinner.getSelectedItemPosition(); mPrevious.setEnabled(position > 0); mNext.setEnabled(position < mHelpSpinner.getCount() - 1); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.core.model.persistence.InitialDataGenerator; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.preference.model.Preferences; import roboguice.inject.InjectView; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import com.google.inject.Inject; public class WelcomeActivity extends FlurryEnabledActivity { private static final String cTag = "WelcomeActivity"; @InjectView(R.id.sample_data_button) Button mSampleDataButton; @InjectView(R.id.clean_slate_button) Button mCleanSlateButton; @Inject InitialDataGenerator mGenerator; private Handler mHandler; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Log.d(cTag, "onCreate"); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.welcome); mSampleDataButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCreateSampleData(); } }); mCleanSlateButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { disableButtons(); startProgressAnimation(); performCleanSlate(); } }); mHandler = new Handler() { @Override public void handleMessage(Message msg) { updateFirstTimePref(false); // Stop the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_OFF); startActivity(new Intent(WelcomeActivity.this, TopLevelActivity.class)); finish(); } }; } private void disableButtons() { mCleanSlateButton.setEnabled(false); mSampleDataButton.setEnabled(false); } private void startProgressAnimation() { // Start the spinner getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS, Window.PROGRESS_VISIBILITY_ON); } private void performCreateSampleData() { Log.i(cTag, "Adding sample data"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.createSampleData(mHandler); } }.start(); } private void performCleanSlate() { Log.i(cTag, "Cleaning the slate"); setProgressBarVisibility(true); new Thread() { public void run() { mGenerator.cleanSlate(mHandler); } }.start(); } private void updateFirstTimePref(boolean value) { SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putBoolean(Preferences.FIRST_TIME, value); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { return MenuUtils.checkCommonItemsSelected(item, this, MenuUtils.INBOX_ID) || super.onOptionsItemSelected(item); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.service.SynchronizationService; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class BootstrapActivity extends FlurryEnabledActivity { private static final String cTag = "BootstrapActivity"; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); Class<? extends Activity> activityClass = null; boolean firstTime = Preferences.isFirstTime(this); if (firstTime) { Log.i(cTag, "First time using Shuffle. Show intro screen"); activityClass = WelcomeActivity.class; } else { activityClass = TopLevelActivity.class; } startService(new Intent(this, SynchronizationService.class)); startActivity(new Intent(this, activityClass)); finish(); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.activity; import com.google.inject.Inject; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.model.persistence.selector.EntitySelector; import org.dodgybits.shuffle.android.core.util.Constants; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.*; import org.dodgybits.shuffle.android.list.config.DueActionsListConfig; import org.dodgybits.shuffle.android.list.config.ListConfig; import org.dodgybits.shuffle.android.list.config.TaskListConfig; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.app.AlertDialog; import android.app.Dialog; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.database.Cursor; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.text.SpannableString; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.util.AndroidException; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; /** * Displays a list of the main activities. */ public class TopLevelActivity extends FlurryEnabledListActivity { private static final String cTag = "TopLevelActivity"; private static final int INBOX = 0; private static final int DUE_TASKS = 1; private static final int TOP_TASKS = 2; private static final int PROJECTS = 3; private static final int CONTEXTS = 4; private static final int TICKLER = 5; private static final int ITEM_COUNT = 6; private static final String[] cProjection = new String[]{"_id"}; private final static int WHATS_NEW_DIALOG = 0; private Integer[] mIconIds = new Integer[ITEM_COUNT]; private AsyncTask<?, ?, ?> mTask; @Inject @Inbox private TaskListConfig mInboxConfig; @Inject @DueTasks private DueActionsListConfig mDueTasksConfig; @Inject @TopTasks private TaskListConfig mTopTasksConfig; @Inject @Tickler private TaskListConfig mTicklerConfig; @Inject @Projects private ListConfig mProjectsConfig; @Inject @Contexts private ListConfig mContextsConfig; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.top_level); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); addVersionToTitle(); checkLastVersion(); } @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.findItem(MenuUtils.SYNC_ID); if (item != null) { item.setVisible(Preferences.validateTracksSettings(this)); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuUtils.addPrefsHelpMenuItems(this, menu); MenuUtils.addSearchMenuItem(this, menu); MenuUtils.addSyncMenuItem(this, menu); return true; } @Override protected void onResume() { Log.d(cTag, "onResume+"); super.onResume(); CursorGenerator[] generators = new CursorGenerator[ITEM_COUNT]; generators[INBOX] = new EntityCursorGenerator(mInboxConfig); generators[DUE_TASKS] = new EntityCursorGenerator(mDueTasksConfig); generators[TOP_TASKS] = new EntityCursorGenerator(mTopTasksConfig); generators[PROJECTS] = new EntityCursorGenerator(mProjectsConfig); generators[CONTEXTS] = new EntityCursorGenerator(mContextsConfig); generators[TICKLER] = new EntityCursorGenerator(mTicklerConfig); mIconIds[INBOX] = R.drawable.inbox; mIconIds[DUE_TASKS] = R.drawable.due_actions; mIconIds[TOP_TASKS] = R.drawable.next_actions; mIconIds[PROJECTS] = R.drawable.projects; mIconIds[CONTEXTS] = R.drawable.contexts; mIconIds[TICKLER] = R.drawable.ic_media_pause; mTask = new CalculateCountTask().execute(generators); String[] perspectives = getResources().getStringArray(R.array.perspectives).clone(); ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.list_item_view, R.id.name, perspectives, mIconIds); setListAdapter(adapter); } @Override protected void onDestroy() { super.onDestroy(); if (mTask != null && mTask.getStatus() != AsyncTask.Status.RUNNING) { mTask.cancel(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (MenuUtils.checkCommonItemsSelected(item, this, -1)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { MenuUtils.checkCommonItemsSelected(position + MenuUtils.INBOX_ID, this, -1, false); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; if (id == WHATS_NEW_DIALOG) { dialog = new AlertDialog.Builder(this) .setTitle(R.string.whats_new_dialog_title) .setPositiveButton(R.string.ok_button_title, null) .setMessage(R.string.whats_new_dialog_message) .create(); } else { dialog = super.onCreateDialog(id); } return dialog; } private interface CursorGenerator { Cursor generate(); } private class EntityCursorGenerator implements CursorGenerator { private EntitySelector mEntitySelector; public EntityCursorGenerator(ListConfig config) { mEntitySelector = config.getEntitySelector(); mEntitySelector = mEntitySelector.builderFrom() .applyListPreferences(TopLevelActivity.this, config.getListPreferenceSettings()) .build(); } public Cursor generate() { return getContentResolver().query( mEntitySelector.getContentUri(), cProjection, mEntitySelector.getSelection(TopLevelActivity.this), mEntitySelector.getSelectionArgs(), mEntitySelector.getSortOrder()); } } private class UriCursorGenerator implements CursorGenerator { private Uri mUri; public UriCursorGenerator(Uri uri) { mUri = uri; } public Cursor generate() { return getContentResolver().query( mUri, cProjection, null, null, null); } } private class CalculateCountTask extends AsyncTask<CursorGenerator, CharSequence[], Void> { public Void doInBackground(CursorGenerator... params) { String[] perspectives = getResources().getStringArray(R.array.perspectives); int colour = getResources().getColor(R.drawable.pale_blue); ForegroundColorSpan span = new ForegroundColorSpan(colour); CharSequence[] labels = new CharSequence[perspectives.length]; int length = perspectives.length; for (int i = 0; i < length; i++) { labels[i] = " " + perspectives[i]; } int[] cachedCounts = Preferences.getTopLevelCounts(TopLevelActivity.this); if (cachedCounts != null && cachedCounts.length == length) { for (int i = 0; i < length; i++) { CharSequence label = labels[i] + " (" + cachedCounts[i] + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, labels[i].length(), label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; } } publishProgress(labels); String cachedCountStr = ""; for (int i = 0; i < length; i++) { CursorGenerator generator = params[i]; Cursor cursor = generator.generate(); int count = cursor.getCount(); cursor.close(); CharSequence label = " " + perspectives[i] + " (" + count + ")"; SpannableString spannable = new SpannableString(label); spannable.setSpan(span, perspectives[i].length() + 2, label.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); labels[i] = spannable; publishProgress(labels); cachedCountStr += count; if (i < length - 1) { cachedCountStr += ","; } } // updated cached counts SharedPreferences.Editor editor = Preferences.getEditor(TopLevelActivity.this); editor.putString(Preferences.TOP_LEVEL_COUNTS_KEY, cachedCountStr); editor.commit(); return null; } @Override public void onProgressUpdate(CharSequence[]... progress) { CharSequence[] labels = progress[0]; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( TopLevelActivity.this, R.layout.list_item_view, R.id.name, labels, mIconIds); int position = getSelectedItemPosition(); setListAdapter(adapter); setSelection(position); } @SuppressWarnings("unused") public void onPostExecute() { mTask = null; } } private void addVersionToTitle() { String title = getTitle().toString(); try { PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0); title += " " + info.versionName; setTitle(title); } catch (AndroidException e) { Log.e(cTag, "Failed to add version to title: " + e.getMessage()); } } private void checkLastVersion() { final int lastVersion = Preferences.getLastVersion(this); if (Math.abs(lastVersion) < Math.abs(Constants.cVersion)) { // This is a new install or an upgrade. // show what's new message SharedPreferences.Editor editor = Preferences.getEditor(this); editor.putInt(Preferences.LAST_VERSION, Constants.cVersion); editor.commit(); showDialog(WHATS_NEW_DIALOG); } } }
Java
package org.dodgybits.shuffle.android.core.activity; import java.util.ArrayList; import java.util.List; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.flurry.FlurryEnabledListActivity; import org.dodgybits.shuffle.android.core.view.IconArrayAdapter; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class LauncherShortcutActivity extends FlurryEnabledListActivity { private static final String cScreenId = "screenId"; private static final int NEW_TASK = 0; private static final int INBOX = 1; private static final int DUE_TASKS = 2; private static final int TOP_TASKS = 3; private static final int PROJECTS = 4; private static final int CONTEXTS = 5; private List<String> mLabels; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); final String action = getIntent().getAction(); setContentView(R.layout.launcher_shortcut); setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); String[] perspectives = getResources().getStringArray(R.array.perspectives); mLabels = new ArrayList<String>(); // TODO figure out a non-retarded way of added padding between text and icon mLabels.add(0, " " + getString(R.string.title_new_task)); for (String label : perspectives) { mLabels.add(" " + label); } if (!Intent.ACTION_CREATE_SHORTCUT.equals(action)) { int screenId = getIntent().getExtras().getInt(cScreenId, -1); if (screenId < INBOX && screenId > CONTEXTS) { // unknown id - just go to BootstrapActivity startActivity(new Intent(this, BootstrapActivity.class)); } else { int menuIndex = (screenId - INBOX) + MenuUtils.INBOX_ID; MenuUtils.checkCommonItemsSelected( menuIndex, this, -1, false); } finish(); return; } setTitle(R.string.title_shortcut_picker); Integer[] iconIds = new Integer[6]; iconIds[NEW_TASK] = R.drawable.list_add; iconIds[INBOX] = R.drawable.inbox; iconIds[DUE_TASKS] = R.drawable.due_actions; iconIds[TOP_TASKS] = R.drawable.next_actions; iconIds[PROJECTS] = R.drawable.projects; iconIds[CONTEXTS] = R.drawable.contexts; ArrayAdapter<CharSequence> adapter = new IconArrayAdapter( this, R.layout.text_item_view, R.id.name, mLabels.toArray(new String[0]), iconIds); setListAdapter(adapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { Intent shortcutIntent; Parcelable iconResource; if (position == NEW_TASK) { shortcutIntent = new Intent(Intent.ACTION_INSERT, TaskProvider.Tasks.CONTENT_URI); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon_add); } else { shortcutIntent = new Intent(this, LauncherShortcutActivity.class); shortcutIntent.putExtra(cScreenId, position); iconResource = Intent.ShortcutIconResource.fromContext( this, R.drawable.shuffle_icon); } Intent intent = new Intent(); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mLabels.get(position).trim()); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource); // Now, return the result to the launcher setResult(RESULT_OK, intent); finish(); } }
Java
package org.dodgybits.shuffle.android.core.configuration; import android.content.ContextWrapper; import com.google.inject.Provides; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.encoding.ContextEncoder; import org.dodgybits.shuffle.android.core.model.encoding.EntityEncoder; import org.dodgybits.shuffle.android.core.model.encoding.ProjectEncoder; import org.dodgybits.shuffle.android.core.model.encoding.TaskEncoder; import org.dodgybits.shuffle.android.core.model.persistence.ContextPersister; import org.dodgybits.shuffle.android.core.model.persistence.DefaultEntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityCache; import org.dodgybits.shuffle.android.core.model.persistence.EntityPersister; import org.dodgybits.shuffle.android.core.model.persistence.ProjectPersister; import org.dodgybits.shuffle.android.core.model.persistence.TaskPersister; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.view.MenuUtils; import org.dodgybits.shuffle.android.list.annotation.*; import org.dodgybits.shuffle.android.list.config.*; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import roboguice.config.AbstractAndroidModule; import com.google.inject.TypeLiteral; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.no; public class ShuffleModule extends AbstractAndroidModule { @Override protected void configure() { addCaches(); addPersisters(); addEncoders(); addListPreferenceSettings(); addListConfig(); } private void addCaches() { bind(new TypeLiteral<EntityCache<Context>>() {}).to(new TypeLiteral<DefaultEntityCache<Context>>() {}); bind(new TypeLiteral<EntityCache<Project>>() {}).to(new TypeLiteral<DefaultEntityCache<Project>>() {}); } private void addPersisters() { bind(new TypeLiteral<EntityPersister<Context>>() {}).to(ContextPersister.class); bind(new TypeLiteral<EntityPersister<Project>>() {}).to(ProjectPersister.class); bind(new TypeLiteral<EntityPersister<Task>>() {}).to(TaskPersister.class); } private void addEncoders() { bind(new TypeLiteral<EntityEncoder<Context>>() {}).to(ContextEncoder.class); bind(new TypeLiteral<EntityEncoder<Project>>() {}).to(ProjectEncoder.class); bind(new TypeLiteral<EntityEncoder<Task>>() {}).to(TaskEncoder.class); } private void addListPreferenceSettings() { bind(ListPreferenceSettings.class).annotatedWith(Inbox.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cInbox)); bind(ListPreferenceSettings.class).annotatedWith(TopTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cNextTasks) .setDefaultCompleted(Flag.no) .disableCompleted() .disableDeleted() .disableActive()); ListPreferenceSettings projectSettings = new ListPreferenceSettings(StandardTaskQueries.cProjectFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ProjectTasks.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(Projects.class).toInstance(projectSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableProjects.class).toInstance(projectSettings); ListPreferenceSettings contextSettings = new ListPreferenceSettings(StandardTaskQueries.cContextFilterPrefs); bind(ListPreferenceSettings.class).annotatedWith(ContextTasks.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(Contexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(ExpandableContexts.class).toInstance(contextSettings); bind(ListPreferenceSettings.class).annotatedWith(DueTasks.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cDueTasksFilterPrefs).setDefaultCompleted(Flag.no)); bind(ListPreferenceSettings.class).annotatedWith(Tickler.class).toInstance( new ListPreferenceSettings(StandardTaskQueries.cTickler) .setDefaultCompleted(Flag.no) .setDefaultActive(Flag.no)); } private void addListConfig() { bind(DueActionsListConfig.class).annotatedWith(DueTasks.class).to(DueActionsListConfig.class); bind(ContextTasksListConfig.class).annotatedWith(ContextTasks.class).to(ContextTasksListConfig.class); bind(ProjectTasksListConfig.class).annotatedWith(ProjectTasks.class).to(ProjectTasksListConfig.class); bind(ListConfig.class).annotatedWith(Projects.class).to(ProjectListConfig.class); bind(ListConfig.class).annotatedWith(Contexts.class).to(ContextListConfig.class); } @Provides @Inbox TaskListConfig providesInboxTaskListConfig(TaskPersister taskPersister, @Inbox ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cInbox), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_inbox); } }; } @Provides @TopTasks TaskListConfig providesTopTasksTaskListConfig(TaskPersister taskPersister, @TopTasks ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cNextTasks), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.TOP_TASKS_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_next_tasks); } }; } @Provides @Tickler TaskListConfig providesTicklerTaskListConfig(TaskPersister taskPersister, @Tickler ListPreferenceSettings settings) { return new AbstractTaskListConfig( StandardTaskQueries.getQuery(StandardTaskQueries.cTickler), taskPersister, settings) { public int getCurrentViewMenuId() { return MenuUtils.INBOX_ID; } public String createTitle(ContextWrapper context) { return context.getString(R.string.title_tickler); } }; } }
Java
package org.dodgybits.shuffle.android.core; import com.google.inject.Module; import org.dodgybits.shuffle.android.core.configuration.ShuffleModule; import roboguice.application.RoboApplication; import java.util.List; public class ShuffleApplication extends RoboApplication { @Override protected void addApplicationModules(List<Module> modules) { modules.add(new ShuffleModule()); } }
Java
package org.dodgybits.shuffle.android.core.model; public final class Id { private final long mId; public static final Id NONE = new Id(0L); private Id(long id) { mId = id; } public long getId() { return mId; } public boolean isInitialised() { return mId != 0L; } @Override public String toString() { return isInitialised() ? String.valueOf(mId) : ""; } @Override public boolean equals(Object o) { boolean result = false; if (o instanceof Id) { result = ((Id)o).mId == mId; } return result; } @Override public int hashCode() { return (int)mId; } public static Id create(long id) { Id result = NONE; if (id != 0L) { result = new Id(id); } return result; } }
Java
package org.dodgybits.shuffle.android.core.model; public class Reminder { public Integer id; public final int minutes; public final Method method; public Reminder(Integer id, int minutes, Method method) { this.id = id; this.minutes = minutes; this.method = method; } public Reminder(int minutes, Method method) { this(null, minutes, method); } public static enum Method { DEFAULT, ALERT; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Project implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private Id mDefaultContextId = Id.NONE; private long mModifiedDate; private boolean mParallel; private boolean mArchived; private Id mTracksId = Id.NONE; private boolean mDeleted; private boolean mActive = true; private Project() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final Id getDefaultContextId() { return mDefaultContextId; } public final long getModifiedDate() { return mModifiedDate; } public final boolean isParallel() { return mParallel; } public final boolean isArchived() { return mArchived; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public final boolean isDeleted() { return mDeleted; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public boolean isActive() { return mActive; } @Override public final String toString() { return String.format( "[Project id=%1$s name='%2$s' defaultContextId='%3$s' " + "parallel=%4$s archived=%5$s tracksId='%6$s' deleted=%7$s active=%8$s]", mLocalId, mName, mDefaultContextId, mParallel, mArchived, mTracksId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Project> { private Builder() { } private Project result; private static Builder create() { Builder builder = new Builder(); builder.result = new Project(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public Id getDefaultContextId() { return result.mDefaultContextId; } public Builder setDefaultContextId(Id value) { assert value != null; result.mDefaultContextId = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public boolean isParallel() { return result.mParallel; } public Builder setParallel(boolean value) { result.mParallel = value; return this; } public boolean isArchived() { return result.mArchived; } public Builder setArchived(boolean value) { result.mArchived = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Project build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Project returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Project project) { setLocalId(project.mLocalId); setName(project.mName); setDefaultContextId(project.mDefaultContextId); setModifiedDate(project.mModifiedDate); setParallel(project.mParallel); setArchived(project.mArchived); setTracksId(project.mTracksId); setDeleted(project.mDeleted); setActive(project.mActive); return this; } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public final class Task implements TracksEntity { private Id mLocalId = Id.NONE; private String mDescription; private String mDetails; private Id mContextId = Id.NONE; private Id mProjectId = Id.NONE; private long mCreatedDate; private long mModifiedDate; private long mStartDate; private long mDueDate; private String mTimezone; private boolean mAllDay; private boolean mHasAlarms; private boolean mActive = true; private boolean mDeleted; private Id mCalendarEventId = Id.NONE; // 0-indexed order within a project. private int mOrder; private boolean mComplete; private Id mTracksId = Id.NONE; private Task() { }; @Override public final Id getLocalId() { return mLocalId; } public final String getDescription() { return mDescription; } public final String getDetails() { return mDetails; } public final Id getContextId() { return mContextId; } public final Id getProjectId() { return mProjectId; } public final long getCreatedDate() { return mCreatedDate; } @Override public final long getModifiedDate() { return mModifiedDate; } public final long getStartDate() { return mStartDate; } public final long getDueDate() { return mDueDate; } public final String getTimezone() { return mTimezone; } public final boolean isAllDay() { return mAllDay; } public final boolean hasAlarms() { return mHasAlarms; } public final Id getCalendarEventId() { return mCalendarEventId; } public final int getOrder() { return mOrder; } public final boolean isComplete() { return mComplete; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mDescription; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public boolean isPending() { long now = System.currentTimeMillis(); return mStartDate > now; } @Override public final boolean isValid() { if (TextUtils.isEmpty(mDescription)) { return false; } return true; } @Override public final String toString() { return String.format( "[Task id=%8$s description='%1$s' detail='%2$s' contextId=%3$s projectId=%4$s " + "order=%5$s complete=%6$s tracksId='%7$s' deleted=%9$s active=%10$s]", mDescription, mDetails, mContextId, mProjectId, mOrder, mComplete, mTracksId, mLocalId, mDeleted, mActive); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Task> { private Builder() { } private Task result; private static Builder create() { Builder builder = new Builder(); builder.result = new Task(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getDescription() { return result.mDescription; } public Builder setDescription(String value) { result.mDescription = value; return this; } public String getDetails() { return result.mDetails; } public Builder setDetails(String value) { result.mDetails = value; return this; } public Id getContextId() { return result.mContextId; } public Builder setContextId(Id value) { assert value != null; result.mContextId = value; return this; } public Id getProjectId() { return result.mProjectId; } public Builder setProjectId(Id value) { assert value != null; result.mProjectId = value; return this; } public long getCreatedDate() { return result.mCreatedDate; } public Builder setCreatedDate(long value) { result.mCreatedDate = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public long getStartDate() { return result.mStartDate; } public Builder setStartDate(long value) { result.mStartDate = value; return this; } public long getDueDate() { return result.mDueDate; } public Builder setDueDate(long value) { result.mDueDate = value; return this; } public String getTimezone() { return result.mTimezone; } public Builder setTimezone(String value) { result.mTimezone = value; return this; } public boolean isAllDay() { return result.mAllDay; } public Builder setAllDay(boolean value) { result.mAllDay = value; return this; } public boolean hasAlarms() { return result.mHasAlarms; } public Builder setHasAlarm(boolean value) { result.mHasAlarms = value; return this; } public Id getCalendarEventId() { return result.mCalendarEventId; } public Builder setCalendarEventId(Id value) { assert value != null; result.mCalendarEventId = value; return this; } public int getOrder() { return result.mOrder; } public Builder setOrder(int value) { result.mOrder = value; return this; } public boolean isComplete() { return result.mComplete; } public Builder setComplete(boolean value) { result.mComplete = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public boolean isActive() { return result.mActive; } @Override public Builder setActive(boolean value) { result.mActive = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Task build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Task returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Task task) { setLocalId(task.mLocalId); setDescription(task.mDescription); setDetails(task.mDetails); setContextId(task.mContextId); setProjectId(task.mProjectId); setCreatedDate(task.mCreatedDate); setModifiedDate(task.mModifiedDate); setStartDate(task.mStartDate); setDueDate(task.mDueDate); setTimezone(task.mTimezone); setAllDay(task.mAllDay); setDeleted(task.mDeleted); setHasAlarm(task.mHasAlarms); setCalendarEventId(task.mCalendarEventId); setOrder(task.mOrder); setComplete(task.mComplete); setTracksId(task.mTracksId); setDeleted(task.mDeleted); setActive(task.mActive); return this; } } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model; import org.dodgybits.shuffle.android.synchronisation.tracks.model.TracksEntity; import android.text.TextUtils; public class Context implements TracksEntity { private Id mLocalId = Id.NONE; private String mName; private int mColourIndex; private String mIconName; private long mModifiedDate; private boolean mDeleted; private boolean mActive = true; private Id mTracksId = Id.NONE; private Context() { }; public final Id getLocalId() { return mLocalId; } public final String getName() { return mName; } public final int getColourIndex() { return mColourIndex; } public final String getIconName() { return mIconName; } public final long getModifiedDate() { return mModifiedDate; } public final Id getTracksId() { return mTracksId; } public final String getLocalName() { return mName; } @Override public boolean isDeleted() { return mDeleted; } @Override public boolean isActive() { return mActive; } public final boolean isValid() { if (TextUtils.isEmpty(mName)) { return false; } return true; } @Override public final String toString() { return String.format( "[Context id=%1$s name='%2$s' colourIndex='%3$s' " + "iconName=%4$s tracksId='%5$s' active=%6$s deleted=%7$s]", mLocalId, mName, mColourIndex, mIconName, mTracksId, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder implements EntityBuilder<Context> { private Builder() { } private Context result; private static Builder create() { Builder builder = new Builder(); builder.result = new Context(); return builder; } public Id getLocalId() { return result.mLocalId; } public Builder setLocalId(Id value) { assert value != null; result.mLocalId = value; return this; } public String getName() { return result.mName; } public Builder setName(String value) { result.mName = value; return this; } public int getColourIndex() { return result.mColourIndex; } public Builder setColourIndex(int value) { result.mColourIndex = value; return this; } public String getIconName() { return result.mIconName; } public Builder setIconName(String value) { result.mIconName = value; return this; } public long getModifiedDate() { return result.mModifiedDate; } public Builder setModifiedDate(long value) { result.mModifiedDate = value; return this; } public Id getTracksId() { return result.mTracksId; } public Builder setTracksId(Id value) { assert value != null; result.mTracksId = value; return this; } public boolean isActive() { return result.mActive; } public Builder setActive(boolean value) { result.mActive = value; return this; } public boolean isDeleted() { return result.mDeleted; } @Override public Builder setDeleted(boolean value) { result.mDeleted = value; return this; } public final boolean isInitialized() { return result.isValid(); } public Context build() { if (result == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } Context returnMe = result; result = null; return returnMe; } public Builder mergeFrom(Context context) { setLocalId(context.mLocalId); setName(context.mName); setColourIndex(context.mColourIndex); setIconName(context.mIconName); setModifiedDate(context.mModifiedDate); setTracksId(context.mTracksId); setDeleted(context.mDeleted); setActive(context.mActive); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.COLOUR; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.ICON; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ContextEncoder extends AbstractEntityEncoder implements EntityEncoder<Context> { @Override public void save(Bundle icicle, Context context) { putId(icicle, _ID, context.getLocalId()); putId(icicle, TRACKS_ID, context.getTracksId()); icicle.putLong(MODIFIED_DATE, context.getModifiedDate()); putString(icicle, NAME, context.getName()); icicle.putInt(COLOUR, context.getColourIndex()); putString(icicle, ICON, context.getIconName()); } @Override public Context restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Context.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setColourIndex(icicle.getInt(COLOUR)); builder.setIconName(getString(icicle, ICON)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.ARCHIVED; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.DEFAULT_CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.NAME; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.PARALLEL; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class ProjectEncoder extends AbstractEntityEncoder implements EntityEncoder<Project> { @Override public void save(Bundle icicle, Project project) { putId(icicle, _ID, project.getLocalId()); putId(icicle, TRACKS_ID, project.getTracksId()); icicle.putLong(MODIFIED_DATE, project.getModifiedDate()); putString(icicle, NAME, project.getName()); putId(icicle, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); icicle.putBoolean(ARCHIVED, project.isArchived()); icicle.putBoolean(PARALLEL, project.isParallel()); } @Override public Project restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Project.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setName(getString(icicle, NAME)); builder.setDefaultContextId(getId(icicle, DEFAULT_CONTEXT_ID)); builder.setArchived(icicle.getBoolean(ARCHIVED)); builder.setParallel(icicle.getBoolean(PARALLEL)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import static android.provider.BaseColumns._ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.ALL_DAY; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CAL_EVENT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.COMPLETE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CONTEXT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.CREATED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DESCRIPTION; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DETAILS; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DISPLAY_ORDER; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.DUE_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.HAS_ALARM; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.MODIFIED_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.PROJECT_ID; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.START_DATE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TIMEZONE; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.TRACKS_ID; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import android.os.Bundle; import com.google.inject.Singleton; @Singleton public class TaskEncoder extends AbstractEntityEncoder implements EntityEncoder<Task> { @Override public void save(Bundle icicle, Task task) { putId(icicle, _ID, task.getLocalId()); putId(icicle, TRACKS_ID, task.getTracksId()); icicle.putLong(MODIFIED_DATE, task.getModifiedDate()); putString(icicle, DESCRIPTION, task.getDescription()); putString(icicle, DETAILS, task.getDetails()); putId(icicle, CONTEXT_ID, task.getContextId()); putId(icicle, PROJECT_ID, task.getProjectId()); icicle.putLong(CREATED_DATE, task.getCreatedDate()); icicle.putLong(START_DATE, task.getStartDate()); icicle.putLong(DUE_DATE, task.getDueDate()); putString(icicle, TIMEZONE, task.getTimezone()); putId(icicle, CAL_EVENT_ID, task.getCalendarEventId()); icicle.putBoolean(ALL_DAY, task.isAllDay()); icicle.putBoolean(HAS_ALARM, task.hasAlarms()); icicle.putInt(DISPLAY_ORDER, task.getOrder()); icicle.putBoolean(COMPLETE, task.isComplete()); } @Override public Task restore(Bundle icicle) { if (icicle == null) return null; Builder builder = Task.newBuilder(); builder.setLocalId(getId(icicle, _ID)); builder.setModifiedDate(icicle.getLong(MODIFIED_DATE, 0L)); builder.setTracksId(getId(icicle, TRACKS_ID)); builder.setDescription(getString(icicle, DESCRIPTION)); builder.setDetails(getString(icicle, DETAILS)); builder.setContextId(getId(icicle, CONTEXT_ID)); builder.setProjectId(getId(icicle, PROJECT_ID)); builder.setCreatedDate(icicle.getLong(CREATED_DATE, 0L)); builder.setStartDate(icicle.getLong(START_DATE, 0L)); builder.setDueDate(icicle.getLong(DUE_DATE, 0L)); builder.setTimezone(getString(icicle, TIMEZONE)); builder.setCalendarEventId(getId(icicle, CAL_EVENT_ID)); builder.setAllDay(icicle.getBoolean(ALL_DAY)); builder.setHasAlarm(icicle.getBoolean(HAS_ALARM)); builder.setOrder(icicle.getInt(DISPLAY_ORDER)); builder.setComplete(icicle.getBoolean(COMPLETE)); return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import android.os.Bundle; public interface EntityEncoder<Entity> { void save(Bundle icicle, Entity e); Entity restore(Bundle icicle); }
Java
package org.dodgybits.shuffle.android.core.model.encoding; import org.dodgybits.shuffle.android.core.model.Id; import android.os.Bundle; public abstract class AbstractEntityEncoder { protected static Id getId(Bundle icicle, String key) { Id result = Id.NONE; if (icicle.containsKey(key)) { result = Id.create(icicle.getLong(key)); } return result; } protected static void putId(Bundle icicle, String key, Id value) { if (value.isInitialised()) { icicle.putLong(key, value.getId()); } } protected static String getString(Bundle icicle, String key) { String result = null; if (icicle.containsKey(key)) { result = icicle.getString(key); } return result; } protected static void putString(Bundle icicle, String key, String value) { if (value != null) { icicle.putString(key, value); } } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.dto.ShuffleProtos.Context.Builder; public class ContextProtocolTranslator implements EntityProtocolTranslator<Context , org.dodgybits.shuffle.dto.ShuffleProtos.Context>{ public org.dodgybits.shuffle.dto.ShuffleProtos.Context toMessage(Context context) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Context.newBuilder(); builder .setId(context.getLocalId().getId()) .setName((context.getName())) .setModified(ProtocolUtil.toDate(context.getModifiedDate())) .setColourIndex(context.getColourIndex()) .setActive(context.isActive()) .setDeleted(context.isDeleted()); final Id tracksId = context.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } final String iconName = context.getIconName(); if (iconName != null) { builder.setIcon(iconName); } return builder.build(); } public Context fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Context dto) { Context.Builder builder = Context.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setColourIndex(dto.getColourIndex()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } if (dto.hasIcon()) { builder.setIconName(dto.getIcon()); } return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import com.google.protobuf.MessageLite; public interface EntityProtocolTranslator<E,M extends MessageLite> { E fromMessage(M message); M toMessage(E entity); }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.dto.ShuffleProtos.Project.Builder; public class ProjectProtocolTranslator implements EntityProtocolTranslator<Project, org.dodgybits.shuffle.dto.ShuffleProtos.Project> { private EntityDirectory<Context> mContextDirectory; public ProjectProtocolTranslator(EntityDirectory<Context> contextDirectory) { mContextDirectory = contextDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Project toMessage(Project project) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Project.newBuilder(); builder .setId(project.getLocalId().getId()) .setName((project.getName())) .setModified(ProtocolUtil.toDate(project.getModifiedDate())) .setParallel(project.isParallel()) .setActive(project.isActive()) .setDeleted(project.isDeleted()); final Id defaultContextId = project.getDefaultContextId(); if (defaultContextId.isInitialised()) { builder.setDefaultContextId(defaultContextId.getId()); } final Id tracksId = project.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Project fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Project dto) { Project.Builder builder = Project.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setName(dto.getName()) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setParallel(dto.getParallel()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasDefaultContextId()) { Id defaultContextId = Id.create(dto.getDefaultContextId()); Context context = mContextDirectory.findById(defaultContextId); builder.setDefaultContextId(context.getLocalId()); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.dto.ShuffleProtos.Date; public final class ProtocolUtil { private ProtocolUtil() { // deny } public static Date toDate(long millis) { return Date.newBuilder() .setMillis(millis) .build(); } public static long fromDate(Date date) { long millis = 0L; if (date != null) { millis = date.getMillis(); } return millis; } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.model.Id; public class HashEntityDirectory<Entity> implements EntityDirectory<Entity> { private Map<String,Entity> mItemsByName; private Map<Id, Entity> mItemsById; public HashEntityDirectory() { mItemsByName = new HashMap<String,Entity>(); mItemsById = new HashMap<Id,Entity>(); } public void addItem(Id id, String name, Entity item) { mItemsById.put(id, item); mItemsByName.put(name, item); } @Override public Entity findById(Id id) { return mItemsById.get(id); } @Override public Entity findByName(String name) { return mItemsByName.get(name); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.dto.ShuffleProtos.Task.Builder; public class TaskProtocolTranslator implements EntityProtocolTranslator<Task, org.dodgybits.shuffle.dto.ShuffleProtos.Task> { private final EntityDirectory<Context> mContextDirectory; private final EntityDirectory<Project> mProjectDirectory; public TaskProtocolTranslator( EntityDirectory<Context> contextDirectory, EntityDirectory<Project> projectDirectory) { mContextDirectory = contextDirectory; mProjectDirectory = projectDirectory; } public org.dodgybits.shuffle.dto.ShuffleProtos.Task toMessage(Task task) { Builder builder = org.dodgybits.shuffle.dto.ShuffleProtos.Task.newBuilder(); builder .setId(task.getLocalId().getId()) .setDescription(task.getDescription()) .setCreated(ProtocolUtil.toDate(task.getCreatedDate())) .setModified(ProtocolUtil.toDate(task.getModifiedDate())) .setStartDate(ProtocolUtil.toDate(task.getStartDate())) .setDueDate(ProtocolUtil.toDate(task.getDueDate())) .setAllDay(task.isAllDay()) .setOrder(task.getOrder()) .setComplete(task.isComplete()) .setActive(task.isActive()) .setDeleted(task.isDeleted()); final String details = task.getDetails(); if (details != null) { builder.setDetails(details); } final Id contextId = task.getContextId(); if (contextId.isInitialised()) { builder.setContextId(contextId.getId()); } final Id projectId = task.getProjectId(); if (projectId.isInitialised()) { builder.setProjectId(projectId.getId()); } final String timezone = task.getTimezone(); if (timezone != null) { builder.setTimezone(timezone); } final Id calEventId = task.getCalendarEventId(); if (calEventId.isInitialised()) { builder.setCalEventId(calEventId.getId()); } final Id tracksId = task.getTracksId(); if (tracksId.isInitialised()) { builder.setTracksId(tracksId.getId()); } return builder.build(); } public Task fromMessage( org.dodgybits.shuffle.dto.ShuffleProtos.Task dto) { Task.Builder builder = Task.newBuilder(); builder .setLocalId(Id.create(dto.getId())) .setDescription(dto.getDescription()) .setDetails(dto.getDetails()) .setCreatedDate(ProtocolUtil.fromDate(dto.getCreated())) .setModifiedDate(ProtocolUtil.fromDate(dto.getModified())) .setStartDate(ProtocolUtil.fromDate(dto.getStartDate())) .setDueDate(ProtocolUtil.fromDate(dto.getDueDate())) .setTimezone(dto.getTimezone()) .setAllDay(dto.getAllDay()) .setHasAlarm(false) .setOrder(dto.getOrder()) .setComplete(dto.getComplete()); if (dto.hasActive()) { builder.setActive(dto.getActive()); } else { builder.setActive(true); } if (dto.hasDeleted()) { builder.setDeleted(dto.getDeleted()); } else { builder.setDeleted(false); } if (dto.hasContextId()) { Id contextId = Id.create(dto.getContextId()); Context context = mContextDirectory.findById(contextId); builder.setContextId(context.getLocalId()); } if (dto.hasProjectId()) { Id projectId = Id.create(dto.getProjectId()); Project project = mProjectDirectory.findById(projectId); builder.setProjectId(project.getLocalId()); } if (dto.hasCalEventId()) { builder.setCalendarEventId(Id.create(dto.getCalEventId())); } if (dto.hasTracksId()) { builder.setTracksId(Id.create(dto.getTracksId())); } return builder.build(); } }
Java
package org.dodgybits.shuffle.android.core.model.protocol; import org.dodgybits.shuffle.android.core.model.Id; /** * A lookup service for entities. Useful when matching up entities from different * sources that may have conflicting ids (e.g. backup or remote synching). */ public interface EntityDirectory<Entity> { public Entity findById(Id id); public Entity findByName(String name); }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.model.persistence; import java.util.Calendar; import java.util.TimeZone; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ResourcesProvider; import com.google.inject.Inject; import android.content.ContentResolver; import android.content.ContentUris; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.text.format.DateUtils; import android.util.Log; public class InitialDataGenerator { private static final String cTag = "InitialDataGenerator"; private static final int AT_HOME_INDEX = 0; private static final int AT_WORK_INDEX = 1; private static final int AT_COMPUTER_INDEX = 2; private static final int ERRANDS_INDEX = 3; private static final int COMMUNICATION_INDEX = 4; private static final int READ_INDEX = 5; private Context[] mPresetContexts = null; private EntityPersister<Context> mContextPersister; private EntityPersister<Project> mProjectPersister; private EntityPersister<Task> mTaskPersister; private ContentResolver mContentResolver; private Resources mResources; @Inject public InitialDataGenerator(EntityPersister<Context> contextPersister, EntityPersister<Project> projectPersister, EntityPersister<Task> taskPersister, ContentResolverProvider provider, ResourcesProvider resourcesProvider ) { mContentResolver = provider.get(); mResources = resourcesProvider.get(); mContextPersister = contextPersister; mProjectPersister = projectPersister; mTaskPersister = taskPersister; initPresetContexts(); } public Context getSampleContext() { return mPresetContexts[ERRANDS_INDEX]; } /** * Delete any existing projects, contexts and tasks and create the standard * contexts. * * @param handler the android message handler */ public void cleanSlate(Handler handler) { initPresetContexts(); int deletedRows = mContentResolver.delete( TaskProvider.Tasks.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " tasks."); deletedRows = mContentResolver.delete( ProjectProvider.Projects.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " projects."); deletedRows = mContentResolver.delete( ContextProvider.Contexts.CONTENT_URI, null, null); Log.d(cTag, "Deleted " + deletedRows + " contexts."); for (int i = 0; i < mPresetContexts.length; i++) { mPresetContexts[i] = insertContext(mPresetContexts[i]); } if (handler != null) handler.sendEmptyMessage(0); } /** * Clean out the current data and populate the database with a set of sample * data. * @param handler the message handler */ public void createSampleData(Handler handler) { cleanSlate(null); Calendar cal = Calendar.getInstance(); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); long now = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, -1); long yesterday = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 3); long twoDays = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, 5); long oneWeek = cal.getTimeInMillis(); cal.add(Calendar.WEEK_OF_YEAR, 1); long twoWeeks = cal.getTimeInMillis(); Project sellBike = createProject("Sell old Powerbook", Id.NONE); sellBike = insertProject(sellBike); insertTask( createTask("Backup data", null, AT_COMPUTER_INDEX, sellBike, now, now + DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Reformat HD", "Install Leopard and updates", AT_COMPUTER_INDEX, sellBike, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Determine good price", "Take a look on ebay for similar systems", AT_COMPUTER_INDEX, sellBike, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Put up ad", AT_COMPUTER_INDEX, sellBike, twoWeeks)); Project cleanGarage = createProject("Clean out garage", Id.NONE); cleanGarage = insertProject(cleanGarage); insertTask( createTask("Sort out contents", "Split into keepers and junk", AT_HOME_INDEX, cleanGarage, yesterday, yesterday)); insertTask( createTask("Advertise garage sale", "Local paper(s) and on craigslist", AT_COMPUTER_INDEX, cleanGarage, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Contact local charities", "See what they want or maybe just put in charity bins", COMMUNICATION_INDEX, cleanGarage, now, now)); insertTask( createTask("Take rest to tip", "Hire trailer?", ERRANDS_INDEX, cleanGarage, now, now)); Project skiTrip = createProject("Organise ski trip", Id.NONE); skiTrip = insertProject(skiTrip); insertTask( createTask("Send email to determine best week", null, COMMUNICATION_INDEX, skiTrip, now, now + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Look up package deals", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book chalet", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book flights", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Book hire car", AT_COMPUTER_INDEX, skiTrip, 0L)); insertTask( createTask("Get board waxed", ERRANDS_INDEX, skiTrip, 0L)); Project discussI8n = createProject("Discuss internationalization", mPresetContexts[AT_WORK_INDEX].getLocalId()); discussI8n = insertProject(discussI8n); insertTask( createTask("Read up on options", null, AT_COMPUTER_INDEX, discussI8n, twoDays, twoDays + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Kickoff meeting", null, COMMUNICATION_INDEX, discussI8n, oneWeek, oneWeek + 2 * DateUtils.HOUR_IN_MILLIS)); insertTask( createTask("Produce report", null, AT_WORK_INDEX, discussI8n, twoWeeks, twoWeeks + 2 * DateUtils.HOUR_IN_MILLIS)); // a few stand alone tasks insertTask( createTask("Organise music collection", AT_COMPUTER_INDEX, null, 0L)); insertTask( createTask("Make copy of door keys", ERRANDS_INDEX, null, yesterday)); insertTask( createTask("Read Falling Man", READ_INDEX, null, 0L)); insertTask( createTask("Buy Tufte books", ERRANDS_INDEX, null, oneWeek)); if (handler != null) handler.sendEmptyMessage(0); } private void initPresetContexts() { if (mPresetContexts == null) { mPresetContexts = new Context[] { createContext(mResources.getText(R.string.context_athome).toString(), 5, "go_home"), // 0 createContext(mResources.getText(R.string.context_atwork).toString(), 19, "system_file_manager"), // 1 createContext(mResources.getText(R.string.context_online).toString(), 1, "applications_internet"), // 2 createContext(mResources.getText(R.string.context_errands).toString(), 14, "applications_development"), // 3 createContext(mResources.getText(R.string.context_contact).toString(), 22, "system_users"), // 4 createContext(mResources.getText(R.string.context_read).toString(), 16, "format_justify_fill") // 5 }; } } private Context createContext(String name, int colourIndex, String iconName) { Context.Builder builder = Context.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setColourIndex(colourIndex) .setIconName(iconName); return builder.build(); } private Task createTask(String description, int contextIndex, Project project, long start) { return createTask(description, null, contextIndex, project, start); } private Task createTask(String description, String details, int contextIndex, Project project, long start) { return createTask(description, details, contextIndex, project, start, start); } private int ORDER = 1; private Task createTask(String description, String details, int contextIndex, Project project, long start, long due) { Id contextId = contextIndex > -1 ? mPresetContexts[contextIndex].getLocalId() : Id.NONE; long created = System.currentTimeMillis(); String timezone = TimeZone.getDefault().getID(); Task.Builder builder = Task.newBuilder(); builder .setDescription(description) .setDetails(details) .setContextId(contextId) .setProjectId(project == null ? Id.NONE : project.getLocalId()) .setCreatedDate(created) .setModifiedDate(created) .setStartDate(start) .setDueDate(due) .setTimezone(timezone) .setActive(true) .setDeleted(false) .setOrder(ORDER++); return builder.build(); } private Project createProject(String name, Id defaultContextId) { Project.Builder builder = Project.newBuilder(); builder .setName(name) .setActive(true) .setDeleted(false) .setDefaultContextId(defaultContextId) .setModifiedDate(System.currentTimeMillis()); return builder.build(); } private Context insertContext( org.dodgybits.shuffle.android.core.model.Context context) { Uri uri = mContextPersister.insert(context); long id = ContentUris.parseId(uri); Log.d(cTag, "Created context id=" + id + " uri=" + uri); Context.Builder builder = Context.newBuilder(); builder.mergeFrom(context); builder.setLocalId(Id.create(id)); context = builder.build(); return context; } private Project insertProject( Project project) { Uri uri = mProjectPersister.insert(project); long id = ContentUris.parseId(uri); Log.d(cTag, "Created project id=" + id + " uri=" + uri); Project.Builder builder = Project.newBuilder(); builder.mergeFrom(project); builder.setLocalId(Id.create(id)); project = builder.build(); return project; } private Task insertTask( Task task) { Uri uri = mTaskPersister.insert(task); long id = ContentUris.parseId(uri); Log.d(cTag, "Created task id=" + id); Task.Builder builder = Task.newBuilder(); builder.mergeFrom(task); builder.setLocalId(Id.create(id)); task = builder.build(); return task; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCountParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryCreateEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryDeleteEntityEvent; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryEntityTypeParam; import static org.dodgybits.shuffle.android.core.util.Constants.cFlurryUpdateEntityEvent; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; public abstract class AbstractEntityPersister<E extends Entity> implements EntityPersister<E> { protected Analytics mAnalytics; protected ContentResolver mResolver; protected Map<String, String> mFlurryParams; public AbstractEntityPersister(ContentResolver resolver, Analytics analytics) { mResolver = resolver; mAnalytics = analytics; Map<String, String> params = new HashMap<String,String>(); params.put(cFlurryEntityTypeParam, getEntityName()); mFlurryParams = Collections.unmodifiableMap(params); } @Override public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { Cursor cursor = mResolver.query( getContentUri(), getFullProjection(), BaseColumns._ID + " = ?", new String[] {localId.toString()}, null); if (cursor.moveToFirst()) { entity = read(cursor); } cursor.close(); } return entity; } @Override public Uri insert(E e) { validate(e); Uri uri = mResolver.insert(getContentUri(), null); update(uri, e); mAnalytics.onEvent(cFlurryCreateEntityEvent, mFlurryParams); return uri; } @Override public void bulkInsert(Collection<E> entities) { int numEntities = entities.size(); if (numEntities > 0) { ContentValues[] valuesArray = new ContentValues[numEntities]; int i = 0; for(E entity : entities) { validate(entity); ContentValues values = new ContentValues(); writeContentValues(values, entity); valuesArray[i++] = values; } int rowsCreated = mResolver.bulkInsert(getContentUri(), valuesArray); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsCreated)); mAnalytics.onEvent(cFlurryCreateEntityEvent, params); } } @Override public void update(E e) { validate(e); Uri uri = getUri(e); update(uri, e); mAnalytics.onEvent(cFlurryUpdateEntityEvent, mFlurryParams); } @Override public boolean updateDeletedFlag(Id id, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return (mResolver.update(getUri(id), values, null, null) == 1); } @Override public int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted) { ContentValues values = new ContentValues(); writeBoolean(values, ShuffleTable.DELETED, isDeleted); values.put(ShuffleTable.MODIFIED_DATE, System.currentTimeMillis()); return mResolver.update(getContentUri(), values, selection, selectionArgs); } @Override public int emptyTrash() { int rowsDeleted = mResolver.delete(getContentUri(), "deleted = 1", null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return rowsDeleted; } @Override public boolean deletePermanently(Id id) { Uri uri = getUri(id); boolean success = (mResolver.delete(uri, null, null) == 1); if (success) { mAnalytics.onEvent(cFlurryDeleteEntityEvent, mFlurryParams); } return success; } abstract public Uri getContentUri(); abstract protected void writeContentValues(ContentValues values, E e); abstract protected String getEntityName(); private void validate(E e) { if (e == null || !e.isValid()) { throw new IllegalArgumentException("Cannot persist uninitialised entity " + e); } } protected Uri getUri(E e) { return getUri(e.getLocalId()); } protected Uri getUri(Id localId) { return ContentUris.appendId( getContentUri().buildUpon(), localId.getId()).build(); } private void update(Uri uri, E e) { ContentValues values = new ContentValues(); writeContentValues(values, e); mResolver.update(uri, values, null, null); } protected static Id readId(Cursor cursor, int index) { Id result = Id.NONE; if (!cursor.isNull(index)) { result = Id.create(cursor.getLong(index)); } return result; } protected static String readString(Cursor cursor, int index) { return (cursor.isNull(index) ? null : cursor.getString(index)); } protected static long readLong(Cursor cursor, int index) { return readLong(cursor, index, 0L); } protected static long readLong(Cursor cursor, int index, long defaultValue) { long result = defaultValue; if (!cursor.isNull(index)) { result = cursor.getLong(index); } return result; } protected static Boolean readBoolean(Cursor cursor, int index) { return (cursor.getInt(index) == 1); } protected static void writeId(ContentValues values, String key, Id id) { if (id.isInitialised()) { values.put(key, id.getId()); } else { values.putNull(key); } } protected static void writeBoolean(ContentValues values, String key, boolean value) { values.put(key, value ? 1 : 0); } protected static void writeString(ContentValues values, String key, String value) { if (value == null) { values.putNull(key); } else { values.put(key, value); } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Project; import org.dodgybits.shuffle.android.core.model.Project.Builder; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.ProjectProvider.Projects.*; @ContextScoped public class ProjectPersister extends AbstractEntityPersister<Project> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int DEFAULT_CONTEXT_INDEX = 2; private static final int TRACKS_ID_INDEX = 3; private static final int MODIFIED_INDEX = 4; private static final int PARALLEL_INDEX = 5; private static final int ARCHIVED_INDEX = 6; private static final int DELETED_INDEX = 7; private static final int ACTIVE_INDEX = 8; @Inject public ProjectPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Project read(Cursor cursor) { Builder builder = Project.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setDefaultContextId(readId(cursor, DEFAULT_CONTEXT_INDEX)) .setParallel(readBoolean(cursor, PARALLEL_INDEX)) .setArchived(readBoolean(cursor, ARCHIVED_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Project project) { // never write id since it's auto generated values.put(MODIFIED_DATE, project.getModifiedDate()); writeId(values, TRACKS_ID, project.getTracksId()); writeString(values, NAME, project.getName()); writeId(values, DEFAULT_CONTEXT_ID, project.getDefaultContextId()); writeBoolean(values, PARALLEL, project.isParallel()); writeBoolean(values, ARCHIVED, project.isArchived()); writeBoolean(values, DELETED, project.isDeleted()); writeBoolean(values, ACTIVE, project.isActive()); } @Override protected String getEntityName() { return "project"; } @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override public String[] getFullProjection() { return ProjectProvider.Projects.FULL_PROJECTION; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import android.provider.BaseColumns; import android.text.TextUtils; import android.text.format.Time; import android.util.Log; import android.util.SparseIntArray; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.model.Task; import org.dodgybits.shuffle.android.core.model.Task.Builder; import org.dodgybits.shuffle.android.core.model.persistence.selector.Flag; import org.dodgybits.shuffle.android.core.model.persistence.selector.TaskSelector; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import roboguice.util.Ln; import java.util.*; import static org.dodgybits.shuffle.android.core.util.Constants.*; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.ACTIVE; import static org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider.ShuffleTable.DELETED; import static org.dodgybits.shuffle.android.persistence.provider.TaskProvider.Tasks.*; @ContextScoped public class TaskPersister extends AbstractEntityPersister<Task> { private static final String cTag = "TaskPersister"; private static final int ID_INDEX = 0; private static final int DESCRIPTION_INDEX = ID_INDEX + 1; private static final int DETAILS_INDEX = DESCRIPTION_INDEX + 1; private static final int PROJECT_INDEX = DETAILS_INDEX + 1; private static final int CONTEXT_INDEX = PROJECT_INDEX + 1; private static final int CREATED_INDEX = CONTEXT_INDEX + 1; private static final int MODIFIED_INDEX = CREATED_INDEX + 1; private static final int START_INDEX = MODIFIED_INDEX + 1; private static final int DUE_INDEX = START_INDEX + 1; private static final int TIMEZONE_INDEX = DUE_INDEX + 1; private static final int CAL_EVENT_INDEX = TIMEZONE_INDEX + 1; private static final int DISPLAY_ORDER_INDEX = CAL_EVENT_INDEX + 1; private static final int COMPLETE_INDEX = DISPLAY_ORDER_INDEX + 1; private static final int ALL_DAY_INDEX = COMPLETE_INDEX + 1; private static final int HAS_ALARM_INDEX = ALL_DAY_INDEX + 1; private static final int TASK_TRACK_INDEX = HAS_ALARM_INDEX + 1; private static final int DELETED_INDEX = TASK_TRACK_INDEX +1; private static final int ACTIVE_INDEX = DELETED_INDEX +1; @Inject public TaskPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Task read(Cursor cursor) { Builder builder = Task.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setDescription(readString(cursor, DESCRIPTION_INDEX)) .setDetails(readString(cursor, DETAILS_INDEX)) .setProjectId(readId(cursor, PROJECT_INDEX)) .setContextId(readId(cursor, CONTEXT_INDEX)) .setCreatedDate(readLong(cursor, CREATED_INDEX)) .setModifiedDate(readLong(cursor, MODIFIED_INDEX)) .setStartDate(readLong(cursor, START_INDEX)) .setDueDate(readLong(cursor, DUE_INDEX)) .setTimezone(readString(cursor, TIMEZONE_INDEX)) .setCalendarEventId(readId(cursor, CAL_EVENT_INDEX)) .setOrder(cursor.getInt(DISPLAY_ORDER_INDEX)) .setComplete(readBoolean(cursor, COMPLETE_INDEX)) .setAllDay(readBoolean(cursor, ALL_DAY_INDEX)) .setHasAlarm(readBoolean(cursor, HAS_ALARM_INDEX)) .setTracksId(readId(cursor, TASK_TRACK_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Task task) { // never write id since it's auto generated writeString(values, DESCRIPTION, task.getDescription()); writeString(values, DETAILS, task.getDetails()); writeId(values, PROJECT_ID, task.getProjectId()); writeId(values, CONTEXT_ID, task.getContextId()); values.put(CREATED_DATE, task.getCreatedDate()); values.put(MODIFIED_DATE, task.getModifiedDate()); values.put(START_DATE, task.getStartDate()); values.put(DUE_DATE, task.getDueDate()); writeBoolean(values, DELETED, task.isDeleted()); writeBoolean(values, ACTIVE, task.isActive()); String timezone = task.getTimezone(); if (TextUtils.isEmpty(timezone)) { if (task.isAllDay()) { timezone = Time.TIMEZONE_UTC; } else { timezone = TimeZone.getDefault().getID(); } } values.put(TIMEZONE, timezone); writeId(values, CAL_EVENT_ID, task.getCalendarEventId()); values.put(DISPLAY_ORDER, task.getOrder()); writeBoolean(values, COMPLETE, task.isComplete()); writeBoolean(values, ALL_DAY, task.isAllDay()); writeBoolean(values, HAS_ALARM, task.hasAlarms()); writeId(values, TRACKS_ID, task.getTracksId()); } @Override protected String getEntityName() { return "task"; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } @Override public String[] getFullProjection() { return TaskProvider.Tasks.FULL_PROJECTION; } @Override public int emptyTrash() { // find tasks that are deleted or who's context or project is deleted TaskSelector selector = TaskSelector.newBuilder().setDeleted(Flag.yes).build(); Cursor cursor = mResolver.query(getContentUri(), new String[] {BaseColumns._ID}, selector.getSelection(null), selector.getSelectionArgs(), selector.getSortOrder()); List<String> ids = new ArrayList<String>(); while (cursor.moveToNext()) { ids.add(cursor.getString(ID_INDEX)); } cursor.close(); int rowsDeleted = 0; if (ids.size() > 0) { Ln.i("About to delete tasks %s", ids); String queryString = "_id IN (" + StringUtils.join(ids, ",") + ")"; rowsDeleted = mResolver.delete(getContentUri(), queryString, null); Map<String, String> params = new HashMap<String, String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(rowsDeleted)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); } return rowsDeleted; } public int deleteCompletedTasks() { int deletedRows = updateDeletedFlag(TaskProvider.Tasks.COMPLETE + " = 1", null, true); Log.d(cTag, "Deleting " + deletedRows + " completed tasks."); Map<String, String> params = new HashMap<String,String>(mFlurryParams); params.put(cFlurryCountParam, String.valueOf(deletedRows)); mAnalytics.onEvent(cFlurryDeleteEntityEvent, params); return deletedRows; } public void updateCompleteFlag(Id id, boolean isComplete) { ContentValues values = new ContentValues(); writeBoolean(values, COMPLETE, isComplete); values.put(MODIFIED_DATE, System.currentTimeMillis()); mResolver.update(getUri(id), values, null, null); if (isComplete) { mAnalytics.onEvent(cFlurryCompleteTaskEvent); } } /** * Calculate where this task should appear on the list for the given project. * If no project is defined, order is meaningless, so return -1. * * New tasks go on the end of the list if no due date is defined. * If due date is defined, add either to the start, or after the task * closest to the end of the list with an earlier due date. * * For existing tasks, check if the project changed, and if so * treat like a new task, otherwise leave the order as is. * * @param originalTask the task before any changes or null if this is a new task * @param newProjectId the project selected for this task * @param dueMillis due date of this task (or 0L if not defined) * @return 0-indexed order of task when displayed in the project view */ public int calculateTaskOrder(Task originalTask, Id newProjectId, long dueMillis) { if (!newProjectId.isInitialised()) return -1; int order; if (originalTask == null || !originalTask.getProjectId().equals(newProjectId)) { // get current highest order value Cursor cursor = mResolver.query( TaskProvider.Tasks.CONTENT_URI, new String[] {BaseColumns._ID, TaskProvider.Tasks.DISPLAY_ORDER, TaskProvider.Tasks.DUE_DATE}, TaskProvider.Tasks.PROJECT_ID + " = ?", new String[] {String.valueOf(newProjectId.getId())}, TaskProvider.Tasks.DISPLAY_ORDER + " desc"); if (cursor.moveToFirst()) { if (dueMillis > 0L) { Ln.d("Due date defined - finding best place to insert in project task list"); Map<Long,Integer> updateValues = new HashMap<Long,Integer>(); do { long previousId = cursor.getLong(0); int previousOrder = cursor.getInt(1); long previousDueDate = cursor.getLong(2); if (previousDueDate > 0L && previousDueDate < dueMillis) { order = previousOrder + 1; Ln.d("Placing after task %d with earlier due date", previousId); break; } updateValues.put(previousId, previousOrder + 1); order = previousOrder; } while (cursor.moveToNext()); moveFollowingTasks(updateValues); } else { // no due date so put at end of list int highestOrder = cursor.getInt(1); order = highestOrder + 1; } } else { // no tasks in the project yet. order = 0; } cursor.close(); } else { order = originalTask.getOrder(); } return order; } private void moveFollowingTasks(Map<Long,Integer> updateValues) { Set<Long> ids = updateValues.keySet(); ContentValues values = new ContentValues(); for (long id : ids) { values.clear(); values.put(DISPLAY_ORDER, updateValues.get(id)); Uri uri = ContentUris.withAppendedId(TaskProvider.Tasks.CONTENT_URI, id); mResolver.update(uri, values, null, null); } } /** * Swap the display order of two tasks at the given cursor positions. * The cursor is committed and re-queried after the update. */ public void swapTaskPositions(Cursor cursor, int pos1, int pos2) { cursor.moveToPosition(pos1); Id id1 = readId(cursor, ID_INDEX); int positionValue1 = cursor.getInt(DISPLAY_ORDER_INDEX); cursor.moveToPosition(pos2); Id id2 = readId(cursor, ID_INDEX); int positionValue2 = cursor.getInt(DISPLAY_ORDER_INDEX); Uri uri = ContentUris.withAppendedId(getContentUri(), id1.getId()); ContentValues values = new ContentValues(); values.put(DISPLAY_ORDER, positionValue2); mResolver.update(uri, values, null, null); uri = ContentUris.withAppendedId(getContentUri(), id2.getId()); values.clear(); values.put(DISPLAY_ORDER, positionValue1); mResolver.update(uri, values, null, null); mAnalytics.onEvent(cFlurryReorderTasksEvent); } private static final int TASK_COUNT_INDEX = 1; public SparseIntArray readCountArray(Cursor cursor) { SparseIntArray countMap = new SparseIntArray(); while (cursor.moveToNext()) { Integer id = cursor.getInt(ID_INDEX); Integer count = cursor.getInt(TASK_COUNT_INDEX); countMap.put(id, count); } return countMap; } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.ItemCache; import org.dodgybits.shuffle.android.core.util.ItemCache.ValueBuilder; import roboguice.inject.ContextScoped; import android.util.Log; import com.google.inject.Inject; @ContextScoped public class DefaultEntityCache<E extends Entity> implements EntityCache<E> { private static final String cTag = "DefaultEntityCache"; private EntityPersister<E> mPersister; private Builder mBuilder; private ItemCache<Id, E> mCache; @Inject public DefaultEntityCache(EntityPersister<E> persister) { Log.d(cTag, "Created entity cache with " + persister); mPersister = persister; mBuilder = new Builder(); mCache = new ItemCache<Id, E>(mBuilder); } public E findById(Id localId) { E entity = null; if (localId.isInitialised()) { entity = mCache.get(localId); } return entity; } private class Builder implements ValueBuilder<Id, E> { @Override public E build(Id key) { return mPersister.findById(key); } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import java.util.Collection; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; import android.database.Cursor; import android.net.Uri; public interface EntityPersister<E extends Entity> { Uri getContentUri(); String[] getFullProjection(); E findById(Id localId); E read(Cursor cursor); Uri insert(E e); void bulkInsert(Collection<E> entities); void update(E e); /** * Set deleted flag entity with the given id to isDeleted. * * @param id entity id * @param isDeleted flag to set deleted flag to * @return whether the operation succeeded */ boolean updateDeletedFlag(Id id, boolean isDeleted); /** * Set deleted flag for entities that match the criteria to isDeleted. * * @param selection where clause * @param selectionArgs parameter values from where clause * @param isDeleted flag to set deleted flag to * @return number of entities updates */ int updateDeletedFlag(String selection, String[] selectionArgs, boolean isDeleted); /** * Permanently delete all items that currently flagged as deleted. * * @return number of entities removed */ int emptyTrash(); /** * Permanently delete entity with the given id. * * @return whether the operation succeeded */ boolean deletePermanently(Id id); }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import org.dodgybits.shuffle.android.core.model.Entity; import org.dodgybits.shuffle.android.core.model.Id; public interface EntityCache<E extends Entity> { E findById(Id localId); }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.no; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.yes; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import android.net.Uri; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.persistence.provider.TaskProvider; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import org.dodgybits.shuffle.android.preference.model.Preferences; import android.text.format.DateUtils; import android.util.Log; public class TaskSelector extends AbstractEntitySelector { private static final String cTag = "TaskSelector"; private static final String[] cUndefinedArgs = new String[] {}; private PredefinedQuery mPredefined; private List<Id> mProjects; private List<Id> mContexts; private Flag mComplete = ignored; private Flag mPending = ignored; private String mSelection = null; private String[] mSelectionArgs = cUndefinedArgs; private TaskSelector() { } public final PredefinedQuery getPredefinedQuery() { return mPredefined; } public final List<Id> getProjects() { return mProjects; } public final List<Id> getContexts() { return mContexts; } public final Flag getComplete() { return mComplete; } public final Flag getPending() { return mPending; } @Override public Uri getContentUri() { return TaskProvider.Tasks.CONTENT_URI; } public final String getSelection(android.content.Context context) { if (mSelection == null) { List<String> expressions = getSelectionExpressions(context); mSelection = StringUtils.join(expressions, " AND "); Log.d(cTag, mSelection); } return mSelection; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); if (mPredefined != null) { expressions.add(predefinedSelection(context)); } addActiveExpression(expressions); addDeletedExpression(expressions); addPendingExpression(expressions); addListExpression(expressions, TaskProvider.Tasks.PROJECT_ID, mProjects); addListExpression(expressions, TaskProvider.Tasks.CONTEXT_ID, mContexts); addFlagExpression(expressions, TaskProvider.Tasks.COMPLETE, mComplete); return expressions; } private void addActiveExpression(List<String> expressions) { if (mActive == yes) { // A task is active if it is active and both project and context are active. String expression = "(task.active = 1 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.active = 1)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.active = 1)) " + ")"; expressions.add(expression); } else if (mActive == no) { // task is inactive if it is inactive or project in active or context is inactive String expression = "(task.active = 0 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.active = 0)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.active = 0)) " + ")"; expressions.add(expression); } } private void addDeletedExpression(List<String> expressions) { if (mDeleted == yes) { // task is deleted if it is deleted or project is deleted or context is deleted String expression = "(task.deleted = 1 " + "OR (projectId is not null AND projectId IN (select p._id from project p where p.deleted = 1)) " + "OR (contextId is not null AND contextId IN (select c._id from context c where c.deleted = 1)) " + ")"; expressions.add(expression); } else if (mDeleted == no) { // task is not deleted if it is not deleted and project is not deleted and context is not deleted String expression = "(task.deleted = 0 " + "AND (projectId is null OR projectId IN (select p._id from project p where p.deleted = 0)) " + "AND (contextId is null OR contextId IN (select c._id from context c where c.deleted = 0)) " + ")"; expressions.add(expression); } } private void addPendingExpression(List<String> expressions) { long now = System.currentTimeMillis(); if (mPending == yes) { String expression = "(start > " + now + ")"; expressions.add(expression); } else if (mPending == no) { String expression = "(start <= " + now + ")"; expressions.add(expression); } } private String predefinedSelection(android.content.Context context) { String result; long now = System.currentTimeMillis(); switch (mPredefined) { case nextTasks: result = "((complete = 0) AND " + " (start < " + now + ") AND " + " ((projectId is null) OR " + " (projectId IN (select p._id from project p where p.parallel = 1)) OR " + " (task._id = (select t2._id FROM task t2 WHERE " + " t2.projectId = task.projectId AND t2.complete = 0 AND " + " t2.deleted = 0 " + " ORDER BY displayOrder ASC limit 1))" + "))"; break; case inbox: long lastCleanMS = Preferences.getLastInboxClean(context); result = "((projectId is null AND contextId is null) OR (created > " + lastCleanMS + "))"; break; case tickler: // by default show all results (completely customizable) result = "(1 == 1)"; break; case dueToday: case dueNextWeek: case dueNextMonth: long startMS = 0L; long endOfToday = getEndDate(); long endOfTomorrow = endOfToday + DateUtils.DAY_IN_MILLIS; result = "(due > " + startMS + ")" + " AND ( (due < " + endOfToday + ") OR" + "( allDay = 1 AND due < " + endOfTomorrow + " ))"; break; default: throw new RuntimeException("Unknown predefined selection " + mPredefined); } return result; } private long getEndDate() { long endMS = 0L; Calendar cal = Calendar.getInstance(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); switch (mPredefined) { case dueToday: cal.add(Calendar.DAY_OF_YEAR, 1); endMS = cal.getTimeInMillis(); break; case dueNextWeek: cal.add(Calendar.DAY_OF_YEAR, 7); endMS = cal.getTimeInMillis(); break; case dueNextMonth: cal.add(Calendar.MONTH, 1); endMS = cal.getTimeInMillis(); break; } if (Log.isLoggable(cTag, Log.INFO)) { Log.i(cTag, "Due date ends " + endMS); } return endMS; } public final String[] getSelectionArgs() { if (mSelectionArgs == cUndefinedArgs) { List<String> args = new ArrayList<String>(); addIdListArgs(args, mProjects); addIdListArgs(args, mContexts); Log.d(cTag,args.toString()); mSelectionArgs = args.size() > 0 ? args.toArray(new String[0]): null; } return mSelectionArgs; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[TaskSelector predefined=%1$s projects=%2$s contexts='%3$s' " + "complete=%4$s sortOrder=%5$s active=%6$s deleted=%7$s pending=%8$s]", mPredefined, mProjects, mContexts, mComplete, mSortOrder, mActive, mDeleted, mPending); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<TaskSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new TaskSelector(); return builder; } public PredefinedQuery getPredefined() { return mResult.mPredefined; } public Builder setPredefined(PredefinedQuery value) { mResult.mPredefined = value; return this; } public List<Id> getProjects() { return mResult.mProjects; } public Builder setProjects(List<Id> value) { mResult.mProjects = value; return this; } public List<Id> getContexts() { return mResult.mContexts; } public Builder setContexts(List<Id> value) { mResult.mContexts = value; return this; } public Flag getComplete() { return mResult.mComplete; } public Builder setComplete(Flag value) { mResult.mComplete = value; return this; } public Flag getPending() { return mResult.mPending; } public Builder setPending(Flag value) { mResult.mPending = value; return this; } public Builder mergeFrom(TaskSelector query) { super.mergeFrom(query); setPredefined(query.mPredefined); setProjects(query.mProjects); setContexts(query.mContexts); setComplete(query.mComplete); setPending(query.mPending); return this; } public Builder applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { super.applyListPreferences(context, settings); setComplete(settings.getCompleted(context)); setPending(settings.getPending(context)); return this; } } public enum PredefinedQuery { nextTasks, dueToday, dueNextWeek, dueNextMonth, inbox, tickler } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.util.Log; import org.dodgybits.shuffle.android.core.model.Id; import org.dodgybits.shuffle.android.core.util.StringUtils; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; import java.util.ArrayList; import java.util.List; import static org.dodgybits.shuffle.android.core.model.persistence.selector.Flag.ignored; public abstract class AbstractEntitySelector implements EntitySelector { private static final String cTag = "AbstractEntitySelector"; protected Flag mActive = ignored; protected Flag mDeleted = ignored; protected String mSortOrder; @Override public Flag getActive() { return mActive; } @Override public Flag getDeleted() { return mDeleted; } @Override public final String getSortOrder() { return mSortOrder; } @Override public String getSelection(android.content.Context context) { List<String> expressions = getSelectionExpressions(context); String selection = StringUtils.join(expressions, " AND "); Log.d(cTag, selection); return selection; } protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = new ArrayList<String>(); return expressions; } protected void addFlagExpression(List<String> expressions, String field, Flag flag) { if (flag != Flag.ignored) { String expression = field + "=" + (flag == Flag.yes ? "1" : "0"); expressions.add(expression); } } protected void addListExpression(List<String> expressions, String field, List<Id> ids) { if (ids != null) { expressions.add(idListSelection(ids, field)); } } private String idListSelection(List<Id> ids, String idName) { StringBuilder result = new StringBuilder(); if (ids.size() > 0) { result.append(idName) .append(" in (") .append(StringUtils.repeat(ids.size(), "?", ",")) .append(')'); } else { result.append(idName) .append(" is null"); } return result.toString(); } protected void addIdListArgs(List<String> args, List<Id> ids) { if (ids != null && ids.size() > 0) { for(Id id : ids) { args.add(String.valueOf(id.getId())); } } } public abstract static class AbstractBuilder<E extends AbstractEntitySelector> implements EntitySelector.Builder<E> { protected E mResult; @Override public Flag getDeleted() { return mResult.getDeleted(); } @Override public Flag getActive() { return mResult.getActive(); } @Override public String getSortOrder() { return mResult.getSortOrder(); } @Override public AbstractBuilder<E> setSortOrder(String value) { mResult.mSortOrder = value; return this; } @Override public AbstractBuilder<E> setActive(Flag value) { mResult.mActive = value; return this; } @Override public AbstractBuilder<E> setDeleted(Flag value) { mResult.mDeleted = value; return this; } @Override public E build() { if (mResult == null) { throw new IllegalStateException( "build() has already been called on this Builder."); } E returnMe = mResult; mResult = null; Log.d(cTag,returnMe.toString()); return returnMe; } @Override public AbstractBuilder<E> mergeFrom(E selector) { setActive(selector.mActive); setDeleted(selector.mDeleted); setSortOrder(selector.mSortOrder); return this; } @Override public AbstractBuilder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings) { setActive(settings.getActive(context)); setDeleted(settings.getDeleted(context)); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import java.util.List; public class ContextSelector extends AbstractEntitySelector { private static final String cTag = "ContextSelector"; private ContextSelector() { } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public final String toString() { return String.format( "[ContextSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ContextSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ContextSelector(); return builder; } public Builder mergeFrom(ContextSelector query) { super.mergeFrom(query); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.net.Uri; import org.dodgybits.shuffle.android.persistence.provider.AbstractCollectionProvider; import org.dodgybits.shuffle.android.persistence.provider.ProjectProvider; import java.util.List; public class ProjectSelector extends AbstractEntitySelector { private static final String cTag = "ProjectSelector"; private ProjectSelector() { } @Override public Uri getContentUri() { return ProjectProvider.Projects.CONTENT_URI; } @Override protected List<String> getSelectionExpressions(android.content.Context context) { List<String> expressions = super.getSelectionExpressions(context); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.ACTIVE, mActive); addFlagExpression(expressions, AbstractCollectionProvider.ShuffleTable.DELETED, mDeleted); return expressions; } public final String[] getSelectionArgs() { return null; } @Override public Builder builderFrom() { return newBuilder().mergeFrom(this); } @Override public final String toString() { return String.format( "[ProjectSelector sortOrder=%1$s active=%2$s deleted=%3$s]", mSortOrder, mActive, mDeleted); } public static Builder newBuilder() { return Builder.create(); } public static class Builder extends AbstractBuilder<ProjectSelector> { private Builder() { } private static Builder create() { Builder builder = new Builder(); builder.mResult = new ProjectSelector(); return builder; } public Builder mergeFrom(ProjectSelector query) { super.mergeFrom(query); return this; } } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; import android.content.Context; import android.net.Uri; import org.dodgybits.shuffle.android.preference.model.ListPreferenceSettings; public interface EntitySelector<E extends EntitySelector> { Uri getContentUri(); Flag getActive(); Flag getDeleted(); String getSelection(Context context); String[] getSelectionArgs(); String getSortOrder(); Builder<E> builderFrom(); public interface Builder<E extends EntitySelector> { Flag getActive(); Builder<E> setActive(Flag value); Flag getDeleted(); Builder<E> setDeleted(Flag value); String getSortOrder(); Builder<E> setSortOrder(String value); E build(); Builder<E> mergeFrom(E selector); Builder<E> applyListPreferences(android.content.Context context, ListPreferenceSettings settings); } }
Java
package org.dodgybits.shuffle.android.core.model.persistence.selector; public enum Flag { yes, no, ignored }
Java
package org.dodgybits.shuffle.android.core.model.persistence; import android.content.ContentValues; import android.database.Cursor; import android.net.Uri; import com.google.inject.Inject; import org.dodgybits.shuffle.android.core.activity.flurry.Analytics; import org.dodgybits.shuffle.android.core.model.Context; import org.dodgybits.shuffle.android.core.model.Context.Builder; import org.dodgybits.shuffle.android.persistence.provider.ContextProvider; import roboguice.inject.ContentResolverProvider; import roboguice.inject.ContextScoped; import static org.dodgybits.shuffle.android.persistence.provider.ContextProvider.Contexts.*; @ContextScoped public class ContextPersister extends AbstractEntityPersister<Context> { private static final int ID_INDEX = 0; private static final int NAME_INDEX = 1; private static final int COLOUR_INDEX = 2; private static final int ICON_INDEX = 3; private static final int TRACKS_ID_INDEX = 4; private static final int MODIFIED_INDEX = 5; private static final int DELETED_INDEX = 6; private static final int ACTIVE_INDEX = 7; @Inject public ContextPersister(ContentResolverProvider provider, Analytics analytics) { super(provider.get(), analytics); } @Override public Context read(Cursor cursor) { Builder builder = Context.newBuilder(); builder .setLocalId(readId(cursor, ID_INDEX)) .setModifiedDate(cursor.getLong(MODIFIED_INDEX)) .setTracksId(readId(cursor, TRACKS_ID_INDEX)) .setName(readString(cursor, NAME_INDEX)) .setColourIndex(cursor.getInt(COLOUR_INDEX)) .setIconName(readString(cursor, ICON_INDEX)) .setDeleted(readBoolean(cursor, DELETED_INDEX)) .setActive(readBoolean(cursor, ACTIVE_INDEX)); return builder.build(); } @Override protected void writeContentValues(ContentValues values, Context context) { // never write id since it's auto generated values.put(MODIFIED_DATE, context.getModifiedDate()); writeId(values, TRACKS_ID, context.getTracksId()); writeString(values, NAME, context.getName()); values.put(COLOUR, context.getColourIndex()); writeString(values, ICON, context.getIconName()); writeBoolean(values, DELETED, context.isDeleted()); writeBoolean(values, ACTIVE, context.isActive()); } @Override protected String getEntityName() { return "context"; } @Override public Uri getContentUri() { return ContextProvider.Contexts.CONTENT_URI; } @Override public String[] getFullProjection() { return ContextProvider.Contexts.FULL_PROJECTION; } }
Java
package org.dodgybits.shuffle.android.core.model; public interface Entity { /** * @return primary key for entity in local sqlite DB. 0L indicates an unsaved entity. */ Id getLocalId(); /** * @return ms since epoch entity was last modified. */ long getModifiedDate(); boolean isActive(); boolean isDeleted(); boolean isValid(); String getLocalName(); }
Java
package org.dodgybits.shuffle.android.core.model; public interface EntityBuilder<E> { EntityBuilder<E> mergeFrom(E e); EntityBuilder<E> setLocalId(Id id); EntityBuilder<E> setModifiedDate(long ms); EntityBuilder<E> setTracksId(Id id); EntityBuilder<E> setActive(boolean value); EntityBuilder<E> setDeleted(boolean value); E build(); }
Java
package org.dodgybits.shuffle.android.core.view; import android.content.res.Resources; import android.text.TextUtils; public class ContextIcon { private static final String cPackage = "org.dodgybits.android.shuffle"; private static final String cType = "drawable"; public static final ContextIcon NONE = new ContextIcon(null, 0, 0); public final String iconName; public final int largeIconId; public final int smallIconId; private ContextIcon(String iconName, int largeIconId, int smallIconId) { this.iconName = iconName; this.largeIconId = largeIconId; this.smallIconId = smallIconId; } public static ContextIcon createIcon(String iconName, Resources res) { if (TextUtils.isEmpty(iconName)) return NONE; int largeId = res.getIdentifier(iconName, cType, cPackage); int smallId = res.getIdentifier(iconName + "_small", cType, cPackage); return new ContextIcon(iconName, largeId, smallId); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.util.Log; public class AlertUtils { private static final String cTag = "AlertUtils"; private AlertUtils() { //deny } public static void showDeleteGroupWarning(final Context context, final String groupName, final String childName, final int childCount, final OnClickListener buttonListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.delete_warning, groupName.toLowerCase(), childCount, childName.toLowerCase()); CharSequence deleteButtonText = context.getString(R.string.menu_delete); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); OnCancelListener cancelListener = new OnCancelListener() { public void onCancel(DialogInterface dialog) { Log.d(cTag, "Cancelled delete. Do nothing."); } }; Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(deleteButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } public static void showCleanUpInboxMessage(final Context context) { CharSequence title = context.getString(R.string.info_title); CharSequence message = context.getString(R.string.clean_inbox_message); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_information) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showWarning(final Context context, final String message) { CharSequence title = context.getString(R.string.warning_title); CharSequence buttonText = context.getString(R.string.ok_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setPositiveButton(buttonText, null); builder.create().show(); } public static void showFileExistsWarning(final Context context, final String filename, final OnClickListener buttonListener, final OnCancelListener cancelListener) { CharSequence title = context.getString(R.string.warning_title); CharSequence message = context.getString(R.string.warning_filename_exists, filename); CharSequence replaceButtonText = context.getString(R.string.replace_button_title); CharSequence cancelButtonText = context.getString(R.string.cancel_button_title); Builder builder = new Builder(context); builder.setTitle(title).setIcon(R.drawable.dialog_warning) .setMessage(message) .setNegativeButton(cancelButtonText, buttonListener) .setPositiveButton(replaceButtonText, buttonListener) .setOnCancelListener(cancelListener); builder.create().show(); } }
Java
package org.dodgybits.shuffle.android.core.view; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class IconArrayAdapter extends ArrayAdapter<CharSequence> { private Integer[] mIconIds; public IconArrayAdapter( Context context, int resource, int textViewResourceId, CharSequence[] objects, Integer[] iconIds) { super(context, resource, textViewResourceId, objects); mIconIds = iconIds; } public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView nameView = (TextView) view.findViewById(R.id.name); // don't use toString in order to preserve colour change nameView.setText(getItem(position)); Integer iconId = null; if (position < mIconIds.length) { iconId = mIconIds[position]; if (iconId != null) { nameView.setCompoundDrawablesWithIntrinsicBounds( getContext().getResources().getDrawable(iconId), null, null, null); } } return view; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.graphics.drawable.GradientDrawable.Orientation; public class DrawableUtils { private DrawableUtils() { //deny } public static GradientDrawable createGradient(int colour, Orientation orientation) { return createGradient(colour, orientation, 1.1f, 0.9f); } public static GradientDrawable createGradient(int colour, Orientation orientation, float startOffset, float endOffset) { int[] colours = new int[2]; float[] hsv1 = new float[3]; float[] hsv2 = new float[3]; Color.colorToHSV(colour, hsv1); Color.colorToHSV(colour, hsv2); hsv1[2] *= startOffset; hsv2[2] *= endOffset; colours[0] = Color.HSVToColor(hsv1); colours[1] = Color.HSVToColor(hsv2); return new GradientDrawable(orientation, colours); } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.view; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import org.dodgybits.android.shuffle.R; import org.dodgybits.shuffle.android.core.activity.HelpActivity; import org.dodgybits.shuffle.android.list.activity.ContextsActivity; import org.dodgybits.shuffle.android.list.activity.ProjectsActivity; import org.dodgybits.shuffle.android.list.activity.State; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableContextsActivity; import org.dodgybits.shuffle.android.list.activity.expandable.ExpandableProjectsActivity; import org.dodgybits.shuffle.android.list.activity.task.*; import org.dodgybits.shuffle.android.preference.activity.PreferencesActivity; import org.dodgybits.shuffle.android.preference.model.Preferences; import org.dodgybits.shuffle.android.synchronisation.tracks.activity.SynchronizeActivity; public class MenuUtils { private static final String cTag = "MenuUtils"; private MenuUtils() { // deny } // Identifiers for our menu items. public static final int SAVE_ID = Menu.FIRST; public static final int SAVE_AND_ADD_ID = Menu.FIRST + 1; public static final int REVERT_ID = Menu.FIRST + 2; public static final int DISCARD_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int INSERT_ID = Menu.FIRST + 5; public static final int INSERT_CHILD_ID = Menu.FIRST + 6; public static final int INSERT_GROUP_ID = Menu.FIRST + 7; public static final int INBOX_ID = Menu.FIRST + 10; public static final int CALENDAR_ID = Menu.FIRST + 11; public static final int TOP_TASKS_ID = Menu.FIRST + 12; public static final int PROJECT_ID = Menu.FIRST + 13; public static final int CONTEXT_ID = Menu.FIRST + 14; public static final int TICKLER_ID = Menu.FIRST + 15; public static final int PREFERENCE_ID = Menu.FIRST + 20; public static final int HELP_ID = Menu.FIRST + 21; public static final int SYNC_ID = Menu.FIRST + 22; public static final int SEARCH_ID = Menu.FIRST + 23; public static final int CLEAN_INBOX_ID = Menu.FIRST + 50; public static final int PERMANENTLY_DELETE_ID = Menu.FIRST + 51; // Menu item for activity specific items public static final int PUT_BACK_ID = Menu.FIRST + 100; public static final int COMPLETE_ID = Menu.FIRST + 101; public static final int MOVE_UP_ID = Menu.FIRST + 102; public static final int MOVE_DOWN_ID = Menu.FIRST + 103; // Editor menus private static final int SAVE_ORDER = 1; private static final int SAVE_AND_ADD_ORDER = 2; private static final int REVERT_ORDER = 3; private static final int DISCARD_ORDER = 3; // Context menus private static final int EDIT_ORDER = 1; private static final int PUT_BACK_ORDER = 3; private static final int COMPLETE_ORDER = 4; private static final int MOVE_UP_ORDER = 5; private static final int MOVE_DOWN_ORDER = 6; private static final int DELETE_ORDER = 10; // List menus private static final int INSERT_ORDER = 1; private static final int INSERT_CHILD_ORDER = 1; private static final int INSERT_GROUP_ORDER = 2; private static final int CLEAN_INBOX_ORDER = 101; private static final int PERMANENTLY_DELETE_ORDER = 102; // General menus private static final int PERSPECTIVE_ORDER = 201; private static final int PREFERENCE_ORDER = 202; private static final int SYNCH_ORDER = 203; private static final int SEARCH_ORDER = 204; private static final int HELP_ORDER = 205; public static void addInsertMenuItems(Menu menu, String itemName, boolean isTaskList, Context context) { String menuName = context.getResources().getString(R.string.menu_insert, itemName); menu.add(Menu.NONE, INSERT_ID, INSERT_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add) .setAlphabeticShortcut(isTaskList ? 'c' : 'a'); } public static void addExpandableInsertMenuItems(Menu menu, String groupName, String childName, Context context) { String menuName; menuName = context.getResources().getString(R.string.menu_insert, childName); menu.add(Menu.NONE, INSERT_CHILD_ID, INSERT_CHILD_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('c'); menuName = context.getResources().getString(R.string.menu_insert, groupName); menu.add(Menu.NONE, INSERT_GROUP_ID, INSERT_GROUP_ORDER, menuName) .setIcon(android.R.drawable.ic_menu_add).setAlphabeticShortcut('a'); } public static void addViewMenuItems(Menu menu, int currentViewMenuId) { SubMenu viewMenu = menu.addSubMenu(Menu.NONE, Menu.NONE, PERSPECTIVE_ORDER, R.string.menu_view) .setIcon(R.drawable.preferences_system_windows); viewMenu.add(Menu.NONE, INBOX_ID, 0, R.string.title_inbox) .setChecked(INBOX_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CALENDAR_ID, 1, R.string.title_due_tasks) .setChecked(CALENDAR_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TOP_TASKS_ID, 2, R.string.title_next_tasks) .setChecked(TOP_TASKS_ID == currentViewMenuId); viewMenu.add(Menu.NONE, PROJECT_ID, 3, R.string.title_project) .setChecked(PROJECT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, CONTEXT_ID, 4, R.string.title_context) .setChecked(CONTEXT_ID == currentViewMenuId); viewMenu.add(Menu.NONE, TICKLER_ID, 5, R.string.title_tickler) .setChecked(TICKLER_ID == currentViewMenuId); } public static void addEditorMenuItems(Menu menu, int state) { menu.add(Menu.NONE, SAVE_ID, SAVE_ORDER, R.string.menu_save) .setIcon(android.R.drawable.ic_menu_save).setAlphabeticShortcut('s'); menu.add(Menu.NONE, SAVE_AND_ADD_ID, SAVE_AND_ADD_ORDER, R.string.menu_save_and_add) .setIcon(android.R.drawable.ic_menu_save); // Build the menus that are shown when editing. if (state == State.STATE_EDIT) { menu.add(Menu.NONE, REVERT_ID, REVERT_ORDER, R.string.menu_revert) .setIcon(android.R.drawable.ic_menu_revert).setAlphabeticShortcut('r'); menu.add(Menu.NONE, DELETE_ID, DELETE_ORDER, R.string.menu_delete) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); // Build the menus that are shown when inserting. } else { menu.add(Menu.NONE, DISCARD_ID, DISCARD_ORDER, R.string.menu_discard) .setIcon(android.R.drawable.ic_menu_close_clear_cancel).setAlphabeticShortcut('d'); } } public static void addPrefsHelpMenuItems(Context context, Menu menu) { menu.add(Menu.NONE, PREFERENCE_ID, PREFERENCE_ORDER, R.string.menu_preferences) .setIcon(android.R.drawable.ic_menu_preferences).setAlphabeticShortcut('p'); menu.add(Menu.NONE, HELP_ID, HELP_ORDER, R.string.menu_help) .setIcon(android.R.drawable.ic_menu_help).setAlphabeticShortcut('h'); } public static void addSyncMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SYNC_ID, SYNCH_ORDER, R.string.menu_sync) .setIcon(android.R.drawable.ic_menu_rotate).setVisible(Preferences.validateTracksSettings(context)); } public static void addSearchMenuItem(Context context, Menu menu) { menu.add(Menu.NONE, SEARCH_ID, SEARCH_ORDER, R.string.menu_search) .setIcon(android.R.drawable.ic_menu_search).setAlphabeticShortcut('s'); } public static void addSelectedAlternativeMenuItems(Menu menu, Uri uri, boolean includeView) { // Build menu... always starts with the EDIT action... int viewIndex = 0; int editIndex = (includeView ? 1 : 0); Intent[] specifics = new Intent[editIndex + 1]; MenuItem[] items = new MenuItem[editIndex + 1]; if (includeView) { specifics[viewIndex] = new Intent(Intent.ACTION_VIEW, uri); } specifics[editIndex] = new Intent(Intent.ACTION_EDIT, uri); // ... is followed by whatever other actions are available... Intent intent = new Intent(null, uri); intent.addCategory(Intent.CATEGORY_ALTERNATIVE); menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, Menu.NONE, EDIT_ORDER, null, specifics, intent, 0, items); // Give a shortcut to the edit action. if (items[editIndex] != null) { items[editIndex].setAlphabeticShortcut('e'); items[editIndex].setIcon(android.R.drawable.ic_menu_edit); } if (includeView && items[viewIndex] != null) { items[viewIndex].setAlphabeticShortcut('v'); items[viewIndex].setIcon(android.R.drawable.ic_menu_view); } } public static void addPutBackMenuItem(Menu menu) { menu.add(Menu.CATEGORY_ALTERNATIVE, PUT_BACK_ID, PUT_BACK_ORDER, R.string.menu_put_back); } public static void addCompleteMenuItem(Menu menu, boolean isComplete) { int labelId = isComplete ? R.string.menu_incomplete : R.string.menu_complete; menu.add(Menu.CATEGORY_ALTERNATIVE, COMPLETE_ID, COMPLETE_ORDER, labelId) .setIcon(R.drawable.btn_check_on).setAlphabeticShortcut('x'); } public static void addDeleteMenuItem(Menu menu, boolean isDeleted) { int labelId = isDeleted ? R.string.menu_undelete : R.string.menu_delete; menu.add(Menu.CATEGORY_ALTERNATIVE, DELETE_ID, DELETE_ORDER, labelId) .setIcon(android.R.drawable.ic_menu_delete).setAlphabeticShortcut('d'); } public static void addCleanInboxMenuItem(Menu menu) { menu.add(Menu.NONE, CLEAN_INBOX_ID, CLEAN_INBOX_ORDER, R.string.clean_inbox_button_title) .setIcon(R.drawable.edit_clear).setAlphabeticShortcut('i'); } public static void addPermanentlyDeleteMenuItem(Menu menu) { menu.add(Menu.NONE, PERMANENTLY_DELETE_ID, PERMANENTLY_DELETE_ORDER, R.string.permanently_delete_button_title) .setIcon(R.drawable.icon_delete); } public static void addMoveMenuItems(Menu menu, boolean enableUp, boolean enableDown) { if (enableUp) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_UP_ID, MOVE_UP_ORDER, R.string.menu_move_up) .setIcon(R.drawable.go_up).setAlphabeticShortcut('k'); } if (enableDown) { menu.add(Menu.CATEGORY_ALTERNATIVE, MOVE_DOWN_ID, MOVE_DOWN_ORDER, R.string.menu_move_down) .setIcon(R.drawable.go_down).setAlphabeticShortcut('j'); } } public static boolean checkCommonItemsSelected(MenuItem item, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(item.getItemId(), activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId) { return checkCommonItemsSelected(menuItemId, activity, currentViewMenuId, true); } public static boolean checkCommonItemsSelected(int menuItemId, Activity activity, int currentViewMenuId, boolean finishCurrentActivity) { switch (menuItemId) { case MenuUtils.INBOX_ID: if (currentViewMenuId != INBOX_ID) { Log.d(cTag, "Switching to inbox"); activity.startActivity(new Intent(activity, InboxActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.CALENDAR_ID: if (currentViewMenuId != CALENDAR_ID) { Log.d(cTag, "Switching to calendar"); activity.startActivity(new Intent(activity, TabbedDueActionsActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.TOP_TASKS_ID: if (currentViewMenuId != TOP_TASKS_ID) { Log.d(cTag, "Switching to top tasks"); activity.startActivity(new Intent(activity, TopTasksActivity.class)); if (finishCurrentActivity) activity.finish(); } return true; case MenuUtils.PROJECT_ID: if (currentViewMenuId != PROJECT_ID) { Log.d(cTag, "Switching to project list"); Class<? extends Activity> activityClass = null; if (Preferences.isProjectViewExpandable(activity)) { activityClass = ExpandableProjectsActivity.class; } else { activityClass = ProjectsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case CONTEXT_ID: if (currentViewMenuId != CONTEXT_ID) { Log.d(cTag, "Switching to context list"); Class<? extends Activity> activityClass = null; if (Preferences.isContextViewExpandable(activity)) { activityClass = ExpandableContextsActivity.class; } else { activityClass = ContextsActivity.class; } activity.startActivity(new Intent(activity, activityClass)); if (finishCurrentActivity) activity.finish(); } return true; case TICKLER_ID: Log.d(cTag, "Switching to tickler list"); activity.startActivity(new Intent(activity, TicklerActivity.class)); return true; case PREFERENCE_ID: Log.d(cTag, "Bringing up preferences"); activity.startActivity(new Intent(activity, PreferencesActivity.class)); return true; case HELP_ID: Log.d(cTag, "Bringing up help"); Intent intent = new Intent(activity, HelpActivity.class); intent.putExtra(HelpActivity.cHelpPage, getHelpScreen(currentViewMenuId)); activity.startActivity(intent); return true; case SYNC_ID: Log.d(cTag, "starting sync"); activity.startActivity(new Intent(activity, SynchronizeActivity.class)); return true; case SEARCH_ID: Log.d(cTag, "starting search"); activity.onSearchRequested(); return true; } return false; } private static int getHelpScreen(int currentViewMenuId) { int result = 0; switch (currentViewMenuId) { case INBOX_ID: result = 1; break; case PROJECT_ID: result = 2; break; case CONTEXT_ID: result = 3; break; case TOP_TASKS_ID: result = 4; break; case CALENDAR_ID: result = 5; break; } return result; } }
Java
/* * Copyright (C) 2009 Android Shuffle Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.dodgybits.shuffle.android.core.util; import org.dodgybits.android.shuffle.R; import android.content.Context; import android.graphics.Color; import android.util.Log; public class TextColours { private static final String cTag = "TextColours"; private static TextColours instance = null; private int[] textColours; private int[] bgColours; public static TextColours getInstance(Context context) { if (instance == null) { instance = new TextColours(context); } return instance; } private TextColours(Context context) { Log.d(cTag, "Fetching colours"); String[] colourStrings = context.getResources().getStringArray(R.array.text_colours); Log.d(cTag, "Fetched colours"); textColours = parseColourString(colourStrings); colourStrings = context.getResources().getStringArray(R.array.background_colours); bgColours = parseColourString(colourStrings); } private int[] parseColourString(String[] colourStrings) { int[] colours = new int[colourStrings.length]; for (int i = 0; i < colourStrings.length; i++) { String colourString = '#' + colourStrings[i].substring(1); Log.d(cTag, "Parsing " + colourString); colours[i] = Color.parseColor(colourString); } return colours; } public int getNumColours() { return textColours.length; } public int getTextColour(int position) { return textColours[position]; } public int getBackgroundColour(int position) { return bgColours[position]; } }
Java
package org.dodgybits.shuffle.android.core.util; import java.util.List; public class StringUtils { public static String repeat(int count, String token) { return repeat(count, token, ""); } public static String repeat(int count, String token, String delim) { StringBuilder builder = new StringBuilder(); for (int i = 1; i <= count; i++) { builder.append(token); if (i < count) { builder.append(delim); } } return builder.toString(); } public static String join(List<String> items, String delim) { StringBuilder result = new StringBuilder(); final int len = items.size(); for(int i = 0; i < len; i++) { result.append(items.get(i)); if (i < len - 1) { result.append(delim); } } return result.toString(); } }
Java