Example usage for android.net Uri getLastPathSegment

List of usage examples for android.net Uri getLastPathSegment

Introduction

In this page you can find the example usage for android.net Uri getLastPathSegment.

Prototype

@Nullable
public abstract String getLastPathSegment();

Source Link

Document

Gets the decoded last segment in the path.

Usage

From source file:org.cowboycoders.cyclisimo.services.TrackRecordingService.java

/**
 * Inserts a location./*from  w  ww.j a v a  2 s  .co m*/
 * 
 * @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;
    }
    // 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());
        trackTripStatisticsUpdater.addLocation(location, minRecordingDistance);
        markerTripStatisticsUpdater.addLocation(location, minRecordingDistance);
        updateRecordingTrack(track, trackPointId, LocationUtils.isValidLocation(location));
    } catch (SQLiteException e) {
        /*
         * Insert failed, most likely because of SqlLite error code 5
         * (SQLite_BUSY). This is expected to happen extremely rarely (if our
         * listener gets invoked twice at about the same time).
         */
        Log.w(TAG, "SQLiteException", e);
    }
    voiceExecutor.update();
    splitExecutor.update();
    sendTrackBroadcast(R.string.track_update_broadcast_action, track.getId());
}

From source file:org.cowboycoders.cyclismo.services.TrackRecordingService.java

/**
 * Starts a new track./*from  w w w.jav  a 2  s.co  m*/
 * 
 * @return the track id
 */
