diff --git a/MyTracks/src/com/google/android/apps/mytracks/MarkerEditActivity.java b/MyTracks/src/com/google/android/apps/mytracks/MarkerEditActivity.java index f4ded6ad9..1026c1660 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/MarkerEditActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/MarkerEditActivity.java @@ -114,12 +114,12 @@ public class MarkerEditActivity extends AbstractMyTracksActivity { if (newMarker) { statisticsSection.setVisibility(View.GONE); waypointSection.setVisibility(View.VISIBLE); - int nextMarkerNumber = trackId == -1L ? -1 - : MyTracksProviderUtils.Factory.get(this).getNextMarkerNumber(trackId, false); - if (nextMarkerNumber == -1) { - nextMarkerNumber = 0; + int nextWaypointNumber = trackId == -1L ? -1 + : MyTracksProviderUtils.Factory.get(this).getNextWaypointNumber(trackId, false); + if (nextWaypointNumber == -1) { + nextWaypointNumber = 0; } - waypointName.setText(getString(R.string.marker_name_format, nextMarkerNumber)); + waypointName.setText(getString(R.string.marker_name_format, nextWaypointNumber)); waypointName.selectAll(); waypointMarkerType.setText(""); waypointDescription.setText(""); diff --git a/MyTracks/src/com/google/android/apps/mytracks/TrackEditActivity.java b/MyTracks/src/com/google/android/apps/mytracks/TrackEditActivity.java index 2826df1f0..1dc6fafcb 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/TrackEditActivity.java +++ b/MyTracks/src/com/google/android/apps/mytracks/TrackEditActivity.java @@ -125,7 +125,7 @@ public class TrackEditActivity extends AbstractMyTracksActivity { Button cancel = (Button) findViewById(R.id.track_edit_cancel); if (getIntent().getBooleanExtra(EXTRA_NEW_TRACK, false)) { String trackName = TrackNameUtils.getTrackName( - this, -1L, -1L, myTracksProviderUtils.getLastLocation()); + this, -1L, -1L, myTracksProviderUtils.getLastValidTrackPoint(trackId)); if (trackName != null) { name.setText(trackName); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/content/SearchEngine.java b/MyTracks/src/com/google/android/apps/mytracks/content/SearchEngine.java index 46fd69172..b1ec32f49 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/content/SearchEngine.java +++ b/MyTracks/src/com/google/android/apps/mytracks/content/SearchEngine.java @@ -186,7 +186,7 @@ public class SearchEngine { queryLikeSelection, queryLikeSelection }; - Cursor tracksCursor = providerUtils.getTracksCursor( + Cursor tracksCursor = providerUtils.getTrackCursor( TRACK_SELECTION_QUERY, trackSelectionArgs, TRACK_SELECTION_ORDER); if (tracksCursor != null) { try { @@ -213,21 +213,21 @@ public class SearchEngine { queryLikeSelection2, queryLikeSelection2, queryLikeSelection2 }; - Cursor waypointsCursor = providerUtils.getWaypointsCursor( + Cursor waypointCursor = providerUtils.getWaypointCursor( WAYPOINT_SELECTION_QUERY, waypointSelectionArgs, WAYPOINT_SELECTION_ORDER, MAX_SCORED_WAYPOINTS); - if (waypointsCursor != null) { + if (waypointCursor != null) { try { - waypoints.ensureCapacity(waypointsCursor.getCount()); + waypoints.ensureCapacity(waypointCursor.getCount()); - while (waypointsCursor.moveToNext()) { - Waypoint waypoint = providerUtils.createWaypoint(waypointsCursor); + while (waypointCursor.moveToNext()) { + Waypoint waypoint = providerUtils.createWaypoint(waypointCursor); if (LocationUtils.isValidLocation(waypoint.getLocation())) { waypoints.add(waypoint); } } } finally { - waypointsCursor.close(); + waypointCursor.close(); } } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java b/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java index 5bf6be832..6e68a31d5 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java +++ b/MyTracks/src/com/google/android/apps/mytracks/content/TrackDataHub.java @@ -563,7 +563,7 @@ public class TrackDataHub implements DataSourceListener { Cursor cursor = null; try { - cursor = myTracksProviderUtils.getWaypointsCursor( + cursor = myTracksProviderUtils.getWaypointCursor( selectedTrackId, 0L, MAX_DISPLAYED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { do { @@ -614,9 +614,9 @@ public class TrackDataHub implements DataSourceListener { long localLastSeenLocationId = updateSamplingState ? lastSeenLocationId : -1L; long maxPointId = updateSamplingState ? -1L : lastSeenLocationId; - long lastLocationId = myTracksProviderUtils.getLastTrackLocationId(selectedTrackId); + long lastTrackPointId = myTracksProviderUtils.getLastTrackPointId(selectedTrackId); int samplingFrequency = -1; - LocationIterator iterator = myTracksProviderUtils.getLocationIterator( + LocationIterator iterator = myTracksProviderUtils.getTrackPointLocationIterator( selectedTrackId, localLastSeenLocationId + 1, false, locationFactory); boolean includeNextPoint = false; while (iterator.hasNext()) { @@ -633,7 +633,7 @@ public class TrackDataHub implements DataSourceListener { } if (samplingFrequency == -1) { - long numTotalPoints = Math.max(0L, lastLocationId - localFirstSeenLocationId); + long numTotalPoints = Math.max(0L, lastTrackPointId - localFirstSeenLocationId); samplingFrequency = 1 + (int) (numTotalPoints / targetNumPoints); } @@ -646,7 +646,7 @@ public class TrackDataHub implements DataSourceListener { } else { // Also include the last point if the selected track is not recording. if (includeNextPoint || (localNumLoadedPoints % samplingFrequency == 0) - || (locationId == lastLocationId && !isSelectedTrackRecording())) { + || (locationId == lastTrackPointId && !isSelectedTrackRecording())) { includeNextPoint = false; for (TrackDataListener trackDataListener : sampledInListeners) { trackDataListener.onSampledInTrackPoint(location); diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java index b8a00acaa..edc036f32 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/ChartFragment.java @@ -27,7 +27,7 @@ import com.google.android.apps.mytracks.content.TrackDataListener; import com.google.android.apps.mytracks.content.TrackDataType; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.stats.TripStatistics; -import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; +import com.google.android.apps.mytracks.stats.TripStatisticsUpdater; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.UnitConversions; @@ -61,7 +61,7 @@ public class ChartFragment extends Fragment implements TrackDataListener { private TrackDataHub trackDataHub; // Stats gathered from the received data - private TripStatisticsBuilder tripStatisticsBuilder; + private TripStatisticsUpdater tripStatisticsUpdater; private long startTime; private boolean metricUnits = PreferencesUtils.METRIC_UNITS_DEFAULT; @@ -83,7 +83,7 @@ public class ChartFragment extends Fragment implements TrackDataListener { private final Runnable updateChart = new Runnable() { @Override public void run() { - if (trackDataHub == null) { + if (!isResumed() || trackDataHub == null) { return; } @@ -178,111 +178,141 @@ public class ChartFragment extends Fragment implements TrackDataListener { @Override public void onTrackUpdated(Track track) { - if (track == null || track.getTripStatistics() == null) { - startTime = -1L; - return; + if (isResumed()) { + if (track == null || track.getTripStatistics() == null) { + startTime = -1L; + return; + } + startTime = track.getTripStatistics().getStartTime(); } - startTime = track.getTripStatistics().getStartTime(); } @Override public void clearTrackPoints() { - tripStatisticsBuilder = startTime != -1L ? new TripStatisticsBuilder(startTime) : null; - pendingPoints.clear(); - chartView.reset(); - - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - chartView.resetScroll(); - } - }); + if (isResumed()) { + tripStatisticsUpdater = startTime != -1L ? new TripStatisticsUpdater(startTime) : null; + pendingPoints.clear(); + chartView.reset(); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + if (isResumed()) { + chartView.resetScroll(); + } + } + }); + } } @Override public void onSampledInTrackPoint(Location location) { - double[] data = new double[ChartView.NUM_SERIES + 1]; - fillDataPoint(location, data); - pendingPoints.add(data); + if (isResumed()) { + double[] data = new double[ChartView.NUM_SERIES + 1]; + fillDataPoint(location, data); + pendingPoints.add(data); + } } @Override public void onSampledOutTrackPoint(Location location) { - fillDataPoint(location, null); + if (isResumed()) { + fillDataPoint(location, null); + } } @Override public void onSegmentSplit(Location location) { - fillDataPoint(location, null); + if (isResumed()) { + fillDataPoint(location, null); + } } @Override public void onNewTrackPointsDone() { - chartView.addDataPoints(pendingPoints); - pendingPoints.clear(); - getActivity().runOnUiThread(updateChart); + if (isResumed()) { + chartView.addDataPoints(pendingPoints); + pendingPoints.clear(); + getActivity().runOnUiThread(updateChart); + } } @Override public void clearWaypoints() { - chartView.clearWaypoints(); + if (isResumed()) { + chartView.clearWaypoints(); + } } @Override public void onNewWaypoint(Waypoint waypoint) { - if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { + if (isResumed() && waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { chartView.addWaypoint(waypoint); } } @Override public void onNewWaypointsDone() { - getActivity().runOnUiThread(updateChart); + if (isResumed()) { + getActivity().runOnUiThread(updateChart); + } } @Override public boolean onMetricUnitsChanged(boolean metric) { - if (metricUnits == metric) { - return false; - } - metricUnits = metric; - chartView.setMetricUnits(metricUnits); - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - chartView.requestLayout(); + if (isResumed()) { + if (metricUnits == metric) { + return false; } - }); - return true; + metricUnits = metric; + chartView.setMetricUnits(metricUnits); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + if (isResumed()) { + chartView.requestLayout(); + } + } + }); + return true; + } + return false; } @Override public boolean onReportSpeedChanged(boolean speed) { - if (reportSpeed == speed) { - return false; - } - reportSpeed = speed; - chartView.setReportSpeed(reportSpeed); - boolean chartShowSpeed = PreferencesUtils.getBoolean( - getActivity(), R.string.chart_show_speed_key, PreferencesUtils.CHART_SHOW_SPEED_DEFAULT); - setSeriesEnabled(ChartView.SPEED_SERIES, chartShowSpeed && reportSpeed); - setSeriesEnabled(ChartView.PACE_SERIES, chartShowSpeed && !reportSpeed); - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - chartView.requestLayout(); + if (isResumed()) { + if (reportSpeed == speed) { + return false; } - }); - return true; + reportSpeed = speed; + chartView.setReportSpeed(reportSpeed); + boolean chartShowSpeed = PreferencesUtils.getBoolean( + getActivity(), R.string.chart_show_speed_key, PreferencesUtils.CHART_SHOW_SPEED_DEFAULT); + setSeriesEnabled(ChartView.SPEED_SERIES, chartShowSpeed && reportSpeed); + setSeriesEnabled(ChartView.PACE_SERIES, chartShowSpeed && !reportSpeed); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + if (isResumed()) { + chartView.requestLayout(); + } + } + }); + return true; + } + return false; } @Override public boolean onMinRecordingDistanceChanged(int value) { - if (minRecordingDistance == value) { - return false; + if (isResumed()) { + if (minRecordingDistance == value) { + return false; + } + minRecordingDistance = value; + return true; } - minRecordingDistance = value; - return true; + return false; } /** @@ -424,9 +454,9 @@ public class ChartFragment extends Fragment implements TrackDataListener { double cadence = Double.NaN; double power = Double.NaN; - if (tripStatisticsBuilder != null) { - tripStatisticsBuilder.addLocation(location, minRecordingDistance); - TripStatistics tripStatistics = tripStatisticsBuilder.getTripStatistics(); + if (tripStatisticsUpdater != null) { + tripStatisticsUpdater.addLocation(location, minRecordingDistance); + TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics(); if (chartByDistance) { double distance = tripStatistics.getTotalDistance() * UnitConversions.M_TO_KM; if (!metricUnits) { @@ -436,13 +466,13 @@ public class ChartFragment extends Fragment implements TrackDataListener { } else { timeOrDistance = tripStatistics.getTotalTime(); } - - elevation = tripStatisticsBuilder.getSmoothedElevation(); + + elevation = tripStatisticsUpdater.getSmoothedElevation(); if (!metricUnits) { elevation *= UnitConversions.M_TO_FT; } - - speed = tripStatisticsBuilder.getSmoothedSpeed() * UnitConversions.MS_TO_KMH; + + speed = tripStatisticsUpdater.getSmoothedSpeed() * UnitConversions.MS_TO_KMH; if (!metricUnits) { speed *= UnitConversions.KM_TO_MI; } @@ -485,8 +515,8 @@ public class ChartFragment extends Fragment implements TrackDataListener { } @VisibleForTesting - void setTripStatisticsBuilder(long time) { - tripStatisticsBuilder = new TripStatisticsBuilder(time); + void setTripStatisticsUpdater(long time) { + tripStatisticsUpdater = new TripStatisticsUpdater(time); } @VisibleForTesting diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java index 984a463cc..841ba20c9 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/MapFragment.java @@ -275,93 +275,104 @@ public class MapFragment extends Fragment @Override public void onLocationStateChanged(LocationState state) { - final String message; - final boolean isGpsDisabled; - if (!isSelectedTrackRecording()) { - message = null; - isGpsDisabled = false; - } else { - switch (state) { - case DISABLED: - String setting = getString( - GoogleLocationUtils.isAvailable(getActivity()) ? R.string.gps_google_location_settings - : R.string.gps_location_access); - message = getString(R.string.gps_disabled, setting); - isGpsDisabled = true; - break; - case NO_FIX: - message = getString(R.string.gps_wait_for_signal); - isGpsDisabled = false; - break; - case BAD_FIX: - message = getString(R.string.gps_wait_for_better_signal); - isGpsDisabled = false; - break; - case GOOD_FIX: - message = null; - isGpsDisabled = false; - break; - default: - throw new IllegalArgumentException("Unexpected state: " + state); - } - } - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - if (message != null) { - messageTextView.setText(message); - messageTextView.setVisibility(View.VISIBLE); - - if (isGpsDisabled) { - Toast.makeText(getActivity(), R.string.gps_not_found, Toast.LENGTH_LONG).show(); - - // Click to show the location source settings - messageTextView.setOnClickListener(MapFragment.this); - } else { - messageTextView.setOnClickListener(null); - } - } else { - messageTextView.setVisibility(View.GONE); + if (isResumed()) { + final String message; + final boolean isGpsDisabled; + if (!isSelectedTrackRecording()) { + message = null; + isGpsDisabled = false; + } else { + switch (state) { + case DISABLED: + String setting = getString( + GoogleLocationUtils.isAvailable(getActivity()) ? R.string.gps_google_location_settings + : R.string.gps_location_access); + message = getString(R.string.gps_disabled, setting); + isGpsDisabled = true; + break; + case NO_FIX: + message = getString(R.string.gps_wait_for_signal); + isGpsDisabled = false; + break; + case BAD_FIX: + message = getString(R.string.gps_wait_for_better_signal); + isGpsDisabled = false; + break; + case GOOD_FIX: + message = null; + isGpsDisabled = false; + break; + default: + throw new IllegalArgumentException("Unexpected state: " + state); } } - }); + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + if (isResumed()) { + if (message == null) { + messageTextView.setVisibility(View.GONE); + return; + } + messageTextView.setText(message); + messageTextView.setVisibility(View.VISIBLE); + if (isGpsDisabled) { + Toast.makeText(getActivity(), R.string.gps_not_found, Toast.LENGTH_LONG).show(); + + // Click to show the location source settings + messageTextView.setOnClickListener(MapFragment.this); + } else { + messageTextView.setOnClickListener(null); + } + } + } + }); + } } @Override public void onLocationChanged(Location location) { - currentLocation = location; - updateCurrentLocation(); + if (isResumed()) { + currentLocation = location; + updateCurrentLocation(); + } } @Override public void onHeadingChanged(double heading) { - if (mapOverlay.setHeading((float) heading)) { - mapView.postInvalidate(); + if (isResumed()) { + if (mapOverlay.setHeading((float) heading)) { + mapView.postInvalidate(); + } } } @Override public void onSelectedTrackChanged(final Track track) { - getActivity().runOnUiThread(new Runnable() { - @Override - public void run() { - boolean hasTrack = track != null; - mapOverlay.setTrackDrawingEnabled(hasTrack); + if (isResumed()) { + getActivity().runOnUiThread(new Runnable() { + @Override + public void run() { + if (isResumed()) { + boolean hasTrack = track != null; + mapOverlay.setTrackDrawingEnabled(hasTrack); - if (hasTrack) { - synchronized (this) { - /* - * Synchronize to prevent race condition in changing markerTrackId - * and markerId variables. - */ - currentSelectedTrackId = track.getId(); - updateMap(track); + if (hasTrack) { + synchronized (this) { + /* + * Synchronize to prevent race condition in changing + * markerTrackId and markerId variables. + */ + currentSelectedTrackId = track.getId(); + updateMap(track); + } + mapOverlay.setShowEndMarker(!isSelectedTrackRecording()); + } + mapView.invalidate(); } - mapOverlay.setShowEndMarker(!isSelectedTrackRecording()); } - mapView.invalidate(); - } - }); + }); + } } @Override @@ -371,12 +382,16 @@ public class MapFragment extends Fragment @Override public void clearTrackPoints() { - mapOverlay.clearPoints(); + if (isResumed()) { + mapOverlay.clearPoints(); + } } @Override public void onSampledInTrackPoint(Location location) { - mapOverlay.addLocation(location); + if (isResumed()) { + mapOverlay.addLocation(location); + } } @Override @@ -386,22 +401,28 @@ public class MapFragment extends Fragment @Override public void onSegmentSplit(Location location) { - mapOverlay.addSegmentSplit(); + if (isResumed()) { + mapOverlay.addSegmentSplit(); + } } @Override public void onNewTrackPointsDone() { - mapView.postInvalidate(); + if (isResumed()) { + mapView.postInvalidate(); + } } @Override public void clearWaypoints() { - mapOverlay.clearWaypoints(); + if (isResumed()) { + mapOverlay.clearWaypoints(); + } } @Override public void onNewWaypoint(Waypoint waypoint) { - if (waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { + if (isResumed() && waypoint != null && LocationUtils.isValidLocation(waypoint.getLocation())) { // TODO: Optimize locking inside addWaypoint mapOverlay.addWaypoint(waypoint); } @@ -409,7 +430,9 @@ public class MapFragment extends Fragment @Override public void onNewWaypointsDone() { - mapView.postInvalidate(); + if (isResumed()) { + mapView.postInvalidate(); + } } @Override diff --git a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java b/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java index 0e7dcd0c7..e7e3a292d 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java +++ b/MyTracks/src/com/google/android/apps/mytracks/fragments/StatsFragment.java @@ -29,6 +29,7 @@ import com.google.android.maps.mytracks.R; import android.location.Location; import android.os.Bundle; import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; @@ -57,7 +58,8 @@ public class StatsFragment extends Fragment implements TrackDataListener { // A runnable to update the total time field. private final Runnable updateTotalTime = new Runnable() { public void run() { - if (isSelectedTrackRecording() && !isSelectedTrackPaused() && lastTripStatistics != null) { + if (isResumed() && isSelectedTrackRecording() && !isSelectedTrackPaused() + && lastTripStatistics != null) { StatsUtils.setTotalTimeValue(getActivity(), System.currentTimeMillis() - lastTripStatistics.getStopTime() + lastTripStatistics.getTotalTime()); } @@ -71,7 +73,7 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void run() { Log.d(TAG, "UI update thread started"); - while (true) { + while (isResumed() && isSelectedTrackRecording()) { getActivity().runOnUiThread(updateTotalTime); try { Thread.sleep(1000L); @@ -93,7 +95,7 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); - updateUi(); + updateUi(getActivity()); } @Override @@ -114,12 +116,14 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void onLocationStateChanged(LocationState state) { - if (isResumed() && (state == LocationState.DISABLED || state == LocationState.NO_FIX)) { + if (isResumed() && state != LocationState.GOOD_FIX) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { - lastLocation = null; - StatsUtils.setLocationValues(getActivity(), lastLocation, true); + if (isResumed()) { + lastLocation = null; + StatsUtils.setLocationValues(getActivity(), lastLocation, true); + } } }); } @@ -127,12 +131,21 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void onLocationChanged(final Location location) { - if (isResumed() && isSelectedTrackRecording()) { + if (isResumed()) { getActivity().runOnUiThread(new Runnable() { @Override public void run() { - lastLocation = location; - StatsUtils.setLocationValues(getActivity(), lastLocation, true); + if (isResumed()) { + if (isSelectedTrackRecording() && !isSelectedTrackPaused()) { + lastLocation = location; + StatsUtils.setLocationValues(getActivity(), location, true); + } else { + if (lastLocation != null) { + lastLocation = null; + StatsUtils.setLocationValues(getActivity(), lastLocation, true); + } + } + } } }); } @@ -146,14 +159,14 @@ public class StatsFragment extends Fragment implements TrackDataListener { @Override public void onSelectedTrackChanged(Track track) { if (isResumed()) { - boolean isRecording = isSelectedTrackRecording(); - if (uiUpdateThread == null && isRecording) { - uiUpdateThread = new UiUpdateThread(); - uiUpdateThread.start(); - } else if (uiUpdateThread != null && !isRecording) { + if (uiUpdateThread != null) { uiUpdateThread.interrupt(); uiUpdateThread = null; } + if (isSelectedTrackRecording()) { + uiUpdateThread = new UiUpdateThread(); + uiUpdateThread.start(); + } } } @@ -163,18 +176,10 @@ public class StatsFragment extends Fragment implements TrackDataListener { getActivity().runOnUiThread(new Runnable() { @Override public void run() { - if (track == null || track.getTripStatistics() == null) { - lastLocation = null; - lastTripStatistics = null; - updateUi(); - return; + if (isResumed()) { + lastTripStatistics = track != null ? track.getTripStatistics() : null; + updateUi(getActivity()); } - lastTripStatistics = track.getTripStatistics(); - - if (!isSelectedTrackRecording()) { - lastLocation = null; - } - updateUi(); } }); } @@ -226,7 +231,9 @@ public class StatsFragment extends Fragment implements TrackDataListener { getActivity().runOnUiThread(new Runnable() { @Override public void run() { - updateUi(); + if (isResumed()) { + updateUi(getActivity()); + } } }); } @@ -239,7 +246,9 @@ public class StatsFragment extends Fragment implements TrackDataListener { getActivity().runOnUiThread(new Runnable() { @Override public void run() { - updateUi(); + if (isResumed()) { + updateUi(getActivity()); + } } }); } @@ -258,11 +267,8 @@ public class StatsFragment extends Fragment implements TrackDataListener { */ private synchronized void resumeTrackDataHub() { trackDataHub = ((TrackDetailActivity) getActivity()).getTrackDataHub(); - trackDataHub.registerTrackDataListener(this, EnumSet.of( - TrackDataType.SELECTED_TRACK, - TrackDataType.TRACKS_TABLE, - TrackDataType.LOCATION, - TrackDataType.PREFERENCE)); + trackDataHub.registerTrackDataListener(this, EnumSet.of(TrackDataType.SELECTED_TRACK, + TrackDataType.TRACKS_TABLE, TrackDataType.LOCATION, TrackDataType.PREFERENCE)); } /** @@ -293,8 +299,8 @@ public class StatsFragment extends Fragment implements TrackDataListener { /** * Updates the UI. */ - private void updateUi() { - StatsUtils.setTripStatisticsValues(getActivity(), lastTripStatistics); - StatsUtils.setLocationValues(getActivity(), lastLocation, true); + private void updateUi(FragmentActivity activity) { + StatsUtils.setTripStatisticsValues(activity, lastTripStatistics); + StatsUtils.setLocationValues(activity, lastLocation, true); } } diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/file/GpxImporter.java b/MyTracks/src/com/google/android/apps/mytracks/io/file/GpxImporter.java index 8059b1057..7c2b05039 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/file/GpxImporter.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/file/GpxImporter.java @@ -18,7 +18,7 @@ package com.google.android.apps.mytracks.io.file; import com.google.android.apps.mytracks.Constants; import com.google.android.apps.mytracks.content.MyTracksProviderUtils; import com.google.android.apps.mytracks.content.Track; -import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; +import com.google.android.apps.mytracks.stats.TripStatisticsUpdater; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.apps.mytracks.util.StringUtils; @@ -106,9 +106,9 @@ public class GpxImporter extends DefaultHandler { private Track track; /** - * Statistics builder for the current track. + * Trip statistics updater for the current track. */ - private TripStatisticsBuilder tripStatisticsBuilder; + private TripStatisticsUpdater tripStatisticsUpdater; /** * Buffer of locations to be bulk-inserted into the database. @@ -301,20 +301,20 @@ public class GpxImporter extends DefaultHandler { flushPoints(); // Calculate statistics for the imported track - tripStatisticsBuilder.updateTime(lastLocation.getTime()); + tripStatisticsUpdater.updateTime(lastLocation.getTime()); track.setStopId(getLastPointId()); } else { - tripStatisticsBuilder = new TripStatisticsBuilder(0L); - tripStatisticsBuilder.updateTime(0L); + tripStatisticsUpdater = new TripStatisticsUpdater(0L); + tripStatisticsUpdater.updateTime(0L); } - track.setTripStatistics(tripStatisticsBuilder.getTripStatistics()); + track.setTripStatistics(tripStatisticsUpdater.getTripStatistics()); track.setNumberOfPoints(numberOfLocations); myTracksProviderUtils.updateTrack(track); tracksIds.add(track.getId()); isCurrentTrackRollbackable = false; lastSegmentLocation = null; lastLocation = null; - tripStatisticsBuilder = null; + tripStatisticsUpdater = null; } /** @@ -377,11 +377,11 @@ public class GpxImporter extends DefaultHandler { */ private void onTrackPointElementEnd() throws SAXException { if (LocationUtils.isValidLocation(location)) { - if (tripStatisticsBuilder == null) { + if (tripStatisticsUpdater == null) { // first point did not have a time, start stats builder without it - tripStatisticsBuilder = new TripStatisticsBuilder(0); + tripStatisticsUpdater = new TripStatisticsUpdater(0); } - tripStatisticsBuilder.addLocation(location, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); + tripStatisticsUpdater.addLocation(location, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); // insert in db insertPoint(location); @@ -448,8 +448,8 @@ public class GpxImporter extends DefaultHandler { location.setTime(time); // initialize start time with time of first track point - if (tripStatisticsBuilder == null) { - tripStatisticsBuilder = new TripStatisticsBuilder(time); + if (tripStatisticsUpdater == null) { + tripStatisticsUpdater = new TripStatisticsUpdater(time); } } @@ -506,7 +506,7 @@ public class GpxImporter extends DefaultHandler { if (numBufferedPointInserts <= 0) { return; } - myTracksProviderUtils.bulkInsertTrackPoints( + myTracksProviderUtils.bulkInsertTrackPoint( bufferedPointInserts, numBufferedPointInserts, track.getId()); numBufferedPointInserts = 0; } @@ -528,7 +528,7 @@ public class GpxImporter extends DefaultHandler { */ private long getLastPointId() { flushPoints(); - return myTracksProviderUtils.getLastTrackLocationId(track.getId()); + return myTracksProviderUtils.getLastTrackPointId(track.getId()); } /** diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/file/SaveAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/file/SaveAsyncTask.java index 622594f94..9be2add93 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/file/SaveAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/file/SaveAsyncTask.java @@ -168,7 +168,7 @@ public class SaveAsyncTask extends AsyncTask { private Boolean saveAllTracks() { Cursor cursor = null; try { - cursor = myTracksProviderUtils.getTracksCursor(null, null, TracksColumns._ID); + cursor = myTracksProviderUtils.getTrackCursor(null, null, TracksColumns._ID); if (cursor == null) { messageId = R.string.sd_card_save_error_no_track; return false; diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/file/TrackWriterImpl.java b/MyTracks/src/com/google/android/apps/mytracks/io/file/TrackWriterImpl.java index e7fe59768..0a1dadbc4 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/file/TrackWriterImpl.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/file/TrackWriterImpl.java @@ -245,7 +245,7 @@ class TrackWriterImpl implements TrackWriter { // problem because we don't try to load them into objects all at the // same time. Cursor cursor = null; - cursor = providerUtils.getWaypointsCursor(trackId, 0, + cursor = providerUtils.getWaypointCursor(trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); boolean hasWaypoints = false; if (cursor != null) { @@ -314,7 +314,7 @@ class TrackWriterImpl implements TrackWriter { }; TrackWriterLocationFactory locationFactory = new TrackWriterLocationFactory(); - LocationIterator it = providerUtils.getLocationIterator(track.getId(), 0, false, + LocationIterator it = providerUtils.getTrackPointLocationIterator(track.getId(), 0, false, locationFactory); try { if (!it.hasNext()) { diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java index 0afa56da0..3521d7041 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/fusiontables/SendFusionTablesAsyncTask.java @@ -10,7 +10,7 @@ import com.google.android.apps.mytracks.content.Track; import com.google.android.apps.mytracks.content.Waypoint; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils; -import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; +import com.google.android.apps.mytracks.stats.TripStatisticsUpdater; import com.google.android.apps.mytracks.util.ApiAdapterFactory; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; @@ -208,31 +208,31 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { * @return true if success. */ private boolean uploadAllTrackPoints(Track track) { - Cursor locationsCursor = null; + Cursor cursor = null; try { - locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); - if (locationsCursor == null) { + cursor = myTracksProviderUtils.getTrackPointCursor(trackId, 0, -1, false); + if (cursor == null) { Log.d(TAG, "Location cursor is null"); return false; } - int locationsCount = locationsCursor.getCount(); + int count = cursor.getCount(); List locations = new ArrayList(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; // For chart server, limit the number of elevation readings to 250. - int elevationSamplingFrequency = Math.max(1, (int) (locationsCount / 250.0)); + int elevationSamplingFrequency = Math.max(1, (int) (count / 250.0)); Vector distances = new Vector(); Vector elevations = new Vector(); - TripStatisticsBuilder tripStatisticsBuilder = new TripStatisticsBuilder( + TripStatisticsUpdater tripStatisticsUpdater = new TripStatisticsUpdater( track.getTripStatistics().getStartTime()); int minRecordingDistance = PreferencesUtils.getInt(context, R.string.min_recording_distance_key, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); - for (int i = 0; i < locationsCount; i++) { - locationsCursor.moveToPosition(i); + for (int i = 0; i < count; i++) { + cursor.moveToPosition(i); - Location location = myTracksProviderUtils.createLocation(locationsCursor); + Location location = myTracksProviderUtils.createTrackPoint(cursor); locations.add(location); if (i == 0) { @@ -244,10 +244,10 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { } } - tripStatisticsBuilder.addLocation(location, minRecordingDistance); + tripStatisticsUpdater.addLocation(location, minRecordingDistance); if (i % elevationSamplingFrequency == 0) { - distances.add(tripStatisticsBuilder.getTripStatistics().getTotalDistance()); - elevations.add(tripStatisticsBuilder.getSmoothedElevation()); + distances.add(tripStatisticsUpdater.getTripStatistics().getTotalDistance()); + elevations.add(tripStatisticsUpdater.getSmoothedElevation()); } if (LocationUtils.isValidLocation(location)) { lastLocation = location; @@ -260,7 +260,7 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { Log.d(TAG, "Unable to upload points"); return false; } - updateProgress(readCount, locationsCount); + updateProgress(readCount, count); locations.clear(); } } @@ -273,8 +273,8 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { // Create an end marker if (lastLocation != null) { - distances.add(tripStatisticsBuilder.getTripStatistics().getTotalDistance()); - elevations.add(tripStatisticsBuilder.getSmoothedElevation()); + distances.add(tripStatisticsUpdater.getTripStatistics().getTotalDistance()); + elevations.add(tripStatisticsUpdater.getSmoothedElevation()); DescriptionGenerator descriptionGenerator = new DescriptionGeneratorImpl(context); track.setDescription( descriptionGenerator.generateTrackDescription(track, distances, elevations, true)); @@ -287,8 +287,8 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { return true; } finally { - if (locationsCursor != null) { - locationsCursor.close(); + if (cursor != null) { + cursor.close(); } } } @@ -328,7 +328,7 @@ public class SendFusionTablesAsyncTask extends AbstractSendAsyncTask { private boolean uploadWaypoints() { Cursor cursor = null; try { - cursor = myTracksProviderUtils.getWaypointsCursor( + cursor = myTracksProviderUtils.getWaypointCursor( trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { // This will skip the first waypoint (it carries the stats for the diff --git a/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java b/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java index 5e00b08f0..0dfab09ce 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java +++ b/MyTracks/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTask.java @@ -28,7 +28,7 @@ import com.google.android.apps.mytracks.io.gdata.maps.MapsGDataConverter; import com.google.android.apps.mytracks.io.gdata.maps.XmlMapsGDataParserFactory; import com.google.android.apps.mytracks.io.sendtogoogle.AbstractSendAsyncTask; import com.google.android.apps.mytracks.io.sendtogoogle.SendToGoogleUtils; -import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; +import com.google.android.apps.mytracks.stats.TripStatisticsUpdater; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; import com.google.android.common.gdata.AndroidXmlParserFactory; @@ -251,31 +251,31 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { */ @VisibleForTesting boolean uploadAllTrackPoints(Track track) { - Cursor locationsCursor = null; + Cursor cursor = null; try { - locationsCursor = myTracksProviderUtils.getLocationsCursor(trackId, 0, -1, false); - if (locationsCursor == null) { + cursor = myTracksProviderUtils.getTrackPointCursor(trackId, 0, -1, false); + if (cursor == null) { Log.d(TAG, "Location cursor is null"); return false; } - int locationsCount = locationsCursor.getCount(); + int count = cursor.getCount(); List locations = new ArrayList(MAX_POINTS_PER_UPLOAD); Location lastLocation = null; // For chart server, limit the number of elevation readings to 250. - int elevationSamplingFrequency = Math.max(1, (int) (locationsCount / 250.0)); + int elevationSamplingFrequency = Math.max(1, (int) (count / 250.0)); Vector distances = new Vector(); Vector elevations = new Vector(); - TripStatisticsBuilder tripStatisticsBuilder = new TripStatisticsBuilder( + TripStatisticsUpdater tripStatisticsUpdater = new TripStatisticsUpdater( track.getTripStatistics().getStartTime()); int minRecordingDistance = PreferencesUtils.getInt(context, R.string.min_recording_distance_key, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); - for (int i = 0; i < locationsCount; i++) { - locationsCursor.moveToPosition(i); + for (int i = 0; i < count; i++) { + cursor.moveToPosition(i); - Location location = myTracksProviderUtils.createLocation(locationsCursor); + Location location = myTracksProviderUtils.createTrackPoint(cursor); locations.add(location); if (i == 0) { @@ -287,10 +287,10 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { } } - tripStatisticsBuilder.addLocation(location, minRecordingDistance); + tripStatisticsUpdater.addLocation(location, minRecordingDistance); if (i % elevationSamplingFrequency == 0) { - distances.add(tripStatisticsBuilder.getTripStatistics().getTotalDistance()); - elevations.add(tripStatisticsBuilder.getSmoothedElevation()); + distances.add(tripStatisticsUpdater.getTripStatistics().getTotalDistance()); + elevations.add(tripStatisticsUpdater.getSmoothedElevation()); } if (LocationUtils.isValidLocation(location)) { lastLocation = location; @@ -303,7 +303,7 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { Log.d(TAG, "Unable to upload points"); return false; } - updateProgress(readCount, locationsCount); + updateProgress(readCount, count); locations.clear(); } } @@ -316,8 +316,8 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { // Create an end marker if (lastLocation != null) { - distances.add(tripStatisticsBuilder.getTripStatistics().getTotalDistance()); - elevations.add(tripStatisticsBuilder.getSmoothedElevation()); + distances.add(tripStatisticsUpdater.getTripStatistics().getTotalDistance()); + elevations.add(tripStatisticsUpdater.getSmoothedElevation()); DescriptionGenerator descriptionGenerator = new DescriptionGeneratorImpl(context); track.setDescription( descriptionGenerator.generateTrackDescription(track, distances, elevations, true)); @@ -329,8 +329,8 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { } return true; } finally { - if (locationsCursor != null) { - locationsCursor.close(); + if (cursor != null) { + cursor.close(); } } } @@ -436,7 +436,7 @@ public class SendMapsAsyncTask extends AbstractSendAsyncTask { boolean uploadWaypoints() { Cursor cursor = null; try { - cursor = myTracksProviderUtils.getWaypointsCursor( + cursor = myTracksProviderUtils.getWaypointCursor( trackId, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS); if (cursor != null && cursor.moveToFirst()) { // This will skip the first waypoint (it carries the stats for the diff --git a/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java b/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java index c842ad76e..442417da1 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java +++ b/MyTracks/src/com/google/android/apps/mytracks/services/TrackRecordingService.java @@ -36,7 +36,7 @@ import com.google.android.apps.mytracks.services.tasks.AnnouncementPeriodicTaskF import com.google.android.apps.mytracks.services.tasks.PeriodicTaskExecutor; import com.google.android.apps.mytracks.services.tasks.SplitPeriodicTaskFactory; import com.google.android.apps.mytracks.stats.TripStatistics; -import com.google.android.apps.mytracks.stats.TripStatisticsBuilder; +import com.google.android.apps.mytracks.stats.TripStatisticsUpdater; import com.google.android.apps.mytracks.util.IntentUtils; import com.google.android.apps.mytracks.util.LocationUtils; import com.google.android.apps.mytracks.util.PreferencesUtils; @@ -82,8 +82,8 @@ import java.util.concurrent.Executors; public class TrackRecordingService extends Service { private static final String TAG = TrackRecordingService.class.getSimpleName(); - public static final int PAUSE_LATITUDE = 100; - private static final int RESUME_LATITUDE = 200; + public static final double PAUSE_LATITUDE = 100.0; + private static final double RESUME_LATITUDE = 200.0; // One second in milliseconds private static final long ONE_SECOND = 1000; @@ -110,8 +110,8 @@ public class TrackRecordingService extends Service { private long currentRecordingInterval; // The following variables are set when recording: - private TripStatisticsBuilder trackTripStatisticsBuilder; - private TripStatisticsBuilder markerTripStatisticsBuilder; + private TripStatisticsUpdater trackTripStatisticsUpdater; + private TripStatisticsUpdater markerTripStatisticsUpdater; private WakeLock wakeLock; private SensorManager sensorManager; private Location lastLocation; @@ -397,10 +397,10 @@ public class TrackRecordingService extends Service { * Gets the trip statistics. */ public TripStatistics getTripStatistics() { - if (trackTripStatisticsBuilder == null) { + if (trackTripStatisticsUpdater == null) { return null; } - return trackTripStatisticsBuilder.getTripStatistics(); + return trackTripStatisticsUpdater.getTripStatistics(); } /** @@ -419,23 +419,23 @@ public class TrackRecordingService extends Service { if (waypointCreationRequest.getName() != null) { name = waypointCreationRequest.getName(); } else { - int nextMarkerNumber = myTracksProviderUtils.getNextMarkerNumber( + int nextWaypointNumber = myTracksProviderUtils.getNextWaypointNumber( recordingTrackId, isStatistics); - if (nextMarkerNumber == -1) { - nextMarkerNumber = 0; + if (nextWaypointNumber == -1) { + nextWaypointNumber = 0; } name = getString( isStatistics ? R.string.marker_split_name_format : R.string.marker_name_format, - nextMarkerNumber); + nextWaypointNumber); } TripStatistics tripStatistics; String description; if (isStatistics) { long now = System.currentTimeMillis(); - markerTripStatisticsBuilder.updateTime(now); - tripStatistics = markerTripStatisticsBuilder.getTripStatistics(); - markerTripStatisticsBuilder = new TripStatisticsBuilder(now); + markerTripStatisticsUpdater.updateTime(now); + tripStatistics = markerTripStatisticsUpdater.getTripStatistics(); + markerTripStatisticsUpdater = new TripStatisticsUpdater(now); description = new DescriptionGeneratorImpl(this).generateWaypointDescription(tripStatistics); } else { tripStatistics = null; @@ -452,10 +452,9 @@ public class TrackRecordingService extends Service { int type = isStatistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT; long duration; double length; - Location lastTrackLocation = myTracksProviderUtils.getLastTrackLocation(recordingTrackId); - if (currentSegmentHasLocation && LocationUtils.isValidLocation(lastTrackLocation) - && trackTripStatisticsBuilder != null) { - TripStatistics stats = trackTripStatisticsBuilder.getTripStatistics(); + Location location = getLastValidTrackPointInCurrentSegment(recordingTrackId); + if (location != null && trackTripStatisticsUpdater != null) { + TripStatistics stats = trackTripStatisticsUpdater.getTripStatistics(); length = stats.getTotalDistance(); duration = stats.getTotalTime(); } else { @@ -463,14 +462,14 @@ public class TrackRecordingService extends Service { return -1L; } // For track statistics, make it an impossible location - lastTrackLocation = new Location(""); - lastTrackLocation.setLatitude(100); - lastTrackLocation.setLongitude(180); + location = new Location(""); + location.setLatitude(100); + location.setLongitude(180); length = 0; duration = 0; } Waypoint waypoint = new Waypoint(name, description, category, icon, recordingTrackId, type, - length, duration, -1L, -1L, lastTrackLocation, tripStatistics); + length, duration, -1L, -1L, location, tripStatistics); Uri uri = myTracksProviderUtils.insertWaypoint(waypoint); return Long.parseLong(uri.getLastPathSegment()); } @@ -557,8 +556,8 @@ public class TrackRecordingService extends Service { return -1L; } long now = System.currentTimeMillis(); - trackTripStatisticsBuilder = new TripStatisticsBuilder(now); - markerTripStatisticsBuilder = new TripStatisticsBuilder(now); + trackTripStatisticsUpdater = new TripStatisticsUpdater(now); + markerTripStatisticsUpdater = new TripStatisticsUpdater(now); // Insert a track Track track = new Track(); @@ -574,7 +573,7 @@ public class TrackRecordingService extends Service { track.setName(TrackNameUtils.getTrackName(this, trackId, now, null)); track.setCategory(PreferencesUtils.getString( this, R.string.default_activity_key, PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT)); - track.setTripStatistics(trackTripStatisticsBuilder.getTripStatistics()); + track.setTripStatistics(trackTripStatisticsUpdater.getTripStatistics()); myTracksProviderUtils.updateTrack(track); insertWaypoint(WaypointCreationRequest.DEFAULT_START_TRACK); @@ -591,7 +590,7 @@ public class TrackRecordingService extends Service { Log.d(TAG, "Restarting track: " + track.getId()); TripStatistics tripStatistics = track.getTripStatistics(); - trackTripStatisticsBuilder = new TripStatisticsBuilder(tripStatistics.getStartTime()); + trackTripStatisticsUpdater = new TripStatisticsUpdater(tripStatistics.getStartTime()); long markerStartTime; Waypoint waypoint = myTracksProviderUtils.getLastStatisticsWaypoint(recordingTrackId); @@ -600,22 +599,22 @@ public class TrackRecordingService extends Service { } else { markerStartTime = tripStatistics.getStartTime(); } - markerTripStatisticsBuilder = new TripStatisticsBuilder(markerStartTime); + markerTripStatisticsUpdater = new TripStatisticsUpdater(markerStartTime); Cursor cursor = null; try { // TODO: how to handle very long track. - cursor = myTracksProviderUtils.getLocationsCursor( + cursor = myTracksProviderUtils.getTrackPointCursor( recordingTrackId, -1, Constants.MAX_LOADED_TRACK_POINTS, true); if (cursor == null) { Log.e(TAG, "Cursor is null."); } else { if (cursor.moveToLast()) { do { - Location location = myTracksProviderUtils.createLocation(cursor); - trackTripStatisticsBuilder.addLocation(location, minRecordingDistance); + Location location = myTracksProviderUtils.createTrackPoint(cursor); + trackTripStatisticsUpdater.addLocation(location, minRecordingDistance); if (location.getTime() > markerStartTime) { - markerTripStatisticsBuilder.addLocation(location, minRecordingDistance); + markerTripStatisticsUpdater.addLocation(location, minRecordingDistance); } } while (cursor.moveToPrevious()); } @@ -701,14 +700,26 @@ public class TrackRecordingService extends Service { // Update database Track track = myTracksProviderUtils.getTrack(trackId); if (track != null) { - insertLocation(track, lastLocation, myTracksProviderUtils.getLastTrackLocation(trackId)); - updateRecordingTrack(track, myTracksProviderUtils.getLastTrackLocationId(trackId), false); + insertLocation(track, lastLocation, getLastValidTrackPointInCurrentSegment(trackId)); + updateRecordingTrack(track, myTracksProviderUtils.getLastTrackPointId(trackId), false); } endRecording(true, trackId); stopSelf(); } + /** + * Gets the last valid track point in the current segment. Returns null if not available. + * + * @param trackId the track id + */ + private Location getLastValidTrackPointInCurrentSegment(long trackId) { + if (!currentSegmentHasLocation) { + return null; + } + return myTracksProviderUtils.getLastValidTrackPoint(trackId); + } + /** * Pauses the current track. */ @@ -725,8 +736,7 @@ public class TrackRecordingService extends Service { // Update database Track track = myTracksProviderUtils.getTrack(recordingTrackId); if (track != null) { - insertLocation( - track, lastLocation, myTracksProviderUtils.getLastTrackLocation(track.getId())); + insertLocation(track, lastLocation, getLastValidTrackPointInCurrentSegment(track.getId())); Location pause = new Location(LocationManager.GPS_PROVIDER); pause.setLongitude(0); @@ -809,9 +819,8 @@ public class TrackRecordingService extends Service { return; } - Location lastTrackLocation = myTracksProviderUtils.getLastTrackLocation(track.getId()); - long idleTime = currentSegmentHasLocation && LocationUtils.isValidLocation(lastTrackLocation) ? - location.getTime() - lastTrackLocation.getTime() + Location lastValidTrackPoint = getLastValidTrackPointInCurrentSegment(track.getId()); + long idleTime = lastValidTrackPoint != null ? location.getTime() - lastValidTrackPoint.getTime() : 0L; locationListenerPolicy.updateIdleTime(idleTime); if (currentRecordingInterval != locationListenerPolicy.getDesiredPollingInterval()) { @@ -825,41 +834,41 @@ public class TrackRecordingService extends Service { // Always insert the first segment location if (!currentSegmentHasLocation) { - insertLocation(track, location, lastTrackLocation); + insertLocation(track, location, null); currentSegmentHasLocation = true; lastLocation = location; return; } - if (!LocationUtils.isValidLocation(lastTrackLocation)) { + if (!LocationUtils.isValidLocation(lastValidTrackPoint)) { /* * Should not happen. The current segment should have a location. Just * insert the current location. */ - insertLocation(track, location, lastTrackLocation); + insertLocation(track, location, null); lastLocation = location; return; } - double distanceToLastTrackLocation = location.distanceTo(lastTrackLocation); + double distanceToLastTrackLocation = location.distanceTo(lastValidTrackPoint); if (distanceToLastTrackLocation < minRecordingDistance && sensorDataSet == null) { Log.d(TAG, "Not recording location due to min recording distance."); } else if (distanceToLastTrackLocation > maxRecordingDistance) { - insertLocation(track, lastLocation, lastTrackLocation); + insertLocation(track, lastLocation, lastValidTrackPoint); Location pause = new Location(LocationManager.GPS_PROVIDER); pause.setLongitude(0); pause.setLatitude(PAUSE_LATITUDE); pause.setTime(lastLocation.getTime()); insertLocation(track, pause, null); - insertLocation(track, location, lastTrackLocation); + insertLocation(track, location, null); } else { /* * (distanceToLastTrackLocation >= minRecordingDistance || * hasSensorData) && distanceToLastTrackLocation <= maxRecordingDistance */ - insertLocation(track, lastLocation, lastTrackLocation); - insertLocation(track, location, lastTrackLocation); + insertLocation(track, lastLocation, lastValidTrackPoint); + insertLocation(track, location, null); } lastLocation = location; } catch (Error e) { @@ -871,21 +880,29 @@ public class TrackRecordingService extends Service { } } - private void insertLocation(Track track, Location location, Location lastRecordedLocation) { + /** + * Inserts a location. + * + * @param track the track + * @param location the location + * @param lastValidTrackPoint the last valid track point, can be null + */ + private void insertLocation(Track track, Location location, Location lastValidTrackPoint) { if (location == null) { Log.w(TAG, "Ignore insertLocation. loation is null."); return; } - if (location.equals(lastRecordedLocation)) { - Log.w(TAG, "Ignore insertLocation. loation same as last recorded location."); + // Do not insert if inserted already + if (lastValidTrackPoint != null && lastValidTrackPoint.getTime() == location.getTime()) { + Log.w(TAG, "Ignore insertLocation. location time same as last valid track point time."); return; } try { Uri uri = myTracksProviderUtils.insertTrackPoint(location, track.getId()); long trackPointId = Long.parseLong(uri.getLastPathSegment()); - trackTripStatisticsBuilder.addLocation(location, minRecordingDistance); - markerTripStatisticsBuilder.addLocation(location, minRecordingDistance); + trackTripStatisticsUpdater.addLocation(location, minRecordingDistance); + markerTripStatisticsUpdater.addLocation(location, minRecordingDistance); updateRecordingTrack(track, trackPointId, LocationUtils.isValidLocation(location)); } catch (SQLiteException e) { /* @@ -911,8 +928,8 @@ public class TrackRecordingService extends Service { track.setNumberOfPoints(track.getNumberOfPoints() + 1); } - trackTripStatisticsBuilder.updateTime(System.currentTimeMillis()); - track.setTripStatistics(trackTripStatisticsBuilder.getTripStatistics()); + trackTripStatisticsUpdater.updateTime(System.currentTimeMillis()); + track.setTripStatistics(trackTripStatisticsUpdater.getTripStatistics()); myTracksProviderUtils.updateTrack(track); } diff --git a/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java b/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdater.java similarity index 95% rename from MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java rename to MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdater.java index c9933becd..9b18f8ced 100644 --- a/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilder.java +++ b/MyTracks/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdater.java @@ -27,14 +27,14 @@ import android.location.Location; import android.util.Log; /** - * Builder for {@link TripStatistics}. For keeping track statistics as new + * Updater for {@link TripStatistics}. For updating track trip statistics as new * locations are added. Note that some of the locations represent pause/resume * separator. * * @author Sandor Dornbush * @author Rodrigo Damazio */ -public class TripStatisticsBuilder { +public class TripStatisticsUpdater { // The track's trip statistics private final TripStatistics tripStatistics; @@ -62,11 +62,11 @@ public class TripStatisticsBuilder { private final DoubleBuffer gradeBuffer = new DoubleBuffer(Constants.GRADE_SMOOTHING_FACTOR); /** - * Creates a new trip statistics builder. + * Creates a new trip statistics updater. * * @param startTime the start time */ - public TripStatisticsBuilder(long startTime) { + public TripStatisticsUpdater(long startTime) { tripStatistics = init(startTime); currentSegment = init(startTime); } @@ -96,6 +96,10 @@ public class TripStatisticsBuilder { if (!LocationUtils.isValidLocation(location)) { updateTime(location.getTime()); if (location.getLatitude() == TrackRecordingService.PAUSE_LATITUDE) { + if (lastLocation != null && lastMovingLocation != null + && lastLocation != lastMovingLocation) { + currentSegment.addTotalDistance(lastMovingLocation.distanceTo(lastLocation)); + } tripStatistics.merge(currentSegment); } currentSegment = init(location.getTime()); diff --git a/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java b/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java index 8eb6f94e1..3ab8c18d0 100644 --- a/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java +++ b/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtils.java @@ -16,7 +16,6 @@ package com.google.android.apps.mytracks.content; -import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.location.Location; @@ -40,14 +39,23 @@ public interface MyTracksProviderUtils { public static final String AUTHORITY = "com.google.android.maps.mytracks"; /** - * Gets a track cursor. The caller owns the returned cursor and is responsible - * for closing it. + * Creates a {@link Track} from a cursor. * - * @param selection the selection - * @param selectionArgs the selection arguments - * @param sortOrder the sort order + * @param cursor the cursor pointing to the track */ - public Cursor getTracksCursor(String selection, String[] selectionArgs, String sortOrder); + public Track createTrack(Cursor cursor); + + /** + * Deletes all tracks (including waypoints and track points). + */ + public void deleteAllTracks(); + + /** + * Deletes a track. + * + * @param trackId the track id + */ + public void deleteTrack(long trackId); /** * Gets all the tracks. If no track exists, an empty list is returned. @@ -56,6 +64,11 @@ public interface MyTracksProviderUtils { */ public List getAllTracks(); + /** + * Gets the last track. Returns null if doesn't exist. + */ + public Track getLastTrack(); + /** * Gets a track by a track id. Returns null if not found. *

@@ -66,21 +79,14 @@ public interface MyTracksProviderUtils { public Track getTrack(long trackId); /** - * Gets the last track. Returns null if doesn't exist. - */ - public Track getLastTrack(); - - /** - * Gets the last track id. Returns -1L if doesn't exist. - */ - public long getLastTrackId(); - - /** - * Returns true if a track exists. + * Gets a track cursor. The caller owns the returned cursor and is responsible + * for closing it. * - * @param trackId the track id + * @param selection the selection + * @param selectionArgs the selection arguments + * @param sortOrder the sort order */ - public boolean trackExists(long trackId); + public Cursor getTrackCursor(String selection, String[] selectionArgs, String sortOrder); /** * Inserts a track. @@ -102,61 +108,21 @@ public interface MyTracksProviderUtils { public void updateTrack(Track track); /** - * Deletes all tracks (including waypoints and track points). + * Creates a waypoint from a cursor. + * + * @param cursor the cursor pointing to the waypoint */ - public void deleteAllTracks(); + public Waypoint createWaypoint(Cursor cursor); /** - * Deletes a track. + * Deletes a waypoint. If deleting a statistics waypoint, this will also + * correct the next statistics waypoint after the deleted one to reflect the + * deletion. The generator is used to update the next statistics waypoint. * - * @param trackId the track id + * @param waypointId the waypoint id + * @param descriptionGenerator the description generator */ - public void deleteTrack(long trackId); - - /** - * Creates a {@link Track} from a cursor. - * - * @param cursor the cursor pointing to the track - */ - public Track createTrack(Cursor cursor); - - /** - * Creates a {@link ContentValues} from a track. - * - * @param track the track - */ - public ContentValues createContentValues(Track track); - - /** - * Gets a waypoint cursor. The caller owns the returned cursor and is - * responsible for closing it. - * - * @param selection the selection - * @param selectionArgs the selection arguments - * @param sortOrder the sort order - * @param maxWaypoints the maximum number of waypoints to return - */ - public Cursor getWaypointsCursor( - String selection, String[] selectionArgs, String sortOrder, int maxWaypoints); - - /** - * Gets a waypoint cursor for a track. The caller owns the returned cursor and - * is responsible for closing it. - * - * @param trackId the track id - * @param minWaypointId the minimum waypoint id - * @param maxWaypoints the maximum number of waypoints to return - */ - public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints); - - /** - * Gets the first recorded waypoint for a track. The first waypoint is special - * as it contains the stats for the current segment. Returns null if it - * doesn't exist. - * - * @param trackId the track id - */ - public Waypoint getFirstWaypoint(long trackId); + public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); /** * Gets the first waypoint id for a track. The first waypoint is special as it @@ -167,36 +133,21 @@ public interface MyTracksProviderUtils { */ public long getFirstWaypointId(long trackId); - /** - * Gets the last waypoint id for a track. Returns -1L if it doesn't exist. - * - * @param trackId the track id - */ - public long getLastWaypointId(long trackId); - /** * Gets the last statistics waypoint for a track. Returns null if it doesn't exist. * * @param trackId the track id */ public Waypoint getLastStatisticsWaypoint(long trackId); - + /** - * Gets the next marker number. Returns -1 if not able to get the next marker - * number. + * Gets the next waypoint number. Returns -1 if not able to get the next + * waypoint number. * * @param trackId the track id * @param statistics true for statistics marker, false for waypoint marker */ - public int getNextMarkerNumber(long trackId, boolean statistics); - - /** - * Gets the next statistics waypoint after the given waypoint. Returns null if - * it doesn't exists. - * - * @param waypoint the given waypoint - */ - public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint); + public int getNextWaypointNumber(long trackId, boolean statistics); /** * Gets a waypoint from a waypoint id. Returns null if not found. @@ -205,6 +156,28 @@ public interface MyTracksProviderUtils { */ public Waypoint getWaypoint(long waypointId); + /** + * Gets a waypoint cursor. The caller owns the returned cursor and is + * responsible for closing it. + * + * @param selection the selection + * @param selectionArgs the selection arguments + * @param sortOrder the sort order + * @param maxWaypoints the maximum number of waypoints to return + */ + public Cursor getWaypointCursor( + String selection, String[] selectionArgs, String sortOrder, int maxWaypoints); + + /** + * Gets a waypoint cursor for a track. The caller owns the returned cursor and + * is responsible for closing it. + * + * @param trackId the track id + * @param minWaypointId the minimum waypoint id + * @param maxWaypoints the maximum number of waypoints to return + */ + public Cursor getWaypointCursor(long trackId, long minWaypointId, int maxWaypoints); + /** * Inserts a waypoint. * @@ -221,38 +194,36 @@ public interface MyTracksProviderUtils { public boolean updateWaypoint(Waypoint waypoint); /** - * Deletes a waypoint. If deleting a statistics waypoint, this will also - * correct the next statistics waypoint after the deleted one to reflect the - * deletion. The generator is used to update the next statistics waypoint. + * Inserts multiple track points. * - * @param waypointId the waypoint id - * @param descriptionGenerator the description generator + * @param locations an array of locations + * @param length the number of locations (from the beginning of the array) to + * insert, or -1 for all of them + * @param trackId the track id + * @return the number of points inserted */ - public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator); + public int bulkInsertTrackPoint(Location[] locations, int length, long trackId); /** - * Creates a waypoint from a cursor. + * Creates a location object from a cursor. * - * @param cursor the cursor pointing to the waypoint + * @param cursor the cursor pointing to the location */ - public Waypoint createWaypoint(Cursor cursor); + public Location createTrackPoint(Cursor cursor); /** - * Gets the first recorded location. Returns null if it doesn't exist. - */ - public Location getFirstLocation(); - - /** - * Gets the last recorded location. Returns null if it doesn't exist. - */ - public Location getLastLocation(); - - /** - * Gets a location by track point id. Returns null if not found. + * Gets the last location id for a track. Returns -1L if it doesn't exist. * - * @param trackPointId the track point id + * @param trackId the track id */ - public Location getLocation(long trackPointId); + public long getLastTrackPointId(long trackId); + + /** + * Gets the last valid location for a track. Returns null if it doesn't exist. + * + * @param trackId the track id + */ + public Location getLastValidTrackPoint(long trackId); /** * Creates a location cursor. The caller owns the returned cursor and is @@ -264,7 +235,7 @@ public interface MyTracksProviderUtils { * @param descending true to sort the result in descending order (latest * location first) */ - public Cursor getLocationsCursor( + public Cursor getTrackPointCursor( long trackId, long startTrackPointId, int maxLocations, boolean descending); /** @@ -285,23 +256,9 @@ public interface MyTracksProviderUtils { * location first) * @param locationFactory the location factory */ - public LocationIterator getLocationIterator( + public LocationIterator getTrackPointLocationIterator( long trackId, long startTrackPointId, boolean descending, LocationFactory locationFactory); - /** - * Gets the last location id for a track. Returns -1L if it doesn't exist. - * - * @param trackId the track id - */ - public long getLastTrackLocationId(long trackId); - - /** - * Gets the last location for a track. Returns -1L if it doesn't exist. - * - * @param trackId the track id - */ - public Location getLastTrackLocation(long trackId); - /** * Inserts a track point. * @@ -311,32 +268,6 @@ public interface MyTracksProviderUtils { */ public Uri insertTrackPoint(Location location, long trackId); - /** - * Inserts multiple track points. - * - * @param locations an array of locations - * @param length the number of locations (from the beginning of the array) to - * insert, or -1 for all of them - * @param trackId the track id - * @return the number of points inserted - */ - public int bulkInsertTrackPoints(Location[] locations, int length, long trackId); - - /** - * Fills a location from a cursor. - * - * @param cursor the cursor pointing to the location - * @param location the location to be overwritten - */ - public void fillLocation(Cursor cursor, Location location); - - /** - * Creates a location object from a cursor. - * - * @param cursor the cursor pointing to the location - */ - public Location createLocation(Cursor cursor); - /** * A lightweight wrapper around the original {@link Cursor} with a method to * clean up. diff --git a/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java b/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java index e3910bb9b..57f4f6fd0 100644 --- a/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java +++ b/MyTracksLib/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImpl.java @@ -47,153 +47,6 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { this.contentResolver = contentResolver; } - /** - * Gets a track cursor. - * - * @param projection the projection - * @param selection the selection - * @param selectionArgs the selection arguments - * @param sortOrder the sort oder - */ - private Cursor getTracksCursor( - String[] projection, String selection, String[] selectionArgs, String sortOrder) { - return contentResolver.query( - TracksColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); - } - - @Override - public Cursor getTracksCursor(String selection, String[] selectionArgs, String sortOrder) { - return getTracksCursor(null, selection, selectionArgs, sortOrder); - } - - @Override - public List getAllTracks() { - Cursor cursor = getTracksCursor(null, null, null, TracksColumns._ID); - ArrayList tracks = new ArrayList(); - if (cursor != null) { - tracks.ensureCapacity(cursor.getCount()); - if (cursor.moveToFirst()) { - do { - tracks.add(createTrack(cursor)); - } while (cursor.moveToNext()); - } - cursor.close(); - } - return tracks; - } - - @Override - public Track getTrack(long trackId) { - if (trackId < 0) { - return null; - } - Cursor cursor = null; - try { - cursor = getTracksCursor(null, TracksColumns._ID + "=?", - new String[] { Long.toString(trackId) }, TracksColumns._ID); - if (cursor != null && cursor.moveToNext()) { - return createTrack(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public Track getLastTrack() { - Cursor cursor = null; - try { - String selection = TracksColumns._ID + "=(select max(" + TracksColumns._ID + ") from " - + TracksColumns.TABLE_NAME + ")"; - cursor = getTracksCursor(null, selection, null, TracksColumns._ID); - if (cursor != null && cursor.moveToNext()) { - return createTrack(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public long getLastTrackId() { - Cursor cursor = null; - try { - String selection = TracksColumns._ID + "=(select max(" + TracksColumns._ID + ") from " - + TracksColumns.TABLE_NAME + ")"; - cursor = getTracksCursor( - new String[] { TracksColumns._ID }, selection, null, TracksColumns._ID); - if (cursor != null && cursor.moveToFirst()) { - return cursor.getLong(cursor.getColumnIndexOrThrow(TracksColumns._ID)); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return -1L; - } - - @Override - public boolean trackExists(long trackId) { - if (trackId < 0) { - return false; - } - Cursor cursor = null; - try { - cursor = getTracksCursor(new String[] { TracksColumns._ID }, TracksColumns._ID + "=?", - new String[] { Long.toString(trackId) }, TracksColumns._ID); - if (cursor != null && cursor.moveToNext()) { - return true; - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return false; - } - - @Override - public Uri insertTrack(Track track) { - return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); - } - - @Override - public void updateTrack(Track track) { - contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), - TracksColumns._ID + "=?", new String[] { Long.toString(track.getId()) }); - } - - @Override - public void deleteAllTracks() { - contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); - contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); - // Delete tracks last since it triggers a database vaccum call - contentResolver.delete(TracksColumns.CONTENT_URI, null, null); - } - - @Override - public void deleteTrack(long trackId) { - Track track = getTrack(trackId); - if (track != null) { - String where = TrackPointsColumns._ID + ">=? AND " + TrackPointsColumns._ID + "<=?"; - String[] selectionArgs = new String[] { Long.toString(track.getStartId()), Long.toString( - track.getStopId()) }; - contentResolver.delete(TrackPointsColumns.CONTENT_URI, where, selectionArgs); - } - contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=?", - new String[] { Long.toString(trackId) }); - // Delete tracks last since it triggers a database vaccum call - contentResolver.delete(TracksColumns.CONTENT_URI, TracksColumns._ID + "=?", new String[] { - Long.toString(trackId) }); - } - @Override public Track createTrack(Cursor cursor) { int idIndex = cursor.getColumnIndexOrThrow(TracksColumns._ID); @@ -221,7 +74,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { int mapIdIndex = cursor.getColumnIndexOrThrow(TracksColumns.MAPID); int tableIdIndex = cursor.getColumnIndexOrThrow(TracksColumns.TABLEID); int iconIndex = cursor.getColumnIndexOrThrow(TracksColumns.ICON); - + Track track = new Track(); TripStatistics tripStatistics = track.getTripStatistics(); if (!cursor.isNull(idIndex)) { @@ -299,7 +152,100 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { } @Override - public ContentValues createContentValues(Track track) { + public void deleteAllTracks() { + contentResolver.delete(TrackPointsColumns.CONTENT_URI, null, null); + contentResolver.delete(WaypointsColumns.CONTENT_URI, null, null); + // Delete tracks last since it triggers a database vaccum call + contentResolver.delete(TracksColumns.CONTENT_URI, null, null); + } + + @Override + public void deleteTrack(long trackId) { + Track track = getTrack(trackId); + if (track != null) { + String where = TrackPointsColumns._ID + ">=? AND " + TrackPointsColumns._ID + "<=?"; + String[] selectionArgs = new String[] { Long.toString(track.getStartId()), Long.toString( + track.getStopId()) }; + contentResolver.delete(TrackPointsColumns.CONTENT_URI, where, selectionArgs); + } + contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns.TRACKID + "=?", + new String[] { Long.toString(trackId) }); + // Delete tracks last since it triggers a database vaccum call + contentResolver.delete(TracksColumns.CONTENT_URI, TracksColumns._ID + "=?", new String[] { + Long.toString(trackId) }); + } + + @Override + public List getAllTracks() { + Cursor cursor = getTrackCursor(null, null, null, TracksColumns._ID); + ArrayList tracks = new ArrayList(); + if (cursor != null) { + tracks.ensureCapacity(cursor.getCount()); + if (cursor.moveToFirst()) { + do { + tracks.add(createTrack(cursor)); + } while (cursor.moveToNext()); + } + cursor.close(); + } + return tracks; + } + + @Override + public Track getLastTrack() { + Cursor cursor = null; + try { + String selection = TracksColumns._ID + "=(select max(" + TracksColumns._ID + ") from " + + TracksColumns.TABLE_NAME + ")"; + cursor = getTrackCursor(null, selection, null, TracksColumns._ID); + if (cursor != null && cursor.moveToNext()) { + return createTrack(cursor); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; + } + + @Override + public Track getTrack(long trackId) { + if (trackId < 0) { + return null; + } + Cursor cursor = null; + try { + cursor = getTrackCursor(null, TracksColumns._ID + "=?", + new String[] { Long.toString(trackId) }, TracksColumns._ID); + if (cursor != null && cursor.moveToNext()) { + return createTrack(cursor); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; + } + + @Override + public Cursor getTrackCursor(String selection, String[] selectionArgs, String sortOrder) { + return getTrackCursor(null, selection, selectionArgs, sortOrder); + } + + @Override + public Uri insertTrack(Track track) { + return contentResolver.insert(TracksColumns.CONTENT_URI, createContentValues(track)); + } + + @Override + public void updateTrack(Track track) { + contentResolver.update(TracksColumns.CONTENT_URI, createContentValues(track), + TracksColumns._ID + "=?", new String[] { Long.toString(track.getId()) }); + } + + private ContentValues createContentValues(Track track) { ContentValues values = new ContentValues(); TripStatistics tripStatistics = track.getTripStatistics(); @@ -337,234 +283,17 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { } /** - * Gets a waypoints cursor. + * Gets a track cursor. * * @param projection the projection * @param selection the selection - * @param selectionArgs the selection args - * @param sortOrder the sort order - * @param maxWaypoints the maximum number of waypoints + * @param selectionArgs the selection arguments + * @param sortOrder the sort oder */ - private Cursor getWaypointsCursor(String[] projection, String selection, String[] selectionArgs, - String sortOrder, int maxWaypoints) { - if (sortOrder == null) { - sortOrder = WaypointsColumns._ID; - } - if (maxWaypoints > 0) { - sortOrder += " LIMIT " + maxWaypoints; - } + private Cursor getTrackCursor( + String[] projection, String selection, String[] selectionArgs, String sortOrder) { return contentResolver.query( - WaypointsColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); - } - - @Override - public Cursor getWaypointsCursor( - String selection, String[] selectionArgs, String sortOrder, int maxWaypoints) { - return getWaypointsCursor(null, selection, selectionArgs, sortOrder, maxWaypoints); - } - - @Override - public Cursor getWaypointsCursor(long trackId, long minWaypointId, int maxWaypoints) { - if (trackId < 0) { - return null; - } - - String selection; - String[] selectionArgs; - if (minWaypointId >= 0) { - selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns._ID + ">=?"; - selectionArgs = new String[] { Long.toString(trackId), Long.toString(minWaypointId) }; - } else { - selection = WaypointsColumns.TRACKID + "=?"; - selectionArgs = new String[] { Long.toString(trackId) }; - } - return getWaypointsCursor(null, selection, selectionArgs, WaypointsColumns._ID, maxWaypoints); - } - - @Override - public Waypoint getFirstWaypoint(long trackId) { - if (trackId < 0) { - return null; - } - Cursor cursor = null; - try { - cursor = getWaypointsCursor(null, WaypointsColumns.TRACKID + "=?", new String[] { - Long.toString(trackId) }, WaypointsColumns._ID, 1); - if (cursor != null && cursor.moveToFirst()) { - return createWaypoint(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public long getFirstWaypointId(long trackId) { - if (trackId < 0) { - return -1L; - } - Cursor cursor = null; - try { - cursor = getWaypointsCursor(new String[] { WaypointsColumns._ID }, - WaypointsColumns.TRACKID + "=?", new String[] { Long.toString(trackId) }, - WaypointsColumns._ID, 1); - if (cursor != null && cursor.moveToFirst()) { - return cursor.getLong(cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return -1L; - } - - @Override - public long getLastWaypointId(long trackId) { - if (trackId < 0) { - return -1; - } - Cursor cursor = null; - try { - cursor = getWaypointsCursor(new String[] { WaypointsColumns._ID }, - WaypointsColumns.TRACKID + "=?", new String[] { Long.toString(trackId) }, - WaypointsColumns._ID + " DESC", 1); - if (cursor != null && cursor.moveToFirst()) { - return cursor.getLong(cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return -1L; - } - - @Override - public Waypoint getLastStatisticsWaypoint(long trackId) { - if (trackId < 0) { - return null; - } - Cursor cursor = null; - try { - String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=" - + Waypoint.TYPE_STATISTICS; - String[] selectionArgs = new String[] { Long.toString(trackId) }; - cursor = getWaypointsCursor( - null, selection, selectionArgs, WaypointsColumns._ID + " DESC", 1); - if (cursor != null && cursor.moveToFirst()) { - return createWaypoint(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public int getNextMarkerNumber(long trackId, boolean statistics) { - if (trackId < 0) { - return -1; - } - Cursor cursor = null; - try { - String[] projection = { WaypointsColumns._ID }; - String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=?"; - int type = statistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT; - String[] selectionArgs = new String[] { Long.toString(trackId), Integer.toString(type) }; - cursor = getWaypointsCursor(projection, selection, selectionArgs, WaypointsColumns._ID, 0); - if (cursor != null) { - int count = cursor.getCount(); - /* - * For statistics markers, the first marker is for the track statistics, - * so return the count as the next user visible number. - */ - return statistics ? count : count + 1; - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return -1; - } - - @Override - public Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { - Cursor cursor = null; - try { - String selection = WaypointsColumns._ID + ">? AND " + WaypointsColumns.TRACKID + "=? AND " - + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; - String[] selectionArgs = new String[] { - Long.toString(waypoint.getId()), Long.toString(waypoint.getTrackId()) }; - cursor = getWaypointsCursor(null, selection, selectionArgs, WaypointsColumns._ID, 1); - if (cursor != null && cursor.moveToFirst()) { - return createWaypoint(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public Waypoint getWaypoint(long waypointId) { - if (waypointId < 0) { - return null; - } - Cursor cursor = null; - try { - cursor = getWaypointsCursor(null, WaypointsColumns._ID + "=?", - new String[] { Long.toString(waypointId) }, WaypointsColumns._ID, 0); - if (cursor != null && cursor.moveToFirst()) { - return createWaypoint(cursor); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return null; - } - - @Override - public Uri insertWaypoint(Waypoint waypoint) { - waypoint.setId(-1L); - return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); - } - - @Override - public boolean updateWaypoint(Waypoint waypoint) { - int rows = contentResolver.update(WaypointsColumns.CONTENT_URI, createContentValues(waypoint), - WaypointsColumns._ID + "=?", new String[] { Long.toString(waypoint.getId()) }); - return rows == 1; - } - - @Override - public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { - final Waypoint waypoint = getWaypoint(waypointId); - if (waypoint != null && waypoint.getType() == Waypoint.TYPE_STATISTICS) { - final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(waypoint); - if (nextWaypoint == null) { - Log.d(TAG, "Unable to find the next statistics marker after deleting one."); - } else { - nextWaypoint.getTripStatistics().merge(waypoint.getTripStatistics()); - nextWaypoint.setDescription( - descriptionGenerator.generateWaypointDescription(nextWaypoint.getTripStatistics())); - if (!updateWaypoint(nextWaypoint)) { - Log.e(TAG, "Unable to update the next statistics marker after deleting one."); - } - } - } - contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns._ID + "=?", - new String[] { Long.toString(waypointId) }); + TracksColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); } @Override @@ -597,9 +326,9 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { int elevationGainIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN); int minGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE); int maxGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE); - + Waypoint waypoint = new Waypoint(); - + if (!cursor.isNull(idIndex)) { waypoint.setId(cursor.getLong(idIndex)); } @@ -633,7 +362,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { if (!cursor.isNull(stopIdIndex)) { waypoint.setStopId(cursor.getLong(stopIdIndex)); } - + Location location = new Location(""); if (!cursor.isNull(longitudeIndex) && !cursor.isNull(latitudeIndex)) { location.setLongitude(((double) cursor.getInt(longitudeIndex)) / 1E6); @@ -655,7 +384,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { location.setBearing(cursor.getFloat(bearingIndex)); } waypoint.setLocation(location); - + TripStatistics tripStatistics = new TripStatistics(); boolean hasTripStatistics = false; if (!cursor.isNull(startTimeIndex)) { @@ -698,16 +427,165 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { tripStatistics.setMaxGrade(cursor.getFloat(maxGradeIndex)); hasTripStatistics = true; } - + if (hasTripStatistics) { waypoint.setTripStatistics(tripStatistics); } return waypoint; } + @Override + public void deleteWaypoint(long waypointId, DescriptionGenerator descriptionGenerator) { + final Waypoint waypoint = getWaypoint(waypointId); + if (waypoint != null && waypoint.getType() == Waypoint.TYPE_STATISTICS) { + final Waypoint nextWaypoint = getNextStatisticsWaypointAfter(waypoint); + if (nextWaypoint == null) { + Log.d(TAG, "Unable to find the next statistics marker after deleting one."); + } else { + nextWaypoint.getTripStatistics().merge(waypoint.getTripStatistics()); + nextWaypoint.setDescription( + descriptionGenerator.generateWaypointDescription(nextWaypoint.getTripStatistics())); + if (!updateWaypoint(nextWaypoint)) { + Log.e(TAG, "Unable to update the next statistics marker after deleting one."); + } + } + } + contentResolver.delete(WaypointsColumns.CONTENT_URI, WaypointsColumns._ID + "=?", + new String[] { Long.toString(waypointId) }); + } + + @Override + public long getFirstWaypointId(long trackId) { + if (trackId < 0) { + return -1L; + } + Cursor cursor = null; + try { + cursor = getWaypointCursor(new String[] { WaypointsColumns._ID }, + WaypointsColumns.TRACKID + "=?", new String[] { Long.toString(trackId) }, + WaypointsColumns._ID, 1); + if (cursor != null && cursor.moveToFirst()) { + return cursor.getLong(cursor.getColumnIndexOrThrow(WaypointsColumns._ID)); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return -1L; + } + + @Override + public Waypoint getLastStatisticsWaypoint(long trackId) { + if (trackId < 0) { + return null; + } + Cursor cursor = null; + try { + String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=" + + Waypoint.TYPE_STATISTICS; + String[] selectionArgs = new String[] { Long.toString(trackId) }; + cursor = getWaypointCursor( + null, selection, selectionArgs, WaypointsColumns._ID + " DESC", 1); + if (cursor != null && cursor.moveToFirst()) { + return createWaypoint(cursor); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; + } + + @Override + public int getNextWaypointNumber(long trackId, boolean statistics) { + if (trackId < 0) { + return -1; + } + Cursor cursor = null; + try { + String[] projection = { WaypointsColumns._ID }; + String selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns.TYPE + "=?"; + int type = statistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT; + String[] selectionArgs = new String[] { Long.toString(trackId), Integer.toString(type) }; + cursor = getWaypointCursor(projection, selection, selectionArgs, WaypointsColumns._ID, 0); + if (cursor != null) { + int count = cursor.getCount(); + /* + * For statistics markers, the first marker is for the track statistics, + * so return the count as the next user visible number. + */ + return statistics ? count : count + 1; + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return -1; + } + + @Override + public Waypoint getWaypoint(long waypointId) { + if (waypointId < 0) { + return null; + } + Cursor cursor = null; + try { + cursor = getWaypointCursor(null, WaypointsColumns._ID + "=?", + new String[] { Long.toString(waypointId) }, WaypointsColumns._ID, 0); + if (cursor != null && cursor.moveToFirst()) { + return createWaypoint(cursor); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; + } + + @Override + public Cursor getWaypointCursor( + String selection, String[] selectionArgs, String sortOrder, int maxWaypoints) { + return getWaypointCursor(null, selection, selectionArgs, sortOrder, maxWaypoints); + } + + @Override + public Cursor getWaypointCursor(long trackId, long minWaypointId, int maxWaypoints) { + if (trackId < 0) { + return null; + } + + String selection; + String[] selectionArgs; + if (minWaypointId >= 0) { + selection = WaypointsColumns.TRACKID + "=? AND " + WaypointsColumns._ID + ">=?"; + selectionArgs = new String[] { Long.toString(trackId), Long.toString(minWaypointId) }; + } else { + selection = WaypointsColumns.TRACKID + "=?"; + selectionArgs = new String[] { Long.toString(trackId) }; + } + return getWaypointCursor(null, selection, selectionArgs, WaypointsColumns._ID, maxWaypoints); + } + + @Override + public Uri insertWaypoint(Waypoint waypoint) { + waypoint.setId(-1L); + return contentResolver.insert(WaypointsColumns.CONTENT_URI, createContentValues(waypoint)); + } + + @Override + public boolean updateWaypoint(Waypoint waypoint) { + int rows = contentResolver.update(WaypointsColumns.CONTENT_URI, createContentValues(waypoint), + WaypointsColumns._ID + "=?", new String[] { Long.toString(waypoint.getId()) }); + return rows == 1; + } + ContentValues createContentValues(Waypoint waypoint) { ContentValues values = new ContentValues(); - + // Value < 0 indicates no id is available if (waypoint.getId() >= 0) { values.put(WaypointsColumns._ID, waypoint.getId()); @@ -722,7 +600,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { values.put(WaypointsColumns.DURATION, waypoint.getDuration()); values.put(WaypointsColumns.STARTID, waypoint.getStartId()); values.put(WaypointsColumns.STOPID, waypoint.getStopId()); - + Location location = waypoint.getLocation(); if (location != null) { values.put(WaypointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); @@ -741,7 +619,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { values.put(WaypointsColumns.BEARING, location.getBearing()); } } - + TripStatistics tripStatistics = waypoint.getTripStatistics(); if (tripStatistics != null) { values.put(WaypointsColumns.STARTTIME, tripStatistics.getStartTime()); @@ -760,26 +638,16 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { return values; } - /** - * Gets a track points cursor. - * - * @param projection the projection - * @param selection the selection - * @param selectionArgs the selection arguments - * @param sortOrder the sort order - */ - private Cursor getTrackPointsCursor( - String[] projection, String selection, String[] selectionArgs, String sortOrder) { - return contentResolver.query( - TrackPointsColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); - } - - private Location findLocationBy(String selection, String[] selectionArgs) { + private Waypoint getNextStatisticsWaypointAfter(Waypoint waypoint) { Cursor cursor = null; try { - cursor = getTrackPointsCursor(null, selection, selectionArgs, TrackPointsColumns._ID); - if (cursor != null && cursor.moveToNext()) { - return createLocation(cursor); + String selection = WaypointsColumns._ID + ">? AND " + WaypointsColumns.TRACKID + "=? AND " + + WaypointsColumns.TYPE + "=" + Waypoint.TYPE_STATISTICS; + String[] selectionArgs = new String[] { + Long.toString(waypoint.getId()), Long.toString(waypoint.getTrackId()) }; + cursor = getWaypointCursor(null, selection, selectionArgs, WaypointsColumns._ID, 1); + if (cursor != null && cursor.moveToFirst()) { + return createWaypoint(cursor); } } finally { if (cursor != null) { @@ -789,36 +657,89 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { return null; } - @Override - public Location getFirstLocation() { - String selection = TrackPointsColumns._ID + "=(select min(" + TrackPointsColumns._ID + ") from " - + TrackPointsColumns.TABLE_NAME + ")"; - return findLocationBy(selection, null); + /** + * Gets a waypoint cursor. + * + * @param projection the projection + * @param selection the selection + * @param selectionArgs the selection args + * @param sortOrder the sort order + * @param maxWaypoints the maximum number of waypoints + */ + private Cursor getWaypointCursor(String[] projection, String selection, String[] selectionArgs, + String sortOrder, int maxWaypoints) { + if (sortOrder == null) { + sortOrder = WaypointsColumns._ID; + } + if (maxWaypoints > 0) { + sortOrder += " LIMIT " + maxWaypoints; + } + return contentResolver.query( + WaypointsColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); } @Override - public Location getLastLocation() { - String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID + ") from " - + TrackPointsColumns.TABLE_NAME + ")"; - return findLocationBy(selection, null); + public int bulkInsertTrackPoint(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 Location getLocation(long trackPointId) { - if (trackPointId < 0) { + public Location createTrackPoint(Cursor cursor) { + Location location = new MyTracksLocation(""); + fillTrackPoint(cursor, new CachedTrackPointsIndexes(cursor), location); + return location; + } + + @Override + public long getLastTrackPointId(long trackId) { + if (trackId < 0) { + return -1L; + } + Cursor cursor = null; + try { + String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID + + ") from " + TrackPointsColumns.TABLE_NAME + " WHERE " + TrackPointsColumns.TRACKID + + "=?)"; + String[] selectionArgs = new String[] { Long.toString(trackId) }; + cursor = getTrackPointCursor(new String[] { TrackPointsColumns._ID }, selection, + selectionArgs, TrackPointsColumns._ID); + if (cursor != null && cursor.moveToFirst()) { + return cursor.getLong(cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return -1L; + } + + @Override + public Location getLastValidTrackPoint(long trackId) { + if (trackId < 0) { return null; } - return findLocationBy( - TrackPointsColumns._ID + "=?", new String[] { Long.toString(trackPointId) }); + String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID + ") from " + + TrackPointsColumns.TABLE_NAME + " WHERE " + TrackPointsColumns.TRACKID + "=? AND " + + TrackPointsColumns.LATITUDE + "<=90000000)"; + String[] selectionArgs = new String[] { Long.toString(trackId) }; + return findTrackPointBy(selection, selectionArgs); } @Override - public Cursor getLocationsCursor( + public Cursor getTrackPointCursor( long trackId, long startTrackPointId, int maxLocations, boolean descending) { if (trackId < 0) { return null; } - + String selection; String[] selectionArgs; if (startTrackPointId >= 0) { @@ -830,7 +751,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { selection = TrackPointsColumns.TRACKID + "=?"; selectionArgs = new String[] { Long.toString(trackId) }; } - + String sortOrder = TrackPointsColumns._ID; if (descending) { sortOrder += " DESC"; @@ -838,11 +759,11 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { if (maxLocations > 0) { sortOrder += " LIMIT " + maxLocations; } - return getTrackPointsCursor(null, selection, selectionArgs, sortOrder); + return getTrackPointCursor(null, selection, selectionArgs, sortOrder); } @Override - public LocationIterator getLocationIterator(final long trackId, final long startTrackPointId, + public LocationIterator getTrackPointLocationIterator(final long trackId, final long startTrackPointId, final boolean descending, final LocationFactory locationFactory) { if (locationFactory == null) { throw new IllegalArgumentException("locationFactory is null"); @@ -853,16 +774,16 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { private final CachedTrackPointsIndexes indexes = cursor != null ? new CachedTrackPointsIndexes(cursor) : null; - + /** * Gets the track point cursor. * * @param trackPointId the starting track point id */ private Cursor getCursor(long trackPointId) { - return getLocationsCursor(trackId, trackPointId, defaultCursorBatchSize, descending); + return getTrackPointCursor(trackId, trackPointId, defaultCursorBatchSize, descending); } - + /** * Advances the cursor to the next batch. Returns true if successful. */ @@ -874,12 +795,12 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { cursor = getCursor(trackPointId); return cursor != null; } - + @Override public long getLocationId() { return lastTrackPointId; } - + @Override public boolean hasNext() { if (cursor == null) { @@ -896,7 +817,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { } return true; } - + @Override public Location next() { if (cursor == null) { @@ -909,10 +830,10 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { } lastTrackPointId = cursor.getLong(indexes.idIndex); Location location = locationFactory.createLocation(); - fillLocation(cursor, indexes, location); + fillTrackPoint(cursor, indexes, location); return location; } - + @Override public void close() { if (cursor != null) { @@ -920,7 +841,7 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { cursor = null; } } - + @Override public void remove() { throw new UnsupportedOperationException(); @@ -928,70 +849,62 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { }; } - @Override - public long getLastTrackLocationId(long trackId) { - if (trackId < 0) { - return -1L; - } - Cursor cursor = null; - try { - String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID - + ") from " + TrackPointsColumns.TABLE_NAME + " WHERE " + TrackPointsColumns.TRACKID - + "=?)"; - String[] selectionArgs = new String[] { Long.toString(trackId) }; - cursor = getTrackPointsCursor(new String[] { TrackPointsColumns._ID }, selection, - selectionArgs, TrackPointsColumns._ID); - if (cursor != null && cursor.moveToFirst()) { - return cursor.getLong(cursor.getColumnIndexOrThrow(TrackPointsColumns._ID)); - } - } finally { - if (cursor != null) { - cursor.close(); - } - } - return -1L; - } - - @Override - public Location getLastTrackLocation(long trackId) { - if (trackId < 0) { - return null; - } - String selection = TrackPointsColumns._ID + "=(select max(" + TrackPointsColumns._ID - + ") from " + TrackPointsColumns.TABLE_NAME + " WHERE " + TrackPointsColumns.TRACKID - + "=?)"; - String[] selectionArgs = new String[] { Long.toString(trackId) }; - return findLocationBy(selection, selectionArgs); - } - @Override public Uri insertTrackPoint(Location location, long trackId) { 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; + /** + * Creates the {@link ContentValues} for a {@link Location}. + * + * @param location the location + * @param trackId the track id + */ + private ContentValues createContentValues(Location location, long trackId) { + ContentValues values = new ContentValues(); + values.put(TrackPointsColumns.TRACKID, trackId); + values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); + values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); + + // Hack for Samsung phones that don't properly populate the time field + long time = location.getTime(); + if (time == 0) { + time = System.currentTimeMillis(); } - ContentValues[] values = new ContentValues[length]; - for (int i = 0; i < length; i++) { - values[i] = createContentValues(locations[i], trackId); + values.put(TrackPointsColumns.TIME, time); + if (location.hasAltitude()) { + values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); } - return contentResolver.bulkInsert(TrackPointsColumns.CONTENT_URI, values); + if (location.hasAccuracy()) { + values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); + } + if (location.hasSpeed()) { + values.put(TrackPointsColumns.SPEED, location.getSpeed()); + } + if (location.hasBearing()) { + values.put(TrackPointsColumns.BEARING, location.getBearing()); + } + + if (location instanceof MyTracksLocation) { + MyTracksLocation myTracksLocation = (MyTracksLocation) location; + if (myTracksLocation.getSensorDataSet() != null) { + values.put(TrackPointsColumns.SENSOR, myTracksLocation.getSensorDataSet().toByteArray()); + } + } + return values; } /** - * Fills a location from a cursor. + * Fills a track point from a cursor. * * @param cursor the cursor pointing to a location. * @param indexes the cached track points indexes - * @param location the location + * @param location the track point */ - private void fillLocation(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) { + private void fillTrackPoint(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) { location.reset(); - + if (!cursor.isNull(indexes.longitudeIndex)) { location.setLongitude(((double) cursor.getInt(indexes.longitudeIndex)) / 1E6); } @@ -1024,56 +937,33 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils { } } - @Override - public void fillLocation(Cursor cursor, Location location) { - fillLocation(cursor, new CachedTrackPointsIndexes(cursor), location); - } - - @Override - public Location createLocation(Cursor cursor) { - Location location = new MyTracksLocation(""); - fillLocation(cursor, location); - return location; + private Location findTrackPointBy(String selection, String[] selectionArgs) { + Cursor cursor = null; + try { + cursor = getTrackPointCursor(null, selection, selectionArgs, TrackPointsColumns._ID); + if (cursor != null && cursor.moveToNext()) { + return createTrackPoint(cursor); + } + } finally { + if (cursor != null) { + cursor.close(); + } + } + return null; } /** - * Creates the {@link ContentValues} for a {@link Location}. + * Gets a track point cursor. * - * @param location the location - * @param trackId the track id + * @param projection the projection + * @param selection the selection + * @param selectionArgs the selection arguments + * @param sortOrder the sort order */ - private ContentValues createContentValues(Location location, long trackId) { - ContentValues values = new ContentValues(); - values.put(TrackPointsColumns.TRACKID, trackId); - values.put(TrackPointsColumns.LONGITUDE, (int) (location.getLongitude() * 1E6)); - values.put(TrackPointsColumns.LATITUDE, (int) (location.getLatitude() * 1E6)); - - // Hack for Samsung phones that don't properly populate the time field - long time = location.getTime(); - if (time == 0) { - time = System.currentTimeMillis(); - } - values.put(TrackPointsColumns.TIME, time); - if (location.hasAltitude()) { - values.put(TrackPointsColumns.ALTITUDE, location.getAltitude()); - } - if (location.hasAccuracy()) { - values.put(TrackPointsColumns.ACCURACY, location.getAccuracy()); - } - if (location.hasSpeed()) { - values.put(TrackPointsColumns.SPEED, location.getSpeed()); - } - if (location.hasBearing()) { - values.put(TrackPointsColumns.BEARING, location.getBearing()); - } - - if (location instanceof MyTracksLocation) { - MyTracksLocation myTracksLocation = (MyTracksLocation) location; - if (myTracksLocation.getSensorDataSet() != null) { - values.put(TrackPointsColumns.SENSOR, myTracksLocation.getSensorDataSet().toByteArray()); - } - } - return values; + private Cursor getTrackPointCursor( + String[] projection, String selection, String[] selectionArgs, String sortOrder) { + return contentResolver.query( + TrackPointsColumns.CONTENT_URI, projection, selection, selectionArgs, sortOrder); } /** diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImplTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImplTest.java index c3e9b4ba6..51afeec2f 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImplTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/content/MyTracksProviderUtilsImplTest.java @@ -47,7 +47,6 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { private MyTracksProviderUtils providerUtils; private static final String NAME_PREFIX = "test name"; - private static final String TRACK_CATEGORY = "test category"; private static final String MOCK_DESC = "Mock Next Waypoint Desc!"; private static final String TEST_DESC = "Test Desc!"; private static final String TEST_DESC_NEW = "Test Desc new!"; @@ -128,7 +127,8 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { long lastPointId = initializeTrack(trackId, numPoints); ((MyTracksProviderUtilsImpl) providerUtils).setDefaultCursorBatchSize(batchSize); List locations = new ArrayList(numPoints); - LocationIterator it = providerUtils.getLocationIterator(trackId, -1, descending, locationFactory); + LocationIterator it = providerUtils.getTrackPointLocationIterator( + trackId, -1, descending, locationFactory); try { while (it.hasNext()) { Location loc = it.next(); @@ -163,12 +163,12 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { loc.setAltitude(i * 2.5); locations[i] = loc; } - providerUtils.bulkInsertTrackPoints(locations, numPoints, id); + providerUtils.bulkInsertTrackPoint(locations, numPoints, id); // Load all inserted locations. long lastPointId = -1; int counter = 0; - LocationIterator it = providerUtils.getLocationIterator(id, -1, false, + LocationIterator it = providerUtils.getTrackPointLocationIterator(id, -1, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); try { while (it.hasNext()) { @@ -188,69 +188,36 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { } /** - * Tests the method {@link MyTracksProviderUtilsImpl#getAllTracks()} + * Tests the method {@link MyTracksProviderUtilsImpl#createTrack(Cursor)}. */ - public void testGetAllTracks() { - int initialTrackNumber = providerUtils.getAllTracks().size(); + @UsesMocks(Cursor.class) + public void testCreateTrack() { + Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); + int startColumnIndex = 1; + int columnIndex = startColumnIndex; + AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns._ID)) + .andReturn(columnIndex++); + AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).andReturn( + columnIndex++); + columnIndex = startColumnIndex; + // Id + AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + // Name + AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); long trackId = System.currentTimeMillis(); - providerUtils.insertTrack(getTrack(trackId, 0)); - List allTracks = providerUtils.getAllTracks(); - assertEquals(initialTrackNumber + 1, allTracks.size()); - assertEquals(trackId, allTracks.get(allTracks.size() - 1).getId()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getTrack(long)} - */ - public void testGetTrack() { - long trackId = System.currentTimeMillis(); - providerUtils.insertTrack(getTrack(trackId, 0)); - assertNotNull(providerUtils.getTrack(trackId)); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrack()} - */ - public void testGetLastTrack() { - long trackId = System.currentTimeMillis(); - providerUtils.insertTrack(getTrack(trackId, 0)); - assertEquals(trackId, providerUtils.getLastTrack().getId()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackId()} - */ - public void testGetLastTrackId() { - long trackId = System.currentTimeMillis(); - providerUtils.insertTrack(getTrack(trackId, 0)); - assertEquals(trackId, providerUtils.getLastTrackId()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#trackExists(long)} - */ - public void testTrackExists() { - long trackId = System.currentTimeMillis(); - providerUtils.insertTrack(getTrack(trackId, 0)); - assertTrue(providerUtils.trackExists(trackId)); + columnIndex = startColumnIndex; + // Id + AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); + // Name + String name = NAME_PREFIX + Long.toString(trackId); + AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); + AndroidMock.replay(cursorMock); + Track track = providerUtils.createTrack(cursorMock); + assertEquals(trackId, track.getId()); + assertEquals(name, track.getName()); + AndroidMock.verify(cursorMock); } - /** - * Tests the method {@link MyTracksProviderUtilsImpl#updateTrack(Track)} - */ - public void testUpdateTrack() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 0); - String nameOld = "name1"; - String nameNew = "name2"; - track.setName(nameOld); - providerUtils.insertTrack(track); - assertEquals(nameOld, providerUtils.getTrack(trackId).getName()); - track.setName(nameNew); - providerUtils.updateTrack(track); - assertEquals(nameNew, providerUtils.getTrack(trackId).getName()); - } - /** * Tests the method {@link MyTracksProviderUtilsImpl#deleteAllTracks()} */ @@ -284,7 +251,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { null, WaypointsColumns._ID); assertEquals(0, waypointCursor.getCount()); } - + /** * Tests the method {@link MyTracksProviderUtilsImpl#deleteTrack(long)}. */ @@ -324,387 +291,51 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { null, WaypointsColumns._ID); assertEquals(0, waypointCursor.getCount()); } - + /** - * Tests the method {@link MyTracksProviderUtilsImpl#createTrack(Cursor)}. + * Tests the method {@link MyTracksProviderUtilsImpl#getAllTracks()} */ - @UsesMocks(Cursor.class) - public void testCreateTrack() { - Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); - int startColumnIndex = 1; - int columnIndex = startColumnIndex; - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns._ID)) - .andReturn(columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TracksColumns.NAME)).andReturn( - columnIndex++); - columnIndex = startColumnIndex; - // Id - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); - // Name - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + public void testGetAllTracks() { + int initialTrackNumber = providerUtils.getAllTracks().size(); long trackId = System.currentTimeMillis(); - columnIndex = startColumnIndex; - // Id - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); - // Name - String name = NAME_PREFIX + Long.toString(trackId); - AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); - AndroidMock.replay(cursorMock); - Track track = providerUtils.createTrack(cursorMock); - assertEquals(trackId, track.getId()); - assertEquals(name, track.getName()); - AndroidMock.verify(cursorMock); + providerUtils.insertTrack(getTrack(trackId, 0)); + List allTracks = providerUtils.getAllTracks(); + assertEquals(initialTrackNumber + 1, allTracks.size()); + assertEquals(trackId, allTracks.get(allTracks.size() - 1).getId()); } /** - * Tests the method {@link MyTracksProviderUtilsImpl#createContentValues(Track)}. + * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrack()} */ - @UsesMocks(TripStatistics.class) - public void testCreateContentValues_track() { - // ID + public void testGetLastTrack() { long trackId = System.currentTimeMillis(); - // Name - String name = NAME_PREFIX + Long.toString(trackId); - Track track = getTrack(trackId, 10); - track.setName(name); - track.setCategory(TRACK_CATEGORY); - TripStatistics tripStatistics = AndroidMock.createNiceMock(TripStatistics.class); - // Bottom - int bottom = 22; - // AverageSpeed - double averageSpeed = 1.11; - AndroidMock.expect(tripStatistics.getBottom()).andReturn(bottom); - AndroidMock.expect(tripStatistics.getAverageSpeed()).andReturn(averageSpeed); - track.setTripStatistics(tripStatistics); - AndroidMock.replay(tripStatistics); - - ContentValues contentValues = providerUtils.createContentValues(track); - assertEquals(trackId, contentValues.get(TracksColumns._ID)); - assertEquals(name, contentValues.get(TracksColumns.NAME)); - assertEquals(bottom, contentValues.get(TracksColumns.MINLAT)); - assertEquals(averageSpeed, contentValues.get(TracksColumns.AVGSPEED)); - AndroidMock.verify(tripStatistics); + providerUtils.insertTrack(getTrack(trackId, 0)); + assertEquals(trackId, providerUtils.getLastTrack().getId()); } /** - * Tests the method {@link MyTracksProviderUtilsImpl#getFirstWaypoint(long)}. + * Tests the method {@link MyTracksProviderUtilsImpl#getTrack(long)} */ - public void testGetFirstWaypoint() { + public void testGetTrack() { long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setDescription("Desc1"); - waypoint1.setTrackId(trackId); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setDescription("Desc2"); - waypoint2.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - - assertNull(providerUtils.getFirstWaypoint(-1)); - Waypoint wayPoint = providerUtils.getFirstWaypoint(trackId); - assertEquals("Desc1", wayPoint.getDescription()); + providerUtils.insertTrack(getTrack(trackId, 0)); + assertNotNull(providerUtils.getTrack(trackId)); } /** - * Tests the method {@link MyTracksProviderUtilsImpl#getFirstWaypointId(long)}. + * Tests the method {@link MyTracksProviderUtilsImpl#updateTrack(Track)} */ - public void testGetFirstWaypointId() { + public void testUpdateTrack() { long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); + Track track = getTrack(trackId, 0); + String nameOld = "name1"; + String nameNew = "name2"; + track.setName(nameOld); providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setTrackId(trackId); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - - assertEquals(-1L, providerUtils.getFirstWaypointId(-1)); - assertEquals(1L, providerUtils.getFirstWaypointId(trackId)); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastWaypointId(long)}. - */ - public void testGetLastWaypointId() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setTrackId(trackId); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setTrackId(trackId); - Waypoint waypoint3 = new Waypoint(); - waypoint3.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - providerUtils.insertWaypoint(waypoint3); - - assertEquals(-1L, providerUtils.getLastWaypointId(-1)); - assertEquals(3L, providerUtils.getLastWaypointId(trackId)); - } - - /** - * Tests the method - * {@link MyTracksProviderUtils#getLastStatisticsWaypoint(long)}. - */ - public void testGetLastStatisticsWaypoint() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setTrackId(trackId); - waypoint1.setType(Waypoint.TYPE_STATISTICS); - waypoint1.setDescription("Desc1"); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setTrackId(trackId); - waypoint2.setType(Waypoint.TYPE_STATISTICS); - waypoint2.setDescription("Desc2"); - Waypoint waypoint3 = new Waypoint(); - waypoint3.setTrackId(trackId); - waypoint3.setType(Waypoint.TYPE_WAYPOINT); - waypoint3.setDescription("Desc3"); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - providerUtils.insertWaypoint(waypoint3); - - assertEquals("Desc2", providerUtils.getLastStatisticsWaypoint(trackId).getDescription()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getNextMarkerNumber(long, boolean)}. - */ - public void testGetNextMarkerNumber() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setType(Waypoint.TYPE_STATISTICS); - waypoint1.setTrackId(trackId); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setType(Waypoint.TYPE_WAYPOINT); - waypoint2.setTrackId(trackId); - Waypoint waypoint3 = new Waypoint(); - waypoint3.setType(Waypoint.TYPE_STATISTICS); - waypoint3.setTrackId(trackId); - Waypoint waypoint4 = new Waypoint(); - waypoint4.setType(Waypoint.TYPE_WAYPOINT); - waypoint4.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - providerUtils.insertWaypoint(waypoint3); - providerUtils.insertWaypoint(waypoint4); - - assertEquals(2, providerUtils.getNextMarkerNumber(trackId, true)); - assertEquals(3, providerUtils.getNextMarkerNumber(trackId, false)); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getNextStatisticsWaypointAfter(Waypoint)}. - */ - public void testGetNextStatisticsWaypointAfter() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint1 = new Waypoint(); - waypoint1.setType(Waypoint.TYPE_STATISTICS); - waypoint1.setTrackId(trackId); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setType(Waypoint.TYPE_WAYPOINT); - waypoint2.setTrackId(trackId); - Waypoint waypoint3 = new Waypoint(); - waypoint3.setType(Waypoint.TYPE_STATISTICS); - waypoint3.setTrackId(trackId); - waypoint3.setDescription("Desc3"); - Waypoint waypoint4 = new Waypoint(); - waypoint4.setType(Waypoint.TYPE_STATISTICS); - waypoint4.setTrackId(trackId); - waypoint4.setDescription("Desc4"); - providerUtils.insertWaypoint(waypoint1); - providerUtils.insertWaypoint(waypoint2); - providerUtils.insertWaypoint(waypoint3); - providerUtils.insertWaypoint(waypoint4); - - assertEquals("Desc3", providerUtils.getNextStatisticsWaypointAfter(providerUtils.getFirstWaypoint(trackId)).getDescription()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#insertWaypoint(Waypoint)} and - * {@link MyTracksProviderUtilsImpl#getWaypoint(long)}. - */ - public void testInsertAndGetWaypoint() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - Waypoint waypoint = new Waypoint(); - waypoint.setDescription(TEST_DESC); - waypoint.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint); - - assertEquals(TEST_DESC, providerUtils.getWaypoint(1).getDescription()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#updateWaypoint(Waypoint)}. - */ - public void testUpdateWaypoint() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - // Insert at first. - Waypoint waypoint = new Waypoint(); - waypoint.setDescription(TEST_DESC); - waypoint.setTrackId(trackId); - providerUtils.insertWaypoint(waypoint); - // Update - waypoint = providerUtils.getWaypoint(1); - waypoint.setDescription(TEST_DESC_NEW); - providerUtils.updateWaypoint(waypoint); - - assertEquals(TEST_DESC_NEW, providerUtils.getWaypoint(1).getDescription()); - } - - /** - * Tests the method - * {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)} - * when there is only one waypoint in the track. - */ - public void testDeleteWaypoint_onlyOneWayPoint() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - // Insert at first. - Waypoint waypoint1 = new Waypoint(); - waypoint1.setDescription(TEST_DESC); - waypoint1.setTrackId(trackId); - waypoint1.setType(Waypoint.TYPE_STATISTICS); - providerUtils.insertWaypoint(waypoint1); - - // Delete - DescriptionGenerator descriptionGenerator = new DescriptionGenerator() { - - @Override - public String generateWaypointDescription(TripStatistics tripStatistics) { - return MyTracksProviderUtilsImplTest.MOCK_DESC; - } - - @SuppressWarnings("hiding") - @Override - public String generateTrackDescription(Track track, Vector distances, - Vector elevations, boolean html) { - return null; - } - }; - providerUtils.deleteWaypoint(1, descriptionGenerator); - - assertNull(providerUtils.getWaypoint(1)); - } - - /** - * Tests the method - * {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)} - * when there is more than one waypoint in the track. - */ - public void testDeleteWaypoint_hasNextWayPoint() { - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - providerUtils.insertTrack(track); - - TripStatistics statistics = new TripStatistics(); - statistics.setStartTime(1000L); - statistics.setStopTime(2500L); - statistics.setTotalTime(1500L); - statistics.setMovingTime(700L); - statistics.setTotalDistance(750.0); - statistics.setTotalElevationGain(50.0); - statistics.setMaxSpeed(60.0); - statistics.setMaxElevation(1250.0); - statistics.setMinElevation(1200.0); - statistics.setMaxGrade(15.0); - statistics.setMinGrade(-25.0); - statistics.setBounds(-10000, 20000, 30000, -40000); - // Insert at first. - Waypoint waypoint1 = new Waypoint(); - waypoint1.setDescription(Long.toString(trackId)); - waypoint1.setTrackId(trackId); - waypoint1.setType(Waypoint.TYPE_STATISTICS); - waypoint1.setTripStatistics(statistics); - providerUtils.insertWaypoint(waypoint1); - Waypoint waypoint2 = new Waypoint(); - waypoint2.setDescription(Long.toString(trackId)); - waypoint2.setTrackId(trackId); - waypoint2.setType(Waypoint.TYPE_STATISTICS); - waypoint2.setTripStatistics(statistics); - providerUtils.insertWaypoint(waypoint2); - - // Delete - DescriptionGenerator descriptionGenerator = new DescriptionGenerator() { - @Override - public String generateWaypointDescription(TripStatistics tripStatistics) { - return MyTracksProviderUtilsImplTest.MOCK_DESC; - } - - @SuppressWarnings("hiding") - @Override - public String generateTrackDescription(Track track, Vector distances, - Vector elevations, boolean html) { - return null; - } - }; - providerUtils.deleteWaypoint(1, descriptionGenerator); - - assertNull(providerUtils.getWaypoint(1)); - assertEquals(MyTracksProviderUtilsImplTest.MOCK_DESC, providerUtils.getWaypoint(2) - .getDescription()); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#createWaypoint(Cursor)}. - */ - @UsesMocks(Cursor.class) - public void testCreateWaypoint() { - Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); - int startColumnIndex = 1; - int columnIndex = startColumnIndex; - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns._ID)) - .andReturn(columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.NAME)).andReturn( - columnIndex++); - AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.TRACKID)).andReturn( - columnIndex++); - columnIndex = startColumnIndex; - // Id - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); - // Name - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); - // trackIdIndex - AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); - long id = System.currentTimeMillis(); - columnIndex = startColumnIndex; - // Id - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(id); - // Name - String name = NAME_PREFIX + Long.toString(id); - AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); - // trackIdIndex - long trackId = 11L; - AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); - AndroidMock.replay(cursorMock); - Waypoint waypoint = providerUtils.createWaypoint(cursorMock); - assertEquals(id, waypoint.getId()); - assertEquals(name, waypoint.getName()); - assertEquals(trackId, waypoint.getTrackId()); - AndroidMock.verify(cursorMock); + assertEquals(nameOld, providerUtils.getTrack(trackId).getName()); + track.setName(nameNew); + providerUtils.updateTrack(track); + assertEquals(nameNew, providerUtils.getTrack(trackId).getName()); } /** @@ -744,7 +375,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { loc.setAltitude(2.5); waypoint.setLocation(loc); providerUtils.insertWaypoint(waypoint); - + MyTracksProviderUtilsImpl myTracksProviderUtilsImpl = new MyTracksProviderUtilsImpl( new MockContentResolver()); @@ -757,187 +388,272 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { assertEquals(startTime, contentValues.get(WaypointsColumns.STARTTIME)); assertEquals(minGrade, contentValues.get(WaypointsColumns.MINGRADE)); } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getFirstLocation()}. - */ - public void testGetFirstLocation() { - // Insert track, points at first. - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - Location firstLocation = providerUtils.getFirstLocation(); - checkLocation(0, firstLocation); - } - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastLocation()}. + * Tests the method {@link MyTracksProviderUtilsImpl#createWaypoint(Cursor)}. */ - public void testGetLastLocation() { - // Insert track, points at first. - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - Location lastLocation = providerUtils.getLastLocation(); - checkLocation(9, lastLocation); + @UsesMocks(Cursor.class) + public void testCreateWaypoint() { + Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); + int startColumnIndex = 1; + int columnIndex = startColumnIndex; + AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns._ID)) + .andReturn(columnIndex++); + AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.NAME)).andReturn( + columnIndex++); + AndroidMock.expect(cursorMock.getColumnIndexOrThrow(WaypointsColumns.TRACKID)).andReturn( + columnIndex++); + columnIndex = startColumnIndex; + // Id + AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + // Name + AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + // trackIdIndex + AndroidMock.expect(cursorMock.isNull(columnIndex++)).andReturn(false); + long id = System.currentTimeMillis(); + columnIndex = startColumnIndex; + // Id + AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(id); + // Name + String name = NAME_PREFIX + Long.toString(id); + AndroidMock.expect(cursorMock.getString(columnIndex++)).andReturn(name); + // trackIdIndex + long trackId = 11L; + AndroidMock.expect(cursorMock.getLong(columnIndex++)).andReturn(trackId); + AndroidMock.replay(cursorMock); + Waypoint waypoint = providerUtils.createWaypoint(cursorMock); + assertEquals(id, waypoint.getId()); + assertEquals(name, waypoint.getName()); + assertEquals(trackId, waypoint.getTrackId()); + AndroidMock.verify(cursorMock); } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLocation(long)}. - */ - public void testGetLocation() { - // Insert track, points at first. - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - Location location1 = providerUtils.getLocation(1L); - checkLocation(0, location1); - Location location5 = providerUtils.getLocation(5L); - checkLocation(4, location5); - Location location10 = providerUtils.getLocation(10L); - checkLocation(9, location10); - } - /** * Tests the method - * {@link MyTracksProviderUtilsImpl#getLocationsCursor(long, long, int, boolean)} - * in descending. + * {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)} + * when there is only one waypoint in the track. */ - public void testGetLocationCursor_desc() { - // Insert track, points at first. + public void testDeleteWaypoint_onlyOneWayPoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - Cursor cursor = providerUtils.getLocationsCursor(trackId, 2L, 5, true); - assertEquals(2, cursor.getCount()); - } + providerUtils.insertTrack(track); + // Insert at first. + Waypoint waypoint1 = new Waypoint(); + waypoint1.setDescription(TEST_DESC); + waypoint1.setTrackId(trackId); + waypoint1.setType(Waypoint.TYPE_STATISTICS); + providerUtils.insertWaypoint(waypoint1); + + // Delete + DescriptionGenerator descriptionGenerator = new DescriptionGenerator() { + + @Override + public String generateWaypointDescription(TripStatistics tripStatistics) { + return MyTracksProviderUtilsImplTest.MOCK_DESC; + } + + @SuppressWarnings("hiding") + @Override + public String generateTrackDescription(Track track, Vector distances, + Vector elevations, boolean html) { + return null; + } + }; + providerUtils.deleteWaypoint(1, descriptionGenerator); + + assertNull(providerUtils.getWaypoint(1)); + } + /** * Tests the method - * {@link MyTracksProviderUtilsImpl#getLocationsCursor(long, long, int, boolean)} - * in ascending. + * {@link MyTracksProviderUtilsImpl#deleteWaypoint(long, DescriptionGenerator)} + * when there is more than one waypoint in the track. */ - public void testGetLocationCursor_asc() { - // Insert track, points at first. + public void testDeleteWaypoint_hasNextWayPoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - Cursor cursor = providerUtils.getLocationsCursor(trackId, 2L, 5, false); - assertEquals(5, cursor.getCount()); - } + providerUtils.insertTrack(track); - /** - * Tests the method - * {@link MyTracksProviderUtilsImpl#getLocationIterator(long, long, boolean, LocationFactory)} - * in descending. - */ - public void testGeLocationIterator_desc() { - // Insert track, points at first. - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - long startTrackPointId = 2L; - - LocationIterator locationIterator = providerUtils.getLocationIterator(trackId, - startTrackPointId, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); - for (int i = 1; i >= 0; i--) { - assertTrue(locationIterator.hasNext()); - Location location = locationIterator.next(); - assertEquals(2 + (i - 1), locationIterator.getLocationId()); - checkLocation(i, location); - } - assertFalse(locationIterator.hasNext()); - } + TripStatistics statistics = new TripStatistics(); + statistics.setStartTime(1000L); + statistics.setStopTime(2500L); + statistics.setTotalTime(1500L); + statistics.setMovingTime(700L); + statistics.setTotalDistance(750.0); + statistics.setTotalElevationGain(50.0); + statistics.setMaxSpeed(60.0); + statistics.setMaxElevation(1250.0); + statistics.setMinElevation(1200.0); + statistics.setMaxGrade(15.0); + statistics.setMinGrade(-25.0); + statistics.setBounds(-10000, 20000, 30000, -40000); + // Insert at first. + Waypoint waypoint1 = new Waypoint(); + waypoint1.setDescription(Long.toString(trackId)); + waypoint1.setTrackId(trackId); + waypoint1.setType(Waypoint.TYPE_STATISTICS); + waypoint1.setTripStatistics(statistics); + providerUtils.insertWaypoint(waypoint1); + Waypoint waypoint2 = new Waypoint(); + waypoint2.setDescription(Long.toString(trackId)); + waypoint2.setTrackId(trackId); + waypoint2.setType(Waypoint.TYPE_STATISTICS); + waypoint2.setTripStatistics(statistics); + providerUtils.insertWaypoint(waypoint2); + // Delete + DescriptionGenerator descriptionGenerator = new DescriptionGenerator() { + @Override + public String generateWaypointDescription(TripStatistics tripStatistics) { + return MyTracksProviderUtilsImplTest.MOCK_DESC; + } + + @SuppressWarnings("hiding") + @Override + public String generateTrackDescription(Track track, Vector distances, + Vector elevations, boolean html) { + return null; + } + }; + providerUtils.deleteWaypoint(1, descriptionGenerator); + + assertNull(providerUtils.getWaypoint(1)); + assertEquals(MyTracksProviderUtilsImplTest.MOCK_DESC, providerUtils.getWaypoint(2) + .getDescription()); + } + /** - * Tests the method - * {@link MyTracksProviderUtilsImpl#getLocationIterator(long, long, boolean, LocationFactory)} - * in ascending. + * Tests the method {@link MyTracksProviderUtilsImpl#getFirstWaypointId(long)}. */ - public void testGeLocationIterator_asc() { - // Insert track, point at first. + public void testGetFirstWaypointId() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - long startTrackPointId = 2L; - - LocationIterator locationIterator = providerUtils.getLocationIterator(trackId, - startTrackPointId, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); + providerUtils.insertTrack(track); - for (int i = 1; i < 10; i++) { - assertTrue(locationIterator.hasNext()); - Location location = locationIterator.next(); - assertEquals(2 + (i - 1), locationIterator.getLocationId()); - checkLocation(i, location); - } - assertFalse(locationIterator.hasNext()); + Waypoint waypoint1 = new Waypoint(); + waypoint1.setTrackId(trackId); + Waypoint waypoint2 = new Waypoint(); + waypoint2.setTrackId(trackId); + providerUtils.insertWaypoint(waypoint1); + providerUtils.insertWaypoint(waypoint2); + + assertEquals(-1L, providerUtils.getFirstWaypointId(-1)); + assertEquals(1L, providerUtils.getFirstWaypointId(trackId)); } /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackLocationId(long)}. + * Tests the method {@link MyTracksProviderUtilsImpl#getNextWaypointNumber(long, boolean)}. */ - public void testGetLastTrackLocationId() { - // Insert track, point at first. + public void testGetNextWaypointNumber() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - - assertEquals(10, providerUtils.getLastTrackLocationId(trackId)); - } - - /** - * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackLocation(long)}. - */ - public void testGetLastTrackLocation() { - // Insert track, point at first. - long trackId = System.currentTimeMillis(); - Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); - checkLocation(9, providerUtils.getLastTrackLocation(trackId)); + providerUtils.insertTrack(track); + + Waypoint waypoint1 = new Waypoint(); + waypoint1.setType(Waypoint.TYPE_STATISTICS); + waypoint1.setTrackId(trackId); + Waypoint waypoint2 = new Waypoint(); + waypoint2.setType(Waypoint.TYPE_WAYPOINT); + waypoint2.setTrackId(trackId); + Waypoint waypoint3 = new Waypoint(); + waypoint3.setType(Waypoint.TYPE_STATISTICS); + waypoint3.setTrackId(trackId); + Waypoint waypoint4 = new Waypoint(); + waypoint4.setType(Waypoint.TYPE_WAYPOINT); + waypoint4.setTrackId(trackId); + providerUtils.insertWaypoint(waypoint1); + providerUtils.insertWaypoint(waypoint2); + providerUtils.insertWaypoint(waypoint3); + providerUtils.insertWaypoint(waypoint4); + + assertEquals(2, providerUtils.getNextWaypointNumber(trackId, true)); + assertEquals(3, providerUtils.getNextWaypointNumber(trackId, false)); } /** * Tests the method - * {@link MyTracksProviderUtilsImpl#insertTrackPoint(Location, long)}. This - * test also covers the method - * {@link MyTracksProviderUtilsImpl#createContentValues(Location, long)}. + * {@link MyTracksProviderUtils#getLastStatisticsWaypoint(long)}. */ - @SuppressWarnings("javadoc") - public void testInsertTrackPoint() { - // Insert track, point at first. + public void testGetLastStatisticsWaypoint() { long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); - insertTrackWithLocations(track); + providerUtils.insertTrack(track); - providerUtils.insertTrackPoint(createLocation(22), trackId); - assertEquals(11, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount()); + Waypoint waypoint1 = new Waypoint(); + waypoint1.setTrackId(trackId); + waypoint1.setType(Waypoint.TYPE_STATISTICS); + waypoint1.setDescription("Desc1"); + Waypoint waypoint2 = new Waypoint(); + waypoint2.setTrackId(trackId); + waypoint2.setType(Waypoint.TYPE_STATISTICS); + waypoint2.setDescription("Desc2"); + Waypoint waypoint3 = new Waypoint(); + waypoint3.setTrackId(trackId); + waypoint3.setType(Waypoint.TYPE_WAYPOINT); + waypoint3.setDescription("Desc3"); + providerUtils.insertWaypoint(waypoint1); + providerUtils.insertWaypoint(waypoint2); + providerUtils.insertWaypoint(waypoint3); + + assertEquals("Desc2", providerUtils.getLastStatisticsWaypoint(trackId).getDescription()); } + /** + * Tests the method {@link MyTracksProviderUtilsImpl#insertWaypoint(Waypoint)} and + * {@link MyTracksProviderUtilsImpl#getWaypoint(long)}. + */ + public void testInsertAndGetWaypoint() { + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + providerUtils.insertTrack(track); + + Waypoint waypoint = new Waypoint(); + waypoint.setDescription(TEST_DESC); + waypoint.setTrackId(trackId); + providerUtils.insertWaypoint(waypoint); + + assertEquals(TEST_DESC, providerUtils.getWaypoint(1).getDescription()); + } + + /** + * Tests the method {@link MyTracksProviderUtilsImpl#updateWaypoint(Waypoint)}. + */ + public void testUpdateWaypoint() { + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + providerUtils.insertTrack(track); + // Insert at first. + Waypoint waypoint = new Waypoint(); + waypoint.setDescription(TEST_DESC); + waypoint.setTrackId(trackId); + providerUtils.insertWaypoint(waypoint); + // Update + waypoint = providerUtils.getWaypoint(1); + waypoint.setDescription(TEST_DESC_NEW); + providerUtils.updateWaypoint(waypoint); + + assertEquals(TEST_DESC_NEW, providerUtils.getWaypoint(1).getDescription()); + } + /** * Tests the method - * {@link MyTracksProviderUtilsImpl#bulkInsertTrackPoints(Location[], int, long)} + * {@link MyTracksProviderUtilsImpl#bulkInsertTrackPoint(Location[], int, long)} * . This test also covers the method * {@link MyTracksProviderUtilsImpl#createContentValues(Location, long)} and * the inner class {@link MyTracksProviderUtilsImpl.CachedTrackPointsIndexes}. */ @SuppressWarnings("javadoc") - public void testBulkInsertTrackPoints() { + public void testBulkInsertTrackPoint() { // Insert track, point at first. long trackId = System.currentTimeMillis(); Track track = getTrack(trackId, 10); insertTrackWithLocations(track); - - providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), -1, trackId); - assertEquals(20, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount()); - providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), 8, trackId); - assertEquals(28, providerUtils.getLocationsCursor(trackId, 0, 1000, false).getCount()); + + providerUtils.bulkInsertTrackPoint(track.getLocations().toArray(new Location[0]), -1, trackId); + assertEquals(20, providerUtils.getTrackPointCursor(trackId, 0, 1000, false).getCount()); + providerUtils.bulkInsertTrackPoint(track.getLocations().toArray(new Location[0]), 8, trackId); + assertEquals(28, providerUtils.getTrackPointCursor(trackId, 0, 1000, false).getCount()); } /** @@ -950,9 +666,9 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { */ @SuppressWarnings("javadoc") @UsesMocks(Cursor.class) - public void testCreateLocation() { + public void testCreateTrackPoint() { Cursor cursorMock = AndroidMock.createNiceMock(Cursor.class); - + // Set index. int index = 1; // Id @@ -972,7 +688,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { // Sensor AndroidMock.expect(cursorMock.getColumnIndexOrThrow(TrackPointsColumns.SENSOR)).andReturn( index++); - + // Set return value of isNull(). index = 2; // Longitude @@ -985,7 +701,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); // Sensor AndroidMock.expect(cursorMock.isNull(index++)).andReturn(false); - + // Set return value of isNull(). index = 2; // Longitude @@ -1003,9 +719,9 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { // Sensor byte[] sensor = "Sensor state".getBytes(); AndroidMock.expect(cursorMock.getBlob(index++)).andReturn(sensor); - + AndroidMock.replay(cursorMock); - Location location = providerUtils.createLocation(cursorMock); + Location location = providerUtils.createTrackPoint(cursorMock); assertEquals((double) longitude, location.getLongitude()); assertEquals((double) latitude, location.getLatitude()); assertEquals(time, location.getTime()); @@ -1013,6 +729,127 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { AndroidMock.verify(cursorMock); } + /** + * Tests the method + * {@link MyTracksProviderUtilsImpl#insertTrackPoint(Location, long)}. This + * test also covers the method + * {@link MyTracksProviderUtilsImpl#createContentValues(Location, long)}. + */ + @SuppressWarnings("javadoc") + public void testInsertTrackPoint() { + // Insert track, point at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + providerUtils.insertTrackPoint(createLocation(22), trackId); + assertEquals(11, providerUtils.getTrackPointCursor(trackId, 0, 1000, false).getCount()); + } + + /** + * Tests the method {@link MyTracksProviderUtilsImpl#getLastTrackPointId(long)}. + */ + public void testGetLastTrackPointId() { + // Insert track, point at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + assertEquals(10, providerUtils.getLastTrackPointId(trackId)); + } + + /** + * Tests the method {@link MyTracksProviderUtilsImpl#getLastValidTrackPoint(long)}. + */ + public void testGetLastValidTrackPoint() { + // Insert track, points at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + Location lastLocation = providerUtils.getLastValidTrackPoint(trackId); + checkLocation(9, lastLocation); + } + + /** + * Tests the method + * {@link MyTracksProviderUtilsImpl#getTrackPointCursor(long, long, int, boolean)} + * in descending. + */ + public void testGetTrackPointCursor_desc() { + // Insert track, points at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + Cursor cursor = providerUtils.getTrackPointCursor(trackId, 2L, 5, true); + assertEquals(2, cursor.getCount()); + } + + /** + * Tests the method + * {@link MyTracksProviderUtilsImpl#getTrackPointCursor(long, long, int, boolean)} + * in ascending. + */ + public void testGetTrackPointCursor_asc() { + // Insert track, points at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + Cursor cursor = providerUtils.getTrackPointCursor(trackId, 2L, 5, false); + assertEquals(5, cursor.getCount()); + } + + /** + * Tests the method + * {@link MyTracksProviderUtilsImpl#getTrackPointLocationIterator(long, long, boolean, LocationFactory)} + * in descending. + */ + public void testGetTrackPointLocationIterator_desc() { + // Insert track, points at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + long startTrackPointId = 2L; + + LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, + startTrackPointId, true, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); + for (int i = 1; i >= 0; i--) { + assertTrue(locationIterator.hasNext()); + Location location = locationIterator.next(); + assertEquals(2 + (i - 1), locationIterator.getLocationId()); + checkLocation(i, location); + } + assertFalse(locationIterator.hasNext()); + } + + /** + * Tests the method + * {@link MyTracksProviderUtilsImpl#getTrackPointLocationIterator(long, long, boolean, LocationFactory)} + * in ascending. + */ + public void testGetTrackPointLocationIterator_asc() { + // Insert track, point at first. + long trackId = System.currentTimeMillis(); + Track track = getTrack(trackId, 10); + insertTrackWithLocations(track); + + long startTrackPointId = 2L; + + LocationIterator locationIterator = providerUtils.getTrackPointLocationIterator(trackId, + startTrackPointId, false, MyTracksProviderUtils.DEFAULT_LOCATION_FACTORY); + + for (int i = 1; i < 10; i++) { + assertTrue(locationIterator.hasNext()); + Location location = locationIterator.next(); + assertEquals(2 + (i - 1), locationIterator.getLocationId()); + checkLocation(i, location); + } + assertFalse(locationIterator.hasNext()); + } + /** * Simulates a track which is used for testing. * @@ -1067,7 +904,7 @@ public class MyTracksProviderUtilsImplTest extends AndroidTestCase { */ private void insertTrackWithLocations(Track track) { providerUtils.insertTrack(track); - providerUtils.bulkInsertTrackPoints(track.getLocations().toArray(new Location[0]), track + providerUtils.bulkInsertTrackPoint(track.getLocations().toArray(new Location[0]), track .getLocations().size(), track.getId()); } } diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java index 02c22558d..14da06dde 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/content/TrackDataHubTest.java @@ -203,7 +203,7 @@ public class TrackDataHubTest extends AndroidTestCase { // Register two listeners Capture contentObserverCapture = new Capture(); - expect(myTracksProviderUtils.getWaypointsCursor( + expect(myTracksProviderUtils.getWaypointCursor( eq(TRACK_ID), AndroidMock.leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(2)); expect(myTracksProviderUtils.createWaypoint(isA(Cursor.class))) @@ -230,7 +230,7 @@ public class TrackDataHubTest extends AndroidTestCase { // Cause waypoints table update ContentObserver contentObserver = contentObserverCapture.getValue(); - expect(myTracksProviderUtils.getWaypointsCursor( + expect(myTracksProviderUtils.getWaypointCursor( eq(TRACK_ID), AndroidMock.leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(3)); expect(myTracksProviderUtils.createWaypoint(isA(Cursor.class))) @@ -251,7 +251,7 @@ public class TrackDataHubTest extends AndroidTestCase { verifyAndReset(); // Unregister one listener - expect(myTracksProviderUtils.getWaypointsCursor( + expect(myTracksProviderUtils.getWaypointCursor( eq(TRACK_ID), AndroidMock.leq(0L), eq(Constants.MAX_DISPLAYED_WAYPOINTS_POINTS))) .andStubAnswer(new FixedSizeCursorAnswer(4)); expect(myTracksProviderUtils.createWaypoint(isA(Cursor.class))) @@ -288,9 +288,9 @@ public class TrackDataHubTest extends AndroidTestCase { eq(TrackPointsColumns.CONTENT_URI), capture(contentObserverCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); trackDataListener1.onNewTrackPointsDone(); @@ -303,9 +303,9 @@ public class TrackDataHubTest extends AndroidTestCase { // Register a second listener locationIterator = new FixedSizeLocationIterator(1, 10, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L); trackDataListener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener2); trackDataListener2.onNewTrackPointsDone(); @@ -318,9 +318,9 @@ public class TrackDataHubTest extends AndroidTestCase { // Deliver more points - should go to both listeners without clearing ContentObserver contentObserver = contentObserverCapture.getValue(); locationIterator = new FixedSizeLocationIterator(11, 10, 1); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(11L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(20L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(20L); locationIterator.expectLocationsDelivered(trackDataListener1); locationIterator.expectLocationsDelivered(trackDataListener2); trackDataListener1.onNewTrackPointsDone(); @@ -332,10 +332,10 @@ public class TrackDataHubTest extends AndroidTestCase { // Unregister one listener and change track locationIterator = new FixedSizeLocationIterator(101, 10); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID + 1)).andReturn(110L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID + 1)).andReturn(110L); trackDataListener2.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener2); trackDataListener2.onNewTrackPointsDone(); @@ -358,9 +358,9 @@ public class TrackDataHubTest extends AndroidTestCase { eq(TrackPointsColumns.CONTENT_URI), capture(contentObserverCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); @@ -384,9 +384,9 @@ public class TrackDataHubTest extends AndroidTestCase { dataSource.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), capture(contentObserverCapture)); locationIterator = new FixedSizeLocationIterator(1, 10, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); trackDataListener1.onNewTrackPointsDone(); @@ -409,9 +409,9 @@ public class TrackDataHubTest extends AndroidTestCase { eq(TrackPointsColumns.CONTENT_URI), capture(observerCapture)); FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); trackDataListener1.onNewTrackPointsDone(); @@ -434,10 +434,10 @@ public class TrackDataHubTest extends AndroidTestCase { dataSource.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), capture(observerCapture)); locationIterator = new FixedSizeLocationIterator(1, 10); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class))) .andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID + 1)).andReturn(10L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID + 1)).andReturn(10L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); trackDataListener1.onNewTrackPointsDone(); @@ -458,15 +458,15 @@ public class TrackDataHubTest extends AndroidTestCase { dataSource.registerContentObserver( eq(TrackPointsColumns.CONTENT_URI), capture(contentObserverCapture)); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(200L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(200L); AndroidMock.expectLastCall().anyTimes(); FixedSizeLocationIterator locationIterator1 = new FixedSizeLocationIterator( 1, 200, 4, 25, 71, 120); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator1); FixedSizeLocationIterator locationIterator2 = new FixedSizeLocationIterator( 1, 200, 4, 25, 71, 120); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator2); trackDataListener1.clearTrackPoints(); @@ -496,9 +496,9 @@ public class TrackDataHubTest extends AndroidTestCase { // Deliver 30 points (no sampling happens) FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 30, 5); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(30L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(30L); trackDataListener1.clearTrackPoints(); locationIterator.expectLocationsDelivered(trackDataListener1); @@ -513,9 +513,9 @@ public class TrackDataHubTest extends AndroidTestCase { // Now deliver 30 more (incrementally sampled) ContentObserver observer = observerCapture.getValue(); locationIterator = new FixedSizeLocationIterator(31, 30); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(31L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(60L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(60L); locationIterator.expectSampledLocationsDelivered(trackDataListener1, 2, false); trackDataListener1.onNewTrackPointsDone(); replay(); @@ -525,9 +525,9 @@ public class TrackDataHubTest extends AndroidTestCase { // Now another 30 (triggers resampling) locationIterator = new FixedSizeLocationIterator(1, 90); - expect(myTracksProviderUtils.getLocationIterator( + expect(myTracksProviderUtils.getTrackPointLocationIterator( eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator); - expect(myTracksProviderUtils.getLastTrackLocationId(TRACK_ID)).andReturn(90L); + expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(90L); trackDataListener1.clearTrackPoints(); locationIterator.expectSampledLocationsDelivered(trackDataListener1, 2, false); trackDataListener1.onNewTrackPointsDone(); @@ -840,7 +840,7 @@ public class TrackDataHubTest extends AndroidTestCase { dataSource.registerOnSharedPreferenceChangeListener(capture(preferenceChangeListenerCapture)); Capture observerCapture = new Capture(); dataSource.registerContentObserver(eq(WaypointsColumns.CONTENT_URI), capture(observerCapture)); - expect(myTracksProviderUtils.getWaypointsCursor(capture(new Capture()), capture(new Capture()), + expect(myTracksProviderUtils.getWaypointCursor(capture(new Capture()), capture(new Capture()), capture(new Capture()))).andReturn(null); trackDataListener1.clearWaypoints(); trackDataListener1.onNewWaypointsDone(); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java index 4bc725754..1eb7b2cd7 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/fragments/ChartFragmentTest.java @@ -41,7 +41,7 @@ public class ChartFragmentTest extends AndroidTestCase { protected void setUp() throws Exception { chartFragment = new ChartFragment(); chartFragment.setChartView(new ChartView(getContext())); - chartFragment.setTripStatisticsBuilder(TrackStubUtils.INITIAL_TIME); + chartFragment.setTripStatisticsUpdater(TrackStubUtils.INITIAL_TIME); } /** diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxImporterTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxImporterTest.java index 6bcd5b27d..6f21364bf 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxImporterTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/io/file/GpxImporterTest.java @@ -148,13 +148,13 @@ public class GpxImporterTest extends AndroidTestCase { expect(providerUtils.insertTrack(AndroidMock.capture(trackParam))) .andReturn(TRACK_ID_URI); - expect(providerUtils.getLastTrackLocationId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2); + expect(providerUtils.getLastTrackPointId(TRACK_ID)).andReturn(TRACK_POINT_ID_1).andReturn(TRACK_POINT_ID_2); // A flush happens after the first insertion to get the starting point ID, // which is why we get two calls - expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc1), + expect(providerUtils.bulkInsertTrackPoint(LocationsMatcher.eqLoc(loc1), eq(1), eq(TRACK_ID))).andReturn(1); - expect(providerUtils.bulkInsertTrackPoints(LocationsMatcher.eqLoc(loc2), + expect(providerUtils.bulkInsertTrackPoint(LocationsMatcher.eqLoc(loc2), eq(1), eq(TRACK_ID))).andReturn(1); providerUtils.updateTrack(AndroidMock.capture(trackParam)); @@ -223,9 +223,9 @@ public class GpxImporterTest extends AndroidTestCase { expect(providerUtils.insertTrack((Track) AndroidMock.anyObject())) .andReturn(TRACK_ID_URI); - expect(providerUtils.bulkInsertTrackPoints((Location[]) AndroidMock.anyObject(), + expect(providerUtils.bulkInsertTrackPoint((Location[]) AndroidMock.anyObject(), AndroidMock.anyInt(), AndroidMock.anyLong())).andStubReturn(1); - expect(providerUtils.getLastTrackLocationId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1); + expect(providerUtils.getLastTrackPointId(TRACK_ID)).andStubReturn(TRACK_POINT_ID_1); providerUtils.deleteTrack(TRACK_ID); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackWriterTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackWriterTest.java index 467221475..c855c6b35 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackWriterTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/io/file/TrackWriterTest.java @@ -256,7 +256,7 @@ public class TrackWriterTest extends AndroidTestCase { // Make location 3 invalid locs[2].setLatitude(100); - assertEquals(locs.length, providerUtils.bulkInsertTrackPoints(locs, locs.length, TRACK_ID)); + assertEquals(locs.length, providerUtils.bulkInsertTrackPoint(locs, locs.length, TRACK_ID)); for (int i = 0; i < wps.length; ++i) { Waypoint wpt = wps[i]; wpt.setTrackId(TRACK_ID); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTaskTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTaskTest.java index 904114791..61f35e6f3 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTaskTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/io/maps/SendMapsAsyncTaskTest.java @@ -144,7 +144,7 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { */ public void testUploadAllTrackPoints_nullCursor() { Track track = TrackStubUtils.createTrack(1); - AndroidMock.expect(myTracksProviderUtilsMock.getLocationsCursor(TRACK_ID, 0, -1, false)) + AndroidMock.expect(myTracksProviderUtilsMock.getTrackPointCursor(TRACK_ID, 0, -1, false)) .andReturn(null); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock); SendMapsAsyncTask sendMapsAsyncTask = new SendMapsAsyncTask(sendMapsActivityMock, @@ -164,9 +164,9 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { AndroidMock.expect(cursorMock.getCount()).andReturn(2); AndroidMock.expect(cursorMock.moveToPosition(0)).andReturn(true); cursorMock.close(); - AndroidMock.expect(myTracksProviderUtilsMock.createLocation(cursorMock)).andReturn( + AndroidMock.expect(myTracksProviderUtilsMock.createTrackPoint(cursorMock)).andReturn( new Location("1")); - AndroidMock.expect(myTracksProviderUtilsMock.getLocationsCursor(TRACK_ID, 0, -1, false)) + AndroidMock.expect(myTracksProviderUtilsMock.getTrackPointCursor(TRACK_ID, 0, -1, false)) .andReturn(cursorMock); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock, cursorMock); @@ -191,9 +191,9 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { AndroidMock.expect(cursorMock.moveToPosition(0)).andReturn(true); AndroidMock.expect(cursorMock.moveToPosition(1)).andReturn(true); cursorMock.close(); - AndroidMock.expect(myTracksProviderUtilsMock.createLocation(cursorMock)) + AndroidMock.expect(myTracksProviderUtilsMock.createTrackPoint(cursorMock)) .andReturn(new Location("1")).times(2); - AndroidMock.expect(myTracksProviderUtilsMock.getLocationsCursor(TRACK_ID, 0, -1, false)) + AndroidMock.expect(myTracksProviderUtilsMock.getTrackPointCursor(TRACK_ID, 0, -1, false)) .andReturn(cursorMock); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock, cursorMock); @@ -221,9 +221,9 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { AndroidMock.expect(cursorMock.moveToPosition(0)).andReturn(true); AndroidMock.expect(cursorMock.moveToPosition(1)).andReturn(true); cursorMock.close(); - AndroidMock.expect(myTracksProviderUtilsMock.createLocation(cursorMock)) + AndroidMock.expect(myTracksProviderUtilsMock.createTrackPoint(cursorMock)) .andReturn(new Location("1")).times(2); - AndroidMock.expect(myTracksProviderUtilsMock.getLocationsCursor(TRACK_ID, 0, -1, false)) + AndroidMock.expect(myTracksProviderUtilsMock.getTrackPointCursor(TRACK_ID, 0, -1, false)) .andReturn(cursorMock); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock, cursorMock); @@ -250,9 +250,9 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { AndroidMock.expect(cursorMock.moveToPosition(0)).andReturn(true); AndroidMock.expect(cursorMock.moveToPosition(1)).andReturn(true); cursorMock.close(); - AndroidMock.expect(myTracksProviderUtilsMock.createLocation(cursorMock)) + AndroidMock.expect(myTracksProviderUtilsMock.createTrackPoint(cursorMock)) .andReturn(new Location("1")).times(2); - AndroidMock.expect(myTracksProviderUtilsMock.getLocationsCursor(TRACK_ID, 0, -1, false)) + AndroidMock.expect(myTracksProviderUtilsMock.getTrackPointCursor(TRACK_ID, 0, -1, false)) .andReturn(cursorMock); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock, cursorMock); @@ -274,7 +274,7 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { @UsesMocks(Cursor.class) public void testUploadWaypoints_nullCursor() { AndroidMock.expect( - myTracksProviderUtilsMock.getWaypointsCursor(TRACK_ID, 0, + myTracksProviderUtilsMock.getWaypointCursor(TRACK_ID, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS)).andReturn(null); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock); SendMapsAsyncTask sendMapsAsyncTask = new SendMapsAsyncTask(sendMapsActivityMock, @@ -296,7 +296,7 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { cursorMock.close(); AndroidMock.expect( - myTracksProviderUtilsMock.getWaypointsCursor(TRACK_ID, 0, + myTracksProviderUtilsMock.getWaypointCursor(TRACK_ID, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS)).andReturn(cursorMock); AndroidMock.replay(sendMapsActivityMock, myTracksProviderUtilsMock, cursorMock); @@ -323,7 +323,7 @@ public class SendMapsAsyncTaskTest extends AndroidTestCase { cursorMock.close(); AndroidMock.expect( - myTracksProviderUtilsMock.getWaypointsCursor(TRACK_ID, 0, + myTracksProviderUtilsMock.getWaypointCursor(TRACK_ID, 0, Constants.MAX_LOADED_WAYPOINTS_POINTS)).andReturn(cursorMock); Waypoint waypoint = new Waypoint(); waypoint.setLocation(TrackStubUtils.createMyTracksLocation()); diff --git a/MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilderTest.java b/MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdaterTest.java similarity index 67% rename from MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilderTest.java rename to MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdaterTest.java index 5e13c4182..70d755e29 100644 --- a/MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsBuilderTest.java +++ b/MyTracksTest/src/com/google/android/apps/mytracks/stats/TripStatisticsUpdaterTest.java @@ -10,28 +10,28 @@ import android.location.Location; import junit.framework.TestCase; /** - * Tests {@link TripStatisticsBuilder}. + * Tests {@link TripStatisticsUpdater}. * * @author Sandor Dornbush */ -public class TripStatisticsBuilderTest extends TestCase { +public class TripStatisticsUpdaterTest extends TestCase { private static final long ONE_SECOND = 1000; private static final long TEN_SECONDS = 10 * ONE_SECOND; - private TripStatisticsBuilder tripStatisticsBuilder = null; + private TripStatisticsUpdater tripStatisticsUpdater = null; @Override protected void setUp() throws Exception { - tripStatisticsBuilder = new TripStatisticsBuilder(System.currentTimeMillis()); + tripStatisticsUpdater = new TripStatisticsUpdater(System.currentTimeMillis()); } public void testAddLocationSimple() throws Exception { long startTime = 1000; - tripStatisticsBuilder = new TripStatisticsBuilder(startTime); - TripStatistics tripStatistics = tripStatisticsBuilder.getTripStatistics(); + tripStatisticsUpdater = new TripStatisticsUpdater(startTime); + TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics(); - assertEquals(0.0, tripStatisticsBuilder.getSmoothedElevation()); + assertEquals(0.0, tripStatisticsUpdater.getSmoothedElevation()); assertEquals(Double.POSITIVE_INFINITY, tripStatistics.getMinElevation()); assertEquals(Double.NEGATIVE_INFINITY, tripStatistics.getMaxElevation()); assertEquals(0.0, tripStatistics.getMaxSpeed()); @@ -57,12 +57,12 @@ public class TripStatisticsBuilderTest extends TestCase { // Each time slice is 10 seconds. location.setTime(startTime + i * TEN_SECONDS); - tripStatisticsBuilder.addLocation(location, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); + tripStatisticsUpdater.addLocation(location, PreferencesUtils.MIN_RECORDING_DISTANCE_DEFAULT); - tripStatistics = tripStatisticsBuilder.getTripStatistics(); + tripStatistics = tripStatisticsUpdater.getTripStatistics(); assertEquals(i * TEN_SECONDS, tripStatistics.getTotalTime()); assertEquals(i * TEN_SECONDS, tripStatistics.getMovingTime()); - assertEquals(i, tripStatisticsBuilder.getSmoothedElevation(), + assertEquals(i, tripStatisticsUpdater.getSmoothedElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(0.0, tripStatistics.getMinElevation()); assertEquals(i, tripStatistics.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); @@ -81,17 +81,17 @@ public class TripStatisticsBuilderTest extends TestCase { } /** - * Tests {@link TripStatisticsBuilder#updateElevation(double)} with constant + * Tests {@link TripStatisticsUpdater#updateElevation(double)} with constant * elevations. */ public void testElevationSimple() throws Exception { for (double elevation = 0; elevation < 1000; elevation += 10) { - tripStatisticsBuilder = new TripStatisticsBuilder(System.currentTimeMillis()); + tripStatisticsUpdater = new TripStatisticsUpdater(System.currentTimeMillis()); for (int i = 0; i < 100; i++) { - assertEquals(0.0, tripStatisticsBuilder.updateElevation(elevation)); - assertEquals(elevation, tripStatisticsBuilder.getSmoothedElevation()); + assertEquals(0.0, tripStatisticsUpdater.updateElevation(elevation)); + assertEquals(elevation, tripStatisticsUpdater.getSmoothedElevation()); - TripStatistics tripStatistics = tripStatisticsBuilder.getTripStatistics(); + TripStatistics tripStatistics = tripStatisticsUpdater.getTripStatistics(); assertEquals(elevation, tripStatistics.getMinElevation()); assertEquals(elevation, tripStatistics.getMaxElevation()); assertEquals(0.0, tripStatistics.getTotalElevationGain()); @@ -100,7 +100,7 @@ public class TripStatisticsBuilderTest extends TestCase { } /** - * Tests {@link TripStatisticsBuilder#updateGrade(double, double)} with + * Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with * elevation gain. */ public void testElevationGain() throws Exception { @@ -113,11 +113,11 @@ public class TripStatisticsBuilderTest extends TestCase { } else { expectedGain = 1.0; } - assertEquals(expectedGain, tripStatisticsBuilder.updateElevation(i)); - assertEquals(i, tripStatisticsBuilder.getSmoothedElevation(), + assertEquals(expectedGain, tripStatisticsUpdater.updateElevation(i)); + assertEquals(i, tripStatisticsUpdater.getSmoothedElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); - TripStatistics data = tripStatisticsBuilder.getTripStatistics(); + TripStatistics data = tripStatisticsUpdater.getTripStatistics(); assertEquals(0.0, data.getMinElevation()); assertEquals(i, data.getMaxElevation(), Constants.ELEVATION_SMOOTHING_FACTOR / 2); assertEquals(i, data.getTotalElevationGain(), Constants.ELEVATION_SMOOTHING_FACTOR); @@ -125,7 +125,7 @@ public class TripStatisticsBuilderTest extends TestCase { } /** - * Tests {@link TripStatisticsBuilder#updateGrade(double, double)} with grade + * Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with grade * of 1 and -1. */ public void testGradeSimple() throws Exception { @@ -134,11 +134,11 @@ public class TripStatisticsBuilderTest extends TestCase { * The value of the elevation does not matter. This is just to fill the * elevation buffer. */ - tripStatisticsBuilder.updateElevation(i); - tripStatisticsBuilder.updateGrade(100, 100); + tripStatisticsUpdater.updateElevation(i); + tripStatisticsUpdater.updateGrade(100, 100); if (i >= Constants.GRADE_SMOOTHING_FACTOR && i >= Constants.ELEVATION_SMOOTHING_FACTOR) { - assertEquals(1.0, tripStatisticsBuilder.getTripStatistics().getMaxGrade()); - assertEquals(1.0, tripStatisticsBuilder.getTripStatistics().getMinGrade()); + assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMaxGrade()); + assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMinGrade()); } } for (double i = 0; i < 1000; i++) { @@ -146,17 +146,17 @@ public class TripStatisticsBuilderTest extends TestCase { * The value of the elevation does not matter. This is just to fill the * elevation buffer. */ - tripStatisticsBuilder.updateElevation(i); - tripStatisticsBuilder.updateGrade(100, -100); + tripStatisticsUpdater.updateElevation(i); + tripStatisticsUpdater.updateGrade(100, -100); if (i >= Constants.GRADE_SMOOTHING_FACTOR && i >= Constants.ELEVATION_SMOOTHING_FACTOR) { - assertEquals(1.0, tripStatisticsBuilder.getTripStatistics().getMaxGrade()); - assertEquals(-1.0, tripStatisticsBuilder.getTripStatistics().getMinGrade()); + assertEquals(1.0, tripStatisticsUpdater.getTripStatistics().getMaxGrade()); + assertEquals(-1.0, tripStatisticsUpdater.getTripStatistics().getMinGrade()); } } } /** - * Tests {@link TripStatisticsBuilder#updateGrade(double, double)} with + * Tests {@link TripStatisticsUpdater#updateGrade(double, double)} with * distance of 1. The grade should get ignored. */ public void testGradeIgnoreShort() throws Exception { @@ -165,56 +165,56 @@ public class TripStatisticsBuilderTest extends TestCase { * The value of the elevation does not matter. This is just to fill the * elevation buffer. */ - tripStatisticsBuilder.updateElevation(i); - tripStatisticsBuilder.updateGrade(1, 100); + tripStatisticsUpdater.updateElevation(i); + tripStatisticsUpdater.updateGrade(1, 100); assertEquals( - Double.NEGATIVE_INFINITY, tripStatisticsBuilder.getTripStatistics().getMaxGrade()); + Double.NEGATIVE_INFINITY, tripStatisticsUpdater.getTripStatistics().getMaxGrade()); assertEquals( - Double.POSITIVE_INFINITY, tripStatisticsBuilder.getTripStatistics().getMinGrade()); + Double.POSITIVE_INFINITY, tripStatisticsUpdater.getTripStatistics().getMinGrade()); } } /** - * Tests {@link TripStatisticsBuilder#updateSpeed(long, double, long, double)} + * Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)} * with speed of zero. */ public void testUpdateSpeedIncludeZero() { for (int i = 0; i < 1000; i++) { - tripStatisticsBuilder.updateSpeed(i + ONE_SECOND, 0.0, i, 4.0); - assertEquals(0.0, tripStatisticsBuilder.getTripStatistics().getMaxSpeed()); + tripStatisticsUpdater.updateSpeed(i + ONE_SECOND, 0.0, i, 4.0); + assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed()); } } /** - * Tests {@link TripStatisticsBuilder#updateSpeed(long, double, long, double)} + * Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)} * with the error code 128. The speed should get ignored. */ public void testUpdateSpeedIngoreErrorCode() { long time = 12344000; - tripStatisticsBuilder.updateSpeed(time + ONE_SECOND, 128.0, time, 0.0); - assertEquals(0.0, tripStatisticsBuilder.getTripStatistics().getMaxSpeed()); + tripStatisticsUpdater.updateSpeed(time + ONE_SECOND, 128.0, time, 0.0); + assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed()); } /** - * Tests {@link TripStatisticsBuilder#updateSpeed(long, double, long, double)} + * Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)} * with a large speed change. The speed should get ignored. */ public void testUpdateSpeedIngoreLargeAcceleration() { long time = 12344000; - tripStatisticsBuilder.updateSpeed(time + ONE_SECOND, 100.0, time, 1.0); - assertEquals(0.0, tripStatisticsBuilder.getTripStatistics().getMaxSpeed()); + tripStatisticsUpdater.updateSpeed(time + ONE_SECOND, 100.0, time, 1.0); + assertEquals(0.0, tripStatisticsUpdater.getTripStatistics().getMaxSpeed()); } /** - * Tests {@link TripStatisticsBuilder#updateSpeed(long, double, long, double)} + * Tests {@link TripStatisticsUpdater#updateSpeed(long, double, long, double)} * with constant speed. */ public void testUpdateSpeed() { double speed = 4.0; for (int i = 0; i < 1000; i++) { - tripStatisticsBuilder.updateSpeed(i + ONE_SECOND, speed, i, speed); + tripStatisticsUpdater.updateSpeed(i + ONE_SECOND, speed, i, speed); if (i >= Constants.SPEED_SMOOTHING_FACTOR) { - assertEquals(speed, tripStatisticsBuilder.getTripStatistics().getMaxSpeed()); + assertEquals(speed, tripStatisticsUpdater.getTripStatistics().getMaxSpeed()); } } }