Code cleanup using static code analysis (Android Studio).

This commit is contained in:
Dennis Guse
2019-07-02 23:44:11 +02:00
parent 5b71810763
commit 71d625e43e
61 changed files with 278 additions and 524 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
<project version="4">
<component name="NullableNotNullManager">
<option name="myDefaultNullable" value="android.support.annotation.Nullable" />
<option name="myDefaultNotNull" value="android.support.annotation.NonNull" />
<option name="myDefaultNotNull" value="androidx.annotation.NonNull" />
<option name="myNullables">
<value>
<list size="10">
+3 -3
View File
@@ -25,7 +25,7 @@ dependencies {
androidTestCompile files('libs/AndroidMockGenerator.jar')
androidTestCompile files('libs/robotium-solo-5.0.1.jar')
implementation 'com.google.android.gms:play-services-location:11.8.0'
implementation 'com.google.android.gms:play-services:11.8.0'
implementation 'com.google.android.gms:play-services-auth:11.8.0'
implementation 'com.google.android.gms:play-services-location:17.0.0'
implementation 'com.google.android.gms:play-services:12.0.1'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
}
@@ -36,7 +36,6 @@ import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.util.ArrayList;
@@ -108,7 +107,7 @@ public abstract class AbstractSendToGoogleActivity extends AbstractMyTracksActiv
*/
private int[] getCheckedPositions(ListView list) {
SparseBooleanArray positions = list.getCheckedItemPositions();
ArrayList<Integer> arrayList = new ArrayList<Integer>();
ArrayList<Integer> arrayList = new ArrayList<>();
for (int i = 0; i < positions.size(); i++) {
int key = positions.keyAt(i);
if (positions.valueAt(i)) {
@@ -173,8 +173,7 @@ public class ChartValueSeries {
* @param max the max value
*/
private int getInterval(double min, double max) {
for (int i = 0; i < intervalValues.length; i++) {
int intervalValue = intervalValues[i];
for (int intervalValue : intervalValues) {
int minValue = getMinMarkerValue(min, intervalValue);
double targetInterval = (max - minValue) / ChartView.Y_AXIS_INTERVALS;
if (intervalValue >= targetInterval) {
@@ -82,8 +82,8 @@ public class ChartView extends View {
private static final int Y_AXIS_OFFSET = 16;
private final ChartValueSeries[] series = new ChartValueSeries[NUM_SERIES];
private final ArrayList<double[]> chartData = new ArrayList<double[]>();
private final ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>();
private final ArrayList<double[]> chartData = new ArrayList<>();
private final ArrayList<Waypoint> waypoints = new ArrayList<>();
private final ExtremityMonitor xExtremityMonitor = new ExtremityMonitor();
private double maxX = 1.0;
@@ -686,7 +686,7 @@ public class ChartView extends View {
* Gets the x axis marker positions.
*/
private ArrayList<Double> getXAxisMarkerPositions(double interval) {
ArrayList<Double> markers = new ArrayList<Double>();
ArrayList<Double> markers = new ArrayList<>();
markers.add(0d);
for (int i = 1; i * interval < maxX; i++) {
markers.add(i * interval);
@@ -20,7 +20,6 @@ import android.content.Context;
import android.os.AsyncTask;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.util.UnitConversions;
/**
@@ -59,12 +59,10 @@ public class MarkerDetailActivity extends AbstractMyTracksActivity implements De
MyTracksProviderUtils myTracksProviderUtils = MyTracksProviderUtils.Factory.get(this);
waypoint = myTracksProviderUtils.getWaypoint(markerId);
markerIds = new ArrayList<Long>();
markerIds = new ArrayList<>();
int markerIndex = -1;
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getWaypointCursor(waypoint.getTrackId(), -1L, -1);
try (Cursor cursor = myTracksProviderUtils.getWaypointCursor(waypoint.getTrackId(), -1L, -1)) {
if (cursor != null && cursor.moveToFirst()) {
/*
* Yes, this will skip the first waypoint and that is intentional as the
@@ -79,10 +77,6 @@ public class MarkerDetailActivity extends AbstractMyTracksActivity implements De
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
ViewPager viewPager = findViewById(R.id.maker_detail_activity_view_pager);
@@ -17,12 +17,10 @@
package com.google.android.apps.mytracks;
import com.google.android.apps.mytracks.content.MyTracksProviderUtils;
import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.content.Waypoint;
import com.google.android.apps.mytracks.content.Waypoint.WaypointType;
import com.google.android.apps.mytracks.content.WaypointCreationRequest;
import com.google.android.apps.mytracks.services.TrackRecordingServiceConnection;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtils;
import com.google.android.maps.mytracks.R;
@@ -437,10 +437,10 @@ public class SearchListActivity extends AbstractSendToGoogleActivity implements
*/
private List<Map<String, Object>> prepareResultsforDisplay(
Collection<ScoredResult> scoredResults) {
ArrayList<Map<String, Object>> output = new ArrayList<Map<String, Object>>(
ArrayList<Map<String, Object>> output = new ArrayList<>(
scoredResults.size());
for (ScoredResult result : scoredResults) {
Map<String, Object> resultMap = new HashMap<String, Object>();
Map<String, Object> resultMap = new HashMap<>();
if (result.track != null) {
prepareTrackForDisplay(result.track, resultMap);
} else {
@@ -50,7 +50,7 @@ public class TabsAdapter extends FragmentPagerAdapter
private final Context context;
private final TabHost tabHost;
private final ViewPager viewPager;
private final ArrayList<TabInfo> tabInfos = new ArrayList<TabInfo>();
private final ArrayList<TabInfo> tabInfos = new ArrayList<>();
/**
* An object to hold a tab's info.
@@ -495,7 +495,6 @@ public class TrackDetailActivity extends AbstractSendToGoogleActivity
}
}
finish();
return;
}
}
@@ -26,7 +26,6 @@ import com.google.android.apps.mytracks.util.TrackRecordingServiceConnectionUtil
import com.google.android.apps.mytracks.util.TrackUtils;
import com.google.android.maps.mytracks.R;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
@@ -53,8 +52,6 @@ public class TrackEditActivity extends AbstractMyTracksActivity implements Choos
private static final String TAG = TrackEditActivity.class.getSimpleName();
private static final String ICON_VALUE_KEY = "icon_value_key";
private static final int DRIVE_REQUEST_CODE = 0;
private Long trackId;
private TrackRecordingServiceConnection trackRecordingServiceConnection;
private MyTracksProviderUtils myTracksProviderUtils;
@@ -624,7 +624,6 @@ public class TrackListActivity extends AbstractSendToGoogleActivity implements F
});
if (dialog != null) {
dialog.show();
return;
}
}
}
@@ -276,7 +276,7 @@ public class MyTracksProvider extends ContentProvider {
if (initialValues == null) {
initialValues = new ContentValues();
}
Uri result = null;
Uri result;
try {
db.beginTransaction();
result = insertContentValues(url, getUrlType(url), initialValues);
@@ -293,7 +293,7 @@ public class MyTracksProvider extends ContentProvider {
if (!canAccess()) {
return 0;
}
int numInserted = 0;
int numInserted;
try {
// Use a transaction in order to make the insertions run as a single batch
db.beginTransaction();
@@ -161,9 +161,9 @@ public class SearchEngine {
* @return a set of results, sorted according to their score
*/
public SortedSet<ScoredResult> search(SearchQuery query) {
ArrayList<Track> tracks = new ArrayList<Track>();
ArrayList<Waypoint> waypoints = new ArrayList<Waypoint>();
TreeSet<ScoredResult> scoredResults = new TreeSet<ScoredResult>(SCORED_RESULT_COMPARATOR);
ArrayList<Track> tracks = new ArrayList<>();
ArrayList<Waypoint> waypoints = new ArrayList<>();
TreeSet<ScoredResult> scoredResults = new TreeSet<>(SCORED_RESULT_COMPARATOR);
retrieveTracks(query, tracks);
retrieveWaypoints(query, waypoints);
@@ -187,20 +187,14 @@ public class SearchEngine {
queryLikeSelection,
queryLikeSelection };
Cursor cursor = null;
try {
cursor = providerUtils.getTrackCursor(
TRACK_SELECTION_QUERY, trackSelectionArgs, TRACK_SELECTION_ORDER);
try (Cursor cursor = providerUtils.getTrackCursor(
TRACK_SELECTION_QUERY, trackSelectionArgs, TRACK_SELECTION_ORDER)) {
if (cursor != null) {
tracks.ensureCapacity(cursor.getCount());
while (cursor.moveToNext()) {
tracks.add(providerUtils.createTrack(cursor));
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@@ -216,10 +210,8 @@ public class SearchEngine {
queryLikeSelection2,
queryLikeSelection2,
queryLikeSelection2 };
Cursor cursor = null;
try {
cursor = providerUtils.getWaypointCursor(WAYPOINT_SELECTION_QUERY, waypointSelectionArgs,
WAYPOINT_SELECTION_ORDER, MAX_SCORED_WAYPOINTS);
try (Cursor cursor = providerUtils.getWaypointCursor(WAYPOINT_SELECTION_QUERY, waypointSelectionArgs,
WAYPOINT_SELECTION_ORDER, MAX_SCORED_WAYPOINTS)) {
if (cursor != null) {
waypoints.ensureCapacity(cursor.getCount());
while (cursor.moveToNext()) {
@@ -229,10 +221,6 @@ public class SearchEngine {
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@@ -410,10 +410,9 @@ public class TrackDataHub implements DataSourceListener {
if (isOnlyListener) {
resetSamplingState();
}
Set<TrackDataListener> sampledInListeners = trackDataListeners;
Set<TrackDataListener> sampledOutListeners = hasSampledOut ? trackDataListeners
: Collections.<TrackDataListener> emptySet();
notifyTrackPointsTableUpdate(isOnlyListener, sampledInListeners, sampledOutListeners);
notifyTrackPointsTableUpdate(isOnlyListener, trackDataListeners, sampledOutListeners);
}
if (trackDataTypes.contains(TrackDataType.WAYPOINTS_TABLE)) {
@@ -452,10 +451,8 @@ public class TrackDataHub implements DataSourceListener {
trackDataListener.clearWaypoints();
}
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getWaypointCursor(
selectedTrackId, -1L, MAX_DISPLAYED_WAYPOINTS);
try (Cursor cursor = myTracksProviderUtils.getWaypointCursor(
selectedTrackId, -1L, MAX_DISPLAYED_WAYPOINTS)) {
if (cursor != null && cursor.moveToFirst()) {
do {
Waypoint waypoint = myTracksProviderUtils.createWaypoint(cursor);
@@ -467,10 +464,6 @@ public class TrackDataHub implements DataSourceListener {
}
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
for (TrackDataListener trackDataListener : trackDataListeners) {
@@ -37,11 +37,11 @@ public class TrackDataManager {
// Map of listener to its track data types
private final Map<TrackDataListener, EnumSet<TrackDataType>>
listenerToTypesMap = new HashMap<TrackDataListener, EnumSet<TrackDataType>>();
listenerToTypesMap = new HashMap<>();
// Map of track data type to listeners
private final Map<TrackDataType, Set<TrackDataListener>>
typeToListenersMap = new EnumMap<TrackDataType, Set<TrackDataListener>>(TrackDataType.class);
typeToListenersMap = new EnumMap<>(TrackDataType.class);
public TrackDataManager() {
for (TrackDataType trackDataType : TrackDataType.values()) {
@@ -58,7 +58,7 @@ public class ChartFragment extends Fragment implements TrackDataListener {
public static final String CHART_FRAGMENT_TAG = "chartFragment";
private final ArrayList<double[]> pendingPoints = new ArrayList<double[]>();
private final ArrayList<double[]> pendingPoints = new ArrayList<>();
private TrackDataHub trackDataHub;
@@ -147,7 +147,7 @@ public class ChooseActivityDialogFragment extends AbstractMyTracksDialogFragment
* Gets the display info.
*/
private List<DisplayInfo> getDisplayInfos(FragmentActivity fragmentActivity) {
List<DisplayInfo> displayInfos = new ArrayList<DisplayInfo>();
List<DisplayInfo> displayInfos = new ArrayList<>();
Intent intent = ShareCompat.IntentBuilder.from(fragmentActivity)
.setType(IntentUtils.TEXT_PLAIN_TYPE).getIntent();
List<ResolveInfo> resolveInfos = packageManager.queryIntentActivities(
@@ -244,7 +244,7 @@ public class ChooseActivityDialogFragment extends AbstractMyTracksDialogFragment
usePackageName = true;
} else {
// Use HashSet to track duplicates
HashSet<CharSequence> duplicates = new HashSet<CharSequence>();
HashSet<CharSequence> duplicates = new HashSet<>();
duplicates.add(appName);
for (int i = start + 1; i <= end; i++) {
ResolveInfo resolveInfo = resolveInfos.get(i);
@@ -103,7 +103,7 @@ public class ChooseActivityTypeDialogFragment extends DialogFragment {
final TextView weight = view.findViewById(R.id.choose_activity_type_weight);
List<Integer> imageIds = new ArrayList<Integer>();
List<Integer> imageIds = new ArrayList<>();
for (String iconValue : TrackIconUtils.getAllIconValues()) {
imageIds.add(TrackIconUtils.getIconDrawable(iconValue));
}
@@ -17,7 +17,6 @@
package com.google.android.apps.mytracks.fragments;
import com.google.android.apps.mytracks.util.DialogUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
@@ -66,14 +66,14 @@ public class FileTrackExporter implements TrackExporter {
try {
trackWriter.prepare(outputStream);
trackWriter.writeHeader(tracks);
for (int i = 0; i < tracks.length; i++) {
writeWaypoints(tracks[i]);
for (Track track1 : tracks) {
writeWaypoints(track1);
}
trackWriter.writeBeginTracks();
long startTime = tracks[0].getTripStatistics().getStartTime();
for (int i = 0; i < tracks.length; i++) {
long offset = tracks[i].getTripStatistics().getStartTime() - startTime;
writeLocations(tracks[i], offset);
for (Track track : tracks) {
long offset = track.getTripStatistics().getStartTime() - startTime;
writeLocations(track, offset);
}
trackWriter.writeEndTracks();
trackWriter.writeFooter();
@@ -95,10 +95,8 @@ public class FileTrackExporter implements TrackExporter {
* load them into objects all at the same time.
*/
boolean hasWaypoints = false;
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getWaypointCursor(
track.getId(), -1L, Constants.MAX_LOADED_WAYPOINTS_POINTS);
try (Cursor cursor = myTracksProviderUtils.getWaypointCursor(
track.getId(), -1L, Constants.MAX_LOADED_WAYPOINTS_POINTS)) {
if (cursor != null && cursor.moveToFirst()) {
/*
* Yes, this will skip the first waypoint and that is intentional as the
@@ -116,10 +114,6 @@ public class FileTrackExporter implements TrackExporter {
trackWriter.writeWaypoint(waypoint);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
if (hasWaypoints) {
trackWriter.writeEndWaypoints();
@@ -183,10 +177,6 @@ public class FileTrackExporter implements TrackExporter {
isLastLocationValid = isLocationValid;
}
if (wroteSegment) {
trackWriter.writeCloseSegment();
wroteSegment = false;
}
if (wroteTrack) {
Location lastValidTrackPoint = myTracksProviderUtils.getLastValidTrackPoint(track.getId());
setLocationTime(lastValidTrackPoint, offset);
@@ -75,9 +75,9 @@ public class KmlTrackWriter implements TrackWriter {
private final MyTracksProviderUtils myTracksProviderUtils;
private PrintWriter printWriter;
private ArrayList<Integer> powerList = new ArrayList<Integer>();
private ArrayList<Integer> cadenceList = new ArrayList<Integer>();
private ArrayList<Integer> heartRateList = new ArrayList<Integer>();
private ArrayList<Integer> powerList = new ArrayList<>();
private ArrayList<Integer> cadenceList = new ArrayList<>();
private ArrayList<Integer> heartRateList = new ArrayList<>();
private boolean hasPower;
private boolean hasCadence;
private boolean hasHeartRate;
@@ -406,30 +406,24 @@ public class KmlTrackWriter implements TrackWriter {
if (trackPointId == -1L) {
return location.getBearing();
}
Cursor cursor = null;
Location viewLocation;
try {
cursor = myTracksProviderUtils.getTrackPointCursor(trackId, trackPointId, 10, true);
try (Cursor cursor = myTracksProviderUtils.getTrackPointCursor(trackId, trackPointId, 10, true)) {
if (cursor == null || cursor.getCount() == 0) {
return location.getBearing();
}
cursor.moveToPosition(cursor.getCount() - 1);
viewLocation = myTracksProviderUtils.createTrackPoint(cursor);
} finally {
if (cursor != null) {
cursor.close();
}
}
return viewLocation.bearingTo(location);
}
private String getCoordinates(Location location, String separator) {
StringBuffer buffer = new StringBuffer();
buffer.append(location.getLongitude()).append(separator).append(location.getLatitude());
StringBuilder builder = new StringBuilder();
builder.append(location.getLongitude()).append(separator).append(location.getLatitude());
if (location.hasAltitude()) {
buffer.append(separator).append(location.getAltitude());
builder.append(separator).append(location.getAltitude());
}
return buffer.toString();
return builder.toString();
}
/**
@@ -111,9 +111,7 @@ public class KmzTrackExporter implements TrackExporter {
private void addImages(ZipOutputStream zipOutputStream) throws InterruptedException, IOException {
for (Track track : tracks) {
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getWaypointCursor(track.getId(), -1L, -1);
try (Cursor cursor = myTracksProviderUtils.getWaypointCursor(track.getId(), -1L, -1)) {
if (cursor != null && cursor.moveToFirst()) {
/*
* Yes, this will skip the first waypoint and that is intentional as
@@ -130,10 +128,6 @@ public class KmzTrackExporter implements TrackExporter {
}
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
@@ -181,18 +175,12 @@ public class KmzTrackExporter implements TrackExporter {
}
private void readFromFile(ZipOutputStream zipOutputStream, Uri uri) throws IOException {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(uri.getPath()));
try (FileInputStream fileInputStream = new FileInputStream(new File(uri.getPath()))) {
byte[] buffer = new byte[BUFFER_SIZE];
int byteCount;
while ((byteCount = fileInputStream.read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, byteCount);
}
} finally {
if (fileInputStream != null) {
fileInputStream.close();
}
}
}
}
@@ -240,9 +240,7 @@ public class SaveAsyncTask extends AsyncTask<Void, Integer, Boolean> {
* Saves all the tracks.
*/
private Boolean saveAllTracks() {
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getTrackCursor(null, null, TracksColumns._ID);
try (Cursor cursor = myTracksProviderUtils.getTrackCursor(null, null, TracksColumns._ID)) {
if (cursor == null) {
return false;
}
@@ -259,10 +257,6 @@ public class SaveAsyncTask extends AsyncTask<Void, Integer, Boolean> {
publishProgress(i + 1, totalCount);
}
return true;
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
@@ -148,8 +148,8 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
PreferencesUtils.RECORDING_DISTANCE_INTERVAL_DEFAULT);
this.weight = PreferencesUtils.getFloat(
context, R.string.weight_key, PreferencesUtils.getDefaultWeight(context));
trackIds = new ArrayList<Long>();
waypoints = new ArrayList<Waypoint>();
trackIds = new ArrayList<>();
waypoints = new ArrayList<>();
}
@Override
@@ -158,7 +158,7 @@ abstract class AbstractFileTrackImporter extends DefaultHandler implements Track
}
@Override
public void characters(char[] ch, int start, int length) throws SAXException {
public void characters(char[] ch, int start, int length) {
String newContent = new String(ch, start, length);
if (content == null) {
content = newContent;
@@ -65,51 +65,67 @@ public class GpxFileTrackImporter extends AbstractFileTrackImporter {
@Override
public void startElement(String uri, String localName, String tag, Attributes attributes)
throws SAXException {
if (tag.equals(TAG_WAYPOINT)) {
switch (tag) {
case TAG_WAYPOINT:
onWaypointStart(attributes);
} else if (tag.equals(TAG_TRACK)) {
break;
case TAG_TRACK:
onTrackStart();
} else if (tag.equals(TAG_TRACK_SEGMENT)) {
break;
case TAG_TRACK_SEGMENT:
onTrackSegmentStart();
} else if (tag.equals(TAG_TRACK_POINT)) {
break;
case TAG_TRACK_POINT:
onTrackPointStart(attributes);
break;
}
}
@Override
public void endElement(String uri, String localName, String tag) throws SAXException {
if (tag.equals(TAG_GPX)) {
switch (tag) {
case TAG_GPX:
onFileEnd();
} else if (tag.equals(TAG_WAYPOINT)) {
break;
case TAG_WAYPOINT:
onWaypointEnd();
} else if (tag.equals(TAG_TRACK)) {
break;
case TAG_TRACK:
onTrackEnd();
} else if (tag.equals(TAG_TRACK_POINT)) {
break;
case TAG_TRACK_POINT:
onTrackPointEnd();
} else if (tag.equals(TAG_NAME)) {
break;
case TAG_NAME:
if (content != null) {
name = content.trim();
}
} else if (tag.equals(TAG_DESCRIPTION)) {
break;
case TAG_DESCRIPTION:
if (content != null) {
description = content.trim();
}
} else if (tag.equals(TAG_TYPE)) {
break;
case TAG_TYPE:
if (content != null) {
category = content.trim();
}
} else if (tag.equals(TAG_TIME)) {
break;
case TAG_TIME:
if (content != null) {
time = content.trim();
}
} else if (tag.equals(TAG_ELEVATION)) {
break;
case TAG_ELEVATION:
if (content != null) {
altitude = content.trim();
}
} else if (tag.equals(TAG_COMMENT)) {
break;
case TAG_COMMENT:
if (content != null) {
waypointType = content.trim();
}
break;
}
// Reset element content
@@ -21,7 +21,6 @@ import com.google.android.apps.mytracks.io.file.TrackFileFormat;
import com.google.android.apps.mytracks.util.DialogUtils;
import com.google.android.apps.mytracks.util.FileUtils;
import com.google.android.apps.mytracks.util.IntentUtils;
import com.google.android.apps.mytracks.util.UriUtils;
import com.google.android.maps.mytracks.R;
import android.app.Activity;
@@ -108,7 +107,7 @@ public class ImportActivity extends Activity {
}
Uri data = intent.getData();
if (!UriUtils.isFileUri(data)) {
if ("file".equals(data.getScheme())) {
Log.d(TAG, "Invalid data: " + intent);
finish();
return;
@@ -214,7 +214,7 @@ public class ImportAsyncTask extends AsyncTask<Void, Integer, Boolean> {
* just the path file.
*/
private List<File> getFiles() {
List<File> files = new ArrayList<File>();
List<File> files = new ArrayList<>();
File file = new File(path);
if (importAll) {
File[] candidates = file.listFiles();
@@ -90,23 +90,29 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
@Override
public void startElement(String uri, String localName, String tag, Attributes attributes)
throws SAXException {
if (tag.equals(TAG_PLACEMARK) || tag.equals(TAG_PHOTO_OVERLAY)) {
switch (tag) {
case TAG_PLACEMARK:
case TAG_PHOTO_OVERLAY:
/*
* Note that a track is contained in a Placemark, calling onWaypointStart
* will clear various track variables like name, category, and
* description.
*/
onWaypointStart();
} else if (tag.equals(TAG_GX_MULTI_TRACK)) {
break;
case TAG_GX_MULTI_TRACK:
trackStarted = true;
onTrackStart();
} else if (tag.equals(TAG_GX_TRACK)) {
break;
case TAG_GX_TRACK:
if (!trackStarted) {
throw new SAXException("No " + TAG_GX_MULTI_TRACK);
}
onTrackSegmentStart();
} else if (tag.equals(TAG_GX_SIMPLE_ARRAY_DATA)) {
break;
case TAG_GX_SIMPLE_ARRAY_DATA:
onSensorDataStart(attributes);
break;
}
}
@@ -215,10 +221,10 @@ public class KmlFileTrackImporter extends AbstractFileTrackImporter {
@Override
protected void onTrackSegmentStart() {
super.onTrackSegmentStart();
locationList = new ArrayList<Location>();
powerList = new ArrayList<Integer>();
cadenceList = new ArrayList<Integer>();
heartRateList = new ArrayList<Integer>();
locationList = new ArrayList<>();
powerList = new ArrayList<>();
cadenceList = new ArrayList<>();
heartRateList = new ArrayList<>();
}
/**
@@ -152,19 +152,13 @@ public class KmzTrackImporter implements TrackImporter {
* @param zipInputStream the zip input stream
*/
private byte[] getKml(ZipInputStream zipInputStream) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byte[] buffer = new byte[BUFFER_SIZE];
int count;
while ((count = zipInputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, count);
}
return byteArrayOutputStream.toByteArray();
} finally {
if (byteArrayOutputStream != null) {
byteArrayOutputStream.close();
}
}
}
@@ -512,7 +512,6 @@ public class TrackRecordingService extends Service {
Log.i(TAG, "Stop resume track.");
updateRecordingState(PreferencesUtils.RECORDING_TRACK_ID_DEFAULT, true);
stopSelfResult(startId);
return;
}
}
}
@@ -1088,7 +1087,6 @@ public class TrackRecordingService extends Service {
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
startForegroundService(pendingIntent, R.string.track_record_notification);
}
return;
} else {
// Not recording
if (isGpsStarted) {
@@ -55,7 +55,7 @@ public class BluetoothSensorManager extends SensorManager {
}
// Get the default adapter from the main application thread
final ArrayList<BluetoothAdapter> adapters = new ArrayList<BluetoothAdapter>(1);
final ArrayList<BluetoothAdapter> adapters = new ArrayList<>(1);
final Object mutex = new Object();
Handler handler = new Handler(Looper.getMainLooper());
@@ -39,7 +39,7 @@ public class StrideReadings {
private final List<Integer> strideReadingsHistory;
public StrideReadings() {
strideReadingsHistory = new LinkedList<Integer>();
strideReadingsHistory = new LinkedList<>();
}
public void updateStrideReading(int numStrides) {
@@ -52,7 +52,7 @@ public class AnnouncementPeriodicTask implements PeriodicTask {
private static final String TAG = AnnouncementPeriodicTask.class.getSimpleName();
@VisibleForTesting
static final HashMap<String, String> SPEECH_PARAMS = new HashMap<String, String>();
static final HashMap<String, String> SPEECH_PARAMS = new HashMap<>();
static {
SPEECH_PARAMS.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "not_used");
}
@@ -295,14 +295,10 @@ public class AnnouncementPeriodicTask implements PeriodicTask {
if (parts[2] != 0) {
sb.append(hours);
sb.append(" ");
sb.append(minutes);
sb.append(" ");
sb.append(seconds);
} else {
sb.append(minutes);
sb.append(" ");
sb.append(seconds);
}
sb.append(minutes);
sb.append(" ");
sb.append(seconds);
return sb.toString();
}
@@ -48,7 +48,7 @@ public class BitmapLoader extends AsyncTask<Void, Void, Bitmap> {
ImageView imageView, Uri uri, int targetWidth, int targetHeight, boolean fitWithin) {
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference<ImageView>(imageView);
imageViewReference = new WeakReference<>(imageView);
this.uri = uri;
this.targetWidth = targetWidth;
this.targetHeight = targetHeight;
@@ -194,7 +194,7 @@ public class AdvancedSettingsActivity extends AbstractSettingsActivity {
Log.i(TAG, "Resetting all settings");
// Actually wipe preferences and save synchronously
sharedPreferences.edit().clear().commit();
sharedPreferences.edit().clear().apply();
// Give UI feedback in the UI thread
runOnUiThread(new Runnable() {
@@ -27,7 +27,6 @@ import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import java.util.ArrayList;
@@ -101,14 +100,12 @@ public class SensorSettingsActivity extends AbstractSettingsActivity {
getString(R.string.bluetooth_sensor_key));
String value = PreferencesUtils.getString(
this, R.string.bluetooth_sensor_key, PreferencesUtils.BLUETOOTH_SENSOR_DEFAULT);
List<String> optionsList = new ArrayList<String>();
List<String> valuesList = new ArrayList<String>();
List<String> optionsList = new ArrayList<>();
List<String> valuesList = new ArrayList<>();
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
BluetoothDeviceUtils.populateDeviceLists(bluetoothAdapter, optionsList, valuesList);
}
String[] options = optionsList.toArray(new String[optionsList.size()]);
String[] values = valuesList.toArray(new String[valuesList.size()]);
if (valuesList.size() == 1) {
if (!valuesList.get(0).equals(value)) {
@@ -121,6 +118,9 @@ public class SensorSettingsActivity extends AbstractSettingsActivity {
PreferencesUtils.setString(this, R.string.bluetooth_sensor_key, value);
}
}
String[] options = optionsList.toArray(new String[0]);
String[] values = valuesList.toArray(new String[0]);
configureListPreference(preference, options, options, values, value, null);
}
}
@@ -16,17 +16,12 @@
package com.google.android.apps.mytracks.settings;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import com.google.android.apps.mytracks.util.DialogUtils;
import com.google.android.apps.mytracks.util.IntentUtils;
import com.google.android.apps.mytracks.util.PreferencesUtils;
import com.google.android.maps.mytracks.R;
/**
@@ -120,14 +120,14 @@ public class DoubleBuffer {
@Override
public String toString() {
StringBuffer stringBuffer = new StringBuffer("Full: ");
stringBuffer.append(isFull);
stringBuffer.append("\n");
StringBuilder builder = new StringBuilder("Full: ");
builder.append(isFull);
builder.append("\n");
for (int i = 0; i < buffer.length; i++) {
stringBuffer.append((i == index) ? "<<" : "[");
stringBuffer.append(buffer[i]);
stringBuffer.append((i == index) ? ">> " : "] ");
builder.append((i == index) ? "<<" : "[");
builder.append(buffer[i]);
builder.append((i == index) ? ">> " : "] ");
}
return stringBuffer.toString();
return builder.toString();
}
}
@@ -74,11 +74,12 @@ public class CalorieUtils {
if (activityType == null || activityType.equals("")) {
return ActivityType.INVALID;
}
if (TrackIconUtils.getIconValue(context, activityType).equals(TrackIconUtils.WALK)) {
switch (TrackIconUtils.getIconValue(context, activityType)) {
case TrackIconUtils.WALK:
return ActivityType.WALKING;
} else if (TrackIconUtils.getIconValue(context, activityType).equals(TrackIconUtils.RUN)) {
case TrackIconUtils.RUN:
return ActivityType.RUNNING;
} else if (TrackIconUtils.getIconValue(context, activityType).equals(TrackIconUtils.BIKE)) {
case TrackIconUtils.BIKE:
return ActivityType.CYCLING;
}
return ActivityType.INVALID;
@@ -225,9 +226,7 @@ public class CalorieUtils {
private static void clearCalorie(MyTracksProviderUtils myTracksProviderUtils, Track track) {
track.getTripStatistics().setCalorie(0);
myTracksProviderUtils.updateTrack(track);
Cursor cursor = null;
try {
cursor = myTracksProviderUtils.getWaypointCursor(track.getId(), -1L, -1);
try (Cursor cursor = myTracksProviderUtils.getWaypointCursor(track.getId(), -1L, -1)) {
if (cursor != null && cursor.moveToFirst()) {
/*
* Yes, this will skip the first waypoint and that is intentional as the
@@ -240,10 +239,6 @@ public class CalorieUtils {
waypoint = getNextStatisticsWaypoint(myTracksProviderUtils, cursor);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@@ -155,20 +155,14 @@ public class GoogleLocationUtils {
*/
private static int getUseLocationForServices(Context context) {
ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = null;
String stringValue = null;
try {
cursor = contentResolver.query(GOOGLE_SETTINGS_CONTENT_URI, new String[] { VALUE },
NAME + "=?", new String[] { USE_LOCATION_FOR_SERVICES }, null);
try (Cursor cursor = contentResolver.query(GOOGLE_SETTINGS_CONTENT_URI, new String[]{VALUE},
NAME + "=?", new String[]{USE_LOCATION_FOR_SERVICES}, null)) {
if (cursor != null && cursor.moveToNext()) {
stringValue = cursor.getString(0);
}
} catch (RuntimeException e) {
Log.w(TAG, "Failed to get 'Use My Location' setting", e);
} finally {
if (cursor != null) {
cursor.close();
}
}
if (stringValue == null) {
return USE_LOCATION_FOR_SERVICES_NOT_SET;
@@ -22,7 +22,6 @@ import com.google.android.apps.mytracks.content.Track;
import com.google.android.apps.mytracks.io.file.TrackFileFormat;
import com.google.android.maps.mytracks.R;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
@@ -47,7 +46,7 @@ public class IntentUtils {
* @param context the context
* @param cls the class
*/
public static final Intent newIntent(Context context, Class<?> cls) {
public static Intent newIntent(Context context, Class<?> cls) {
return new Intent(context, cls).addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
}
@@ -60,7 +59,7 @@ public class IntentUtils {
* @param filePath the file path
* @param trackFileFormat the track file format
*/
public static final Intent newShareFileIntent(
public static Intent newShareFileIntent(
Context context, long trackId, String filePath, TrackFileFormat trackFileFormat) {
Track track = MyTracksProviderUtils.Factory.get(context).getTrack(trackId);
String trackDescription = track == null ? ""
@@ -178,23 +178,23 @@ public class ListItemUtils {
*/
private static String getOwnerTimeDistance(
String sharedOwner, String totalTime, String totalDistance) {
StringBuffer buffer = new StringBuffer();
StringBuilder builder = new StringBuilder();
if (sharedOwner != null && sharedOwner.length() != 0) {
buffer.append(sharedOwner);
builder.append(sharedOwner);
}
if (totalTime != null && totalTime.length() != 0) {
if (buffer.length() != 0) {
buffer.append(" \u2027 ");
if (builder.length() != 0) {
builder.append(" \u2027 ");
}
buffer.append(totalTime);
builder.append(totalTime);
}
if (totalDistance != null && totalDistance.length() != 0) {
if (buffer.length() != 0) {
buffer.append(" ");
if (builder.length() != 0) {
builder.append(" ");
}
buffer.append("(").append(totalDistance).append(")");
builder.append("(").append(totalDistance).append(")");
}
return buffer.toString();
return builder.toString();
}
/**
@@ -94,12 +94,12 @@ public class LocationUtils {
}
int idx;
int maxIdx = 0;
Stack<int[]> stack = new Stack<int[]>();
Stack<int[]> stack = new Stack<>();
double[] dists = new double[n];
dists[0] = 1;
dists[n - 1] = 1;
double maxDist;
double dist = 0.0;
double dist;
int[] current;
if (n > 2) {
@@ -146,7 +146,7 @@ public class LocationUtils {
* @param precision desired precision in meters
*/
public static void decimate(Track track, double precision) {
ArrayList<Location> decimated = new ArrayList<Location>();
ArrayList<Location> decimated = new ArrayList<>();
decimate(precision, track.getLocations(), decimated);
track.setLocations(decimated);
}
@@ -48,7 +48,7 @@ public class PhotoUtils {
if (cancelBitmapLoader(imageView, uri)) {
BitmapLoader bitmapLoader = new BitmapLoader(
imageView, uri, targetWidth, targetHeight, fitWithin);
WeakReference<BitmapLoader> bitmapLoaderReference = new WeakReference<BitmapLoader>(
WeakReference<BitmapLoader> bitmapLoaderReference = new WeakReference<>(
bitmapLoader);
imageView.setTag(bitmapLoaderReference);
bitmapLoader.execute();
@@ -17,7 +17,6 @@
package com.google.android.apps.mytracks.util;
import com.google.android.apps.mytracks.Constants;
import com.google.android.apps.mytracks.io.file.TrackFileFormat;
import com.google.android.gms.location.DetectedActivity;
import com.google.android.maps.mytracks.R;
@@ -60,8 +59,6 @@ public class PreferencesUtils {
public static final String DEFAULT_ACTIVITY_DEFAULT = "";
public static final String EXPORT_EXTERNAL_STORAGE_FORMAT_DEFAULT = TrackFileFormat.KML.name();
// Value for split_frequency_key and voice_frequency_key
public static final int FREQUENCY_OFF = 0;
@@ -93,12 +90,6 @@ public class PreferencesUtils {
public static final boolean STATS_SHOW_GRADE_ELEVATION_DEFAULT = false;
public static final String STATS_UNITS_DEFAULT = "METRIC";
// Track color
public static final String TRACK_COLOR_MODE_DEFAULT = "SINGLE";
public static final int TRACK_COLOR_MODE_MEDIUM_DEFAULT = 15;
public static final int TRACK_COLOR_MODE_PERCENTAGE_DEFAULT = 25;
public static final int TRACK_COLOR_MODE_SLOW_DEFAULT = 9;
public static final String TRACK_NAME_DEFAULT = "LOCATION";
// Track widget
@@ -93,7 +93,6 @@ public class StringUtils {
}
long hours = 0;
long minutes = 0;
long seconds = 0;
long elapsedSeconds = (long) (time * UnitConversions.MS_TO_S);
if (elapsedSeconds >= 3600) {
@@ -104,7 +103,7 @@ public class StringUtils {
minutes = elapsedSeconds / 60;
elapsedSeconds -= minutes * 60;
}
seconds = elapsedSeconds;
long seconds = elapsedSeconds;
if (hours > 0) {
return String.format(Locale.US, "%d:%02d:%02d", hours, minutes, seconds);
@@ -276,13 +275,12 @@ public class StringUtils {
return description;
}
StringBuffer buffer = new StringBuffer();
buffer.append("[").append(category).append("]");
StringBuilder builder = new StringBuilder();
builder.append("[").append(category).append("]");
if (description != null && description.length() != 0) {
buffer.append(" ").append(description);
builder.append(" ").append(description);
}
return buffer.toString();
return builder.toString();
}
/**
@@ -76,25 +76,25 @@ public class TrackIconUtils {
R.string.activity_type_trail_hiking, R.string.activity_type_walking };
private static final LinkedHashMap<String, Pair<Integer, Integer>>
MAP = new LinkedHashMap<String, Pair<Integer, Integer>>();
MAP = new LinkedHashMap<>();
static {
MAP.put(
RUN, new Pair<Integer, Integer>(R.string.activity_type_running, R.drawable.ic_track_run));
RUN, new Pair<>(R.string.activity_type_running, R.drawable.ic_track_run));
MAP.put(
WALK, new Pair<Integer, Integer>(R.string.activity_type_walking, R.drawable.ic_track_walk));
WALK, new Pair<>(R.string.activity_type_walking, R.drawable.ic_track_walk));
MAP.put(
BIKE, new Pair<Integer, Integer>(R.string.activity_type_biking, R.drawable.ic_track_bike));
BIKE, new Pair<>(R.string.activity_type_biking, R.drawable.ic_track_bike));
MAP.put(DRIVE,
new Pair<Integer, Integer>(R.string.activity_type_driving, R.drawable.ic_track_drive));
new Pair<>(R.string.activity_type_driving, R.drawable.ic_track_drive));
MAP.put(
SKI, new Pair<Integer, Integer>(R.string.activity_type_skiing, R.drawable.ic_track_ski));
MAP.put(SNOW_BOARDING, new Pair<Integer, Integer>(
SKI, new Pair<>(R.string.activity_type_skiing, R.drawable.ic_track_ski));
MAP.put(SNOW_BOARDING, new Pair<>(
R.string.activity_type_snow_boarding, R.drawable.ic_track_snow_boarding));
MAP.put(AIRPLANE,
new Pair<Integer, Integer>(R.string.activity_type_airplane, R.drawable.ic_track_airplane));
new Pair<>(R.string.activity_type_airplane, R.drawable.ic_track_airplane));
MAP.put(
BOAT, new Pair<Integer, Integer>(R.string.activity_type_boat, R.drawable.ic_track_boat));
BOAT, new Pair<>(R.string.activity_type_boat, R.drawable.ic_track_boat));
}
private static final float[] REVERT_COLOR_MATRIX = { -1.0f, 0, 0, 0, 255, // red
@@ -135,9 +135,7 @@ public class TrackIconUtils {
* Gets all icon values.
*/
public static List<String> getAllIconValues() {
List<String> values = new ArrayList<>();
values.addAll(MAP.keySet());
return values;
return new ArrayList<>(MAP.keySet());
}
/**
@@ -68,16 +68,16 @@ public class TrackNameUtils {
return new SimpleDateFormat(ISO_8601_FORMAT, Locale.US).format(startTime);
} else if (trackName.equals(
context.getString(R.string.settings_recording_track_name_date_iso_8601_location_value))) {
StringBuffer value = new StringBuffer(
StringBuilder builder = new StringBuilder(
new SimpleDateFormat(ISO_8601_FORMAT, Locale.US).format(startTime));
if (location != null) {
String address = getReverseGeoCoding(context, location);
if (address != null && !address.equals("")) {
value.append(" ").append(address);
builder.append(" ").append(address);
}
}
return value.toString();
return builder.toString();
} else {
// R.string.settings_recording_track_name_number_value)
return context.getString(R.string.track_name_format, trackId);
@@ -49,9 +49,6 @@ public class UnitConversions {
// multiplication factor to convert kilometers to miles
public static final double KM_TO_MI = 0.621371192;
// multiplication factor to convert miles to kilometers
public static final double MI_TO_KM = 1 / KM_TO_MI;
// multiplication factor to convert miles to feet
public static final double MI_TO_FT = 5280.0;
@@ -1,60 +0,0 @@
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.util;
import android.net.Uri;
import java.util.List;
/**
* Utilities for dealing with content and other types of URIs.
*
* @author Rodrigo Damazio
*/
public class UriUtils {
public static boolean matchesContentUri(Uri uri, Uri baseContentUri) {
if (uri == null) {
return false;
}
// Check that scheme and authority are the same.
if (!uri.getScheme().equals(baseContentUri.getScheme()) ||
!uri.getAuthority().equals(baseContentUri.getAuthority())) {
return false;
}
// Checks that all the base path components are in the URI.
List<String> uriPathSegments = uri.getPathSegments();
List<String> basePathSegments = baseContentUri.getPathSegments();
if (basePathSegments.size() > uriPathSegments.size()) {
return false;
}
for (int i = 0; i < basePathSegments.size(); i++) {
if (!uriPathSegments.get(i).equals(basePathSegments.get(i))) {
return false;
}
}
return true;
}
public static boolean isFileUri(Uri uri) {
return "file".equals(uri.getScheme());
}
private UriUtils() {}
}
@@ -62,7 +62,7 @@ public class TrackWidgetConfigActivity extends Activity {
boolean reportSpeed = PreferencesUtils.isReportSpeed(this);
List<CharSequence> list = new ArrayList<CharSequence>();
List<CharSequence> list = new ArrayList<>();
addItem(list, R.string.stats_distance);
addItem(list, R.string.stats_total_time);
addItem(list, reportSpeed ? R.string.stats_average_speed : R.string.stats_average_pace);
@@ -128,7 +128,7 @@ public class TrackWidgetConfigActivity extends Activity {
}
private void configSpinner(Spinner spinner, List<CharSequence> list, int position) {
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<>(
this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
@@ -51,7 +51,6 @@ import android.widget.RemoteViews;
*/
public class TrackWidgetProvider extends AppWidgetProvider {
public static final int KEYGUARD_DEFAULT_SIZE = 1;
public static final int HOME_SCREEN_DEFAULT_SIZE = 2;
private static final String APP_WIDGET_SIZE_KEY = "app_widget_size_key";
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -5,7 +5,7 @@ android {
defaultConfig {
minSdkVersion 21
targetSdkVersion 26
targetSdkVersion 28
}
buildTypes {
@@ -233,38 +233,26 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
@Override
public List<Track> getAllTracks() {
ArrayList<Track> tracks = new ArrayList<Track>();
Cursor cursor = null;
try {
cursor = getTrackCursor(null, null, null, TracksColumns._ID);
ArrayList<Track> tracks = new ArrayList<>();
try (Cursor cursor = getTrackCursor(null, null, null, TracksColumns._ID)) {
if (cursor != null && cursor.moveToFirst()) {
tracks.ensureCapacity(cursor.getCount());
do {
tracks.add(createTrack(cursor));
} while (cursor.moveToNext());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return tracks;
}
@Override
public Track getLastTrack() {
Cursor cursor = null;
try {
try (Cursor cursor = getTrackCursor(null, null, null,
TracksColumns.SHAREDWITHME + " ASC, " + TracksColumns.STARTTIME + " DESC")) {
// Using the same order as shown in the track list
cursor = getTrackCursor(null, null, null,
TracksColumns.SHAREDWITHME + " ASC, " + TracksColumns.STARTTIME + " DESC");
if (cursor != null && cursor.moveToNext()) {
return createTrack(cursor);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@@ -274,17 +262,11 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
if (trackId < 0) {
return null;
}
Cursor cursor = null;
try {
cursor = getTrackCursor(null, TracksColumns._ID + "=?",
new String[] { Long.toString(trackId) }, TracksColumns._ID);
try (Cursor 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;
}
@@ -547,18 +529,12 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
if (trackId < 0) {
return -1L;
}
Cursor cursor = null;
try {
cursor = getWaypointCursor(new String[] { WaypointsColumns._ID },
try (Cursor cursor = getWaypointCursor(new String[]{WaypointsColumns._ID},
WaypointsColumns.TRACKID + "=?", new String[]{Long.toString(trackId)},
WaypointsColumns._ID, 1);
WaypointsColumns._ID, 1)) {
if (cursor != null && cursor.moveToFirst()) {
return cursor.getLong(cursor.getColumnIndexOrThrow(WaypointsColumns._ID));
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return -1L;
}
@@ -618,17 +594,11 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
if (waypointId < 0) {
return null;
}
Cursor cursor = null;
try {
cursor = getWaypointCursor(null, WaypointsColumns._ID + "=?",
new String[] { Long.toString(waypointId) }, WaypointsColumns._ID, 1);
try (Cursor cursor = getWaypointCursor(null, WaypointsColumns._ID + "=?",
new String[]{Long.toString(waypointId)}, WaypointsColumns._ID, 1)) {
if (cursor != null && cursor.moveToFirst()) {
return createWaypoint(cursor);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@@ -1117,16 +1087,10 @@ public class MyTracksProviderUtilsImpl implements MyTracksProviderUtils {
}
private Location findTrackPointBy(String selection, String[] selectionArgs) {
Cursor cursor = null;
try {
cursor = getTrackPointCursor(null, selection, selectionArgs, TrackPointsColumns._ID);
try (Cursor cursor = getTrackPointCursor(null, selection, selectionArgs, TrackPointsColumns._ID)) {
if (cursor != null && cursor.moveToNext()) {
return createTrackPoint(cursor);
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return null;
}
@@ -52,7 +52,7 @@ public class Track implements Parcelable {
private TripStatistics tripStatistics = new TripStatistics();
// Location points (which may not have been loaded)
private ArrayList<Location> locations = new ArrayList<Location>();
private ArrayList<Location> locations = new ArrayList<>();
public Track() {}
@@ -1,28 +0,0 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.android.apps.mytracks.lib;
/**
* Constants for the My Tracks common library.
* These constants should ideally not be used by third-party applications.
*
* @author Rodrigo Damazio
*/
public class MyTracksLibConstants {
public static final String TAG = "MyTracksLib";
private MyTracksLibConstants() {}
}
@@ -131,10 +131,7 @@ public class FileUtils {
* @param components the components
*/
public static String getPath(String... components) {
StringBuilder dirNameBuilder = new StringBuilder();
dirNameBuilder.append(Environment.getExternalStorageDirectory());
dirNameBuilder.append(getPathDisplayName(components));
return dirNameBuilder.toString();
return Environment.getExternalStorageDirectory() + getPathDisplayName(components);
}
/**
@@ -220,17 +217,17 @@ public class FileUtils {
* @param name name
*/
static String sanitizeFileName(String name) {
StringBuffer buffer = new StringBuffer(name.length());
StringBuilder builder = new StringBuilder(name.length());
for (int i = 0; i < name.length(); i++) {
int codePoint = name.codePointAt(i);
char character = name.charAt(i);
if (Character.isLetterOrDigit(character) || codePoint > 127 || isSpecialFat32(character)) {
buffer.appendCodePoint(codePoint);
builder.appendCodePoint(codePoint);
} else {
buffer.append("_");
builder.append("_");
}
}
String result = buffer.toString();
String result = builder.toString();
return result.replaceAll("_+", "_");
}