private long startNewTrack() {
    if (isRecording()) {
        Log.d(TAG, "Ignore startNewTrack. Already recording.");
        return -1L;
    }
    long now = System.currentTimeMillis();
    trackTripStatisticsUpdater = new TripStatisticsUpdater(now);
    markerTripStatisticsUpdater = new TripStatisticsUpdater(now);

    long currentUserId = PreferencesUtils.getLong(this, R.string.settings_select_user_current_selection_key);

    // Insert a track
    Track track = new Track();
    track.setOwner(currentUserId);
    Uri uri = myTracksProviderUtils.insertTrack(track);
    long trackId = Long.parseLong(uri.getLastPathSegment());

    // Update shared preferences
    updateRecordingState(trackId, false);
    PreferencesUtils.setInt(this, R.string.auto_resume_track_current_retry_key, 0);

    // Update database
    track.setId(trackId);
    track.setName(TrackNameUtils.getTrackName(this, trackId, now, null));
    track.setCategory(PreferencesUtils.getString(this, R.string.default_activity_key,
            PreferencesUtils.getDefaultActivityDefault(this)));
    track.setIcon((TrackIconUtils.getIconValue(this, track.getCategory())));
    track.setTripStatistics(trackTripStatisticsUpdater.getTripStatistics());
    myTracksProviderUtils.updateTrack(track);
    insertWaypoint(WaypointCreationRequest.DEFAULT_START_TRACK);

    startRecording(true);
    return trackId;
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = isKK();

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }//from w  w  w  .j  a  v a2  s.  co  m

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] { split[1] };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {

        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();

        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.nogago.android.tracks.services.TrackRecordingService.java

/**
 * Inserts a new location in the track points db and updates the corresponding
 * track in the track db./* www.  ja  va  2  s .  co m*/
 *
 * @param location the location to be inserted
 * @param lastRecordedLocation the last recorded location before this one (or
 *        null if none)
 * @param trackId the id of the track
 * @return true if successful. False if SQLite3 threw an exception.
 */
private boolean insertLocation(Location location, Location lastRecordedLocation, long trackId) {

    // Keep track of length along recorded track (needed when a waypoint is
    // inserted):
    if (LocationUtils.isValidLocation(location)) {
        if (lastValidLocation != null) {
            length += location.distanceTo(lastValidLocation);
        }
        lastValidLocation = location;
    }

    // Insert the new location:
    try {
        Location locationToInsert = location;
        if (sensorManager != null && sensorManager.isEnabled()) {
            SensorDataSet sd = sensorManager.getSensorDataSet();
            if (sd != null && sensorManager.isSensorDataSetValid()) {
                locationToInsert = new MyTracksLocation(location, sd);
            }
        }
        Uri pointUri = providerUtils.insertTrackPoint(locationToInsert, trackId);
        int pointId = Integer.parseInt(pointUri.getLastPathSegment());

        // Update the current track:
        if (lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90) {
            TripStatistics tripStatistics = statsBuilder.getStatistics();
            tripStatistics.setStopTime(System.currentTimeMillis());

            if (recordingTrack.getStartId() < 0) {
                recordingTrack.setStartId(pointId);
            }
            recordingTrack.setStopId(pointId);
            recordingTrack.setNumberOfPoints(recordingTrack.getNumberOfPoints() + 1);
            recordingTrack.setTripStatistics(tripStatistics);
            providerUtils.updateTrack(recordingTrack);
            updateCurrentWaypoint();
        }
    } catch (SQLiteException e) {
        // Insert failed, most likely because of SqlLite error code 5
        // (SQLite_BUSY). This is expected to happen extremely rarely (if our
        // listener gets invoked twice at about the same time).
        Log.w(TAG, "Caught SQLiteException: " + e.getMessage(), e);
        return false;
    }
    announcementExecutor.update();
    splitExecutor.update();
    return true;
}

From source file:com.google.android.apps.mytracks.services.TrackRecordingService.java

/**
 * Starts a new track./*from   ww  w  .j  ava2  s.c  om*/
 * 
 * @return the track id
 */
private long startNewTrack() {
    if (isRecording()) {
        Log.d(TAG, "Ignore startNewTrack. Already recording.");
        return -1L;
    }
    long now = System.currentTimeMillis();

    // SignalStrength register for signal sampling
    signalListener = signalListenerFactory.create(this, this);
    signalListener.register();

    /* Unclear whether service is at all needed...
    Intent intent = new Intent(this, SignalStrengthService.class);
    intent.setAction(SignalStrengthConstants.START_SAMPLING);
    startService(intent);
    // SignalStrength Stop
    */
    trackTripStatisticsUpdater = new TripStatisticsUpdater(now);
    markerTripStatisticsUpdater = new TripStatisticsUpdater(now);

    // Insert a track
    Track track = new Track();
    Uri uri = myTracksProviderUtils.insertTrack(track);
    long trackId = Long.parseLong(uri.getLastPathSegment());

    // Update shared preferences
    updateRecordingState(trackId, false);
    PreferencesUtils.setInt(this, R.string.auto_resume_track_current_retry_key, 0);

    // Update database
    track.setId(trackId);
    track.setName(TrackNameUtils.getTrackName(this, trackId, now, null));
    track.setCategory(PreferencesUtils.getString(this, R.string.default_activity_key,
            PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT));
    track.setTripStatistics(trackTripStatisticsUpdater.getTripStatistics());
    myTracksProviderUtils.updateTrack(track);
    insertWaypoint(WaypointCreationRequest.DEFAULT_START_TRACK);

    startRecording(true);
    return trackId;
}

From source file:org.cowboycoders.cyclismo.services.TrackRecordingService.java

/**
 * Inserts a waypoint./*from ww w . j  a v  a  2s.  c om*/
 * 
 * @param waypointCreationRequest the waypoint creation request
 * @return the waypoint id
 */
public long insertWaypoint(WaypointCreationRequest waypointCreationRequest) {

    if (!isRecording() || isPaused()) {
        return -1L;
    }

    boolean isStatistics = waypointCreationRequest.getType() == WaypointType.STATISTICS;
    String name;
    if (waypointCreationRequest.getName() != null) {
        name = waypointCreationRequest.getName();
    } else {
        int nextWaypointNumber = myTracksProviderUtils.getNextWaypointNumber(recordingTrackId, isStatistics);
        if (nextWaypointNumber == -1) {
            nextWaypointNumber = 0;
        }
        name = getString(isStatistics ? R.string.marker_split_name_format : R.string.marker_name_format,
                nextWaypointNumber);
    }

    TripStatistics tripStatistics;
    String description;
    if (isStatistics) {
        long now = System.currentTimeMillis();
        markerTripStatisticsUpdater.updateTime(now);
        tripStatistics = markerTripStatisticsUpdater.getTripStatistics();
        markerTripStatisticsUpdater = new TripStatisticsUpdater(now);
        description = new DescriptionGeneratorImpl(this).generateWaypointDescription(tripStatistics);
    } else {
        tripStatistics = null;
        description = waypointCreationRequest.getDescription() != null
                ? waypointCreationRequest.getDescription()
                : "";
    }

    String category = waypointCreationRequest.getCategory() != null ? waypointCreationRequest.getCategory()
            : "";
    String icon = getString(
            isStatistics ? R.string.marker_statistics_icon_url : R.string.marker_waypoint_icon_url);
    int type = isStatistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT;
    long duration;
    double length;
    Location location = getLastValidTrackPointInCurrentSegment(recordingTrackId);
    if (location != null && trackTripStatisticsUpdater != null) {
        TripStatistics stats = trackTripStatisticsUpdater.getTripStatistics();
        length = stats.getTotalDistance();
        duration = stats.getTotalTime();
    } else {
        if (!waypointCreationRequest.isTrackStatistics()) {
            return -1L;
        }
        // For track statistics, make it an impossible location
        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, location, tripStatistics);
    Uri uri = myTracksProviderUtils.insertWaypoint(waypoint);
    return Long.parseLong(uri.getLastPathSegment());
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getPath(final Context context, final Uri uri) {
    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }//from   ww w . jav  a 2s .  co m
            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {
            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];
            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            final String selection = MediaColumns._ID + "=?";
            final String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(uri))
            return uri.getLastPathSegment();
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}

From source file:com.google.android.apps.mytracks.services.TrackRecordingService.java

/**
 * Inserts a waypoint./*from   w  w w. j  av  a 2 s . c o m*/
 * 
 * @param waypointCreationRequest the waypoint creation request
 * @return the waypoint id
 */
public long insertWaypoint(WaypointCreationRequest waypointCreationRequest) {
    if (!isRecording() || isPaused()) {
        return -1L;
    }

    boolean isStatistics = waypointCreationRequest.getType() == WaypointType.STATISTICS;
    String name;
    if (waypointCreationRequest.getName() != null) {
        name = waypointCreationRequest.getName();
    } else {
        int nextWaypointNumber = myTracksProviderUtils.getNextWaypointNumber(recordingTrackId, isStatistics);
        if (nextWaypointNumber == -1) {
            nextWaypointNumber = 0;
        }
        name = getString(isStatistics ? R.string.marker_split_name_format : R.string.marker_name_format,
                nextWaypointNumber);
    }

    TripStatistics tripStatistics;
    String description;
    if (isStatistics) {
        long now = System.currentTimeMillis();
        markerTripStatisticsUpdater.updateTime(now);
        tripStatistics = markerTripStatisticsUpdater.getTripStatistics();
        markerTripStatisticsUpdater = new TripStatisticsUpdater(now);
        // TODO Check why serializing statistics as text breaks upload... Do not serialize statistics as text
        description = ""; // new DescriptionGeneratorImpl(this).generateWaypointDescription(tripStatistics);
    } else {
        tripStatistics = null;
        description = waypointCreationRequest.getDescription() != null
                ? waypointCreationRequest.getDescription()
                : "";
    }

    String category = waypointCreationRequest.getCategory() != null ? waypointCreationRequest.getCategory()
            : "";
    String icon = getString(
            isStatistics ? R.string.marker_statistics_icon_url : R.string.marker_waypoint_icon_url);
    int type = isStatistics ? Waypoint.TYPE_STATISTICS : Waypoint.TYPE_WAYPOINT;
    long duration;
    double length;
    Location location = getLastValidTrackPointInCurrentSegment(recordingTrackId);
    if (location != null && trackTripStatisticsUpdater != null) {
        TripStatistics stats = trackTripStatisticsUpdater.getTripStatistics();
        length = stats.getTotalDistance();
        duration = stats.getTotalTime();
    } else {
        if (!waypointCreationRequest.isTrackStatistics()) {
            return -1L;
        }
        // For track statistics, make it an impossible location
        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, location, tripStatistics);
    Uri uri = myTracksProviderUtils.insertWaypoint(waypoint);
    return Long.parseLong(uri.getLastPathSegment());
}

From source file:org.cowboycoders.cyclismo.services.TrackRecordingService.java

/**
 * Inserts a location./*from  w  w w. j  a v  a2s  .co m*/
 * 
 * @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. Location is null.");
        return;
    }

    Log.d(TAG, "insertLocation, location: " + location.toString());
    if (lastValidTrackPoint != null) {
        Log.d(TAG, "insertLocation, lastValidTrackPoint" + lastValidTrackPoint.toString());
    }

    // 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;
    }
    Log.d(TAG, "insertLocation, location: " + location.toString());
    if (lastValidTrackPoint != null) {
        Log.d(TAG, "insertLocation, lastValidLocation: " + lastValidTrackPoint.toString());
    }
    try {
        Uri uri = myTracksProviderUtils.insertTrackPoint(location, track.getId());
        long trackPointId = Long.parseLong(uri.getLastPathSegment());
        trackTripStatisticsUpdater.addLocation(location, minRecordingDistance);
        markerTripStatisticsUpdater.addLocation(location, minRecordingDistance);
        updateRecordingTrack(track, trackPointId, LocationUtils.isValidLocation(location));
    } catch (SQLiteException e) {
        /*
         * Insert failed, most likely because of SqlLite error code 5
         * (SQLite_BUSY). This is expected to happen extremely rarely (if our
         * listener gets invoked twice at about the same time).
         */
        Log.w(TAG, "SQLiteException", e);
    }
    voiceExecutor.update();
    splitExecutor.update();
    sendTrackBroadcast(R.string.track_update_broadcast_action, track.getId());
}

From source file:com.hybris.mobile.lib.commerce.provider.CatalogProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    int nbRowsUpdated;

    switch (URI_MATCHER.match(uri)) {

    // Update a data
    case CatalogContract.Provider.CODE_DATA_ID:
        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase()
                    .update(CatalogContract.DataBaseDataSimple.TABLE_NAME, values, selection, selectionArgs);
        } else {//from   ww  w  . ja  va2 s .co m
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseDataSimple.TABLE_NAME, values,
                    CatalogContract.DataBaseData.ATT_DATA_ID + "=?", new String[] { uri.getLastPathSegment() });
        }
        break;

    // Update a data details
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:
        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase()
                    .update(CatalogContract.DataBaseDataDetails.TABLE_NAME, values, selection, selectionArgs);
        } else {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseDataDetails.TABLE_NAME, values,
                    CatalogContract.DataBaseData.ATT_DATA_ID + "=?", new String[] { uri.getLastPathSegment() });
        }
        break;

    // Update a group sync status
    case CatalogContract.Provider.CODE_SYNC_GROUP:

        if (selection != null && selectionArgs != null) {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, values, selection, selectionArgs);
        } else {
            nbRowsUpdated = mDatabaseHelper.getWritableDatabase().update(
                    CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, values,
                    CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "=?",
                    new String[] { uri.getLastPathSegment() });
        }

        break;

    default:
        Log.e(TAG, "URI not recognized" + uri.toString());
        throw new IllegalArgumentException("URI not recognized" + uri.toString());

    }

    Log.i(TAG, "Notify changes for " + uri);

    // Notify watchers of the change
    getContext().getContentResolver().notifyChange(uri, null);

    return nbRowsUpdated;
}