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.dicadeveloper.runnerapp.services.TrackRecordingService.java

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

    WaypointType waypointType = waypointCreationRequest.getType();
    boolean isStatistics = waypointType == WaypointType.STATISTICS;

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

    // Get category
    String category = waypointCreationRequest.getCategory() != null ? waypointCreationRequest.getCategory()
            : "";

    // Get tripStatistics, description, and icon
    TripStatistics tripStatistics;
    String description;
    String icon;
    if (isStatistics) {
        long now = System.currentTimeMillis();
        markerTripStatisticsUpdater.updateTime(now);
        tripStatistics = markerTripStatisticsUpdater.getTripStatistics();
        markerTripStatisticsUpdater = new TripStatisticsUpdater(now);
        description = new DescriptionGeneratorImpl(this).generateWaypointDescription(tripStatistics);
        icon = getString(R.string.marker_statistics_icon_url);
    } else {
        tripStatistics = null;
        description = waypointCreationRequest.getDescription() != null
                ? waypointCreationRequest.getDescription()
                : "";
        icon = getString(R.string.marker_waypoint_icon_url);
    }

    // Get length and duration
    double length;
    long duration;
    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.0;
        duration = 0L;
    }

    String photoUrl = waypointCreationRequest.getPhotoUrl() != null ? waypointCreationRequest.getPhotoUrl()
            : "";

    // Insert waypoint
    Waypoint waypoint = new Waypoint(name, description, category, icon, recordingTrackId, waypointType, length,
            duration, -1L, -1L, location, tripStatistics, photoUrl);
    Uri uri = myTracksProviderUtils.insertWaypoint(waypoint);
    return Long.parseLong(uri.getLastPathSegment());
}

From source file:com.roamprocess1.roaming4world.ui.messages.MessageActivity.java

public void handlecontactBrowseData(Intent data) {
    Uri uriOfPhoneNumberRecord = data.getData();
    String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
    Cursor cursor = getContentResolver().query(Phone.CONTENT_URI,
            new String[] { Phone.NUMBER, Phone.DISPLAY_NAME }, Phone._ID + "=?",
            new String[] { idOfPhoneRecord }, null);
    if (cursor != null) {
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();/*from   w w  w  .  ja v  a  2  s .  c  o  m*/
            String formattedPhoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
            Log.d("Contact Selected", formattedPhoneNumber + " &");
            String formattedName = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME));
            Log.d("Contact Selected", formattedName + " &");
            String contact_msg = "CON-" + formattedName + "-" + formattedPhoneNumber;
            MessageFragment.sendImage(contact_msg);
        }
        cursor.close();
    }

}

From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java

private int deleteArtwork(@NonNull final Uri uri, final String selection, final String[] selectionArgs) {
    // Opens the database object in "write" mode.
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    String finalWhere = selection;
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        finalWhere = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " = "
                + uri.getLastPathSegment();
        // If there were additional selection criteria, append them to the final WHERE clause
        if (selection != null)
            finalWhere = finalWhere + " AND " + selection;
    }/*from  w  w  w  .j a  v a2 s.  c  o  m*/
    // We can't just simply delete the rows as that won't free up the space occupied by the
    // artwork image files associated with each row being deleted. Instead we have to query
    // and manually delete each artwork file
    String[] projection = new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN };
    Cursor rowsToDelete = queryArtwork(uri, projection, finalWhere, selectionArgs,
            MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI);
    if (rowsToDelete == null) {
        return 0;
    }
    // First we build a list of IDs to be deleted. This will be used if we need to determine
    // if a given image URI needs to be deleted
    List<String> idsToDelete = new ArrayList<>();
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        idsToDelete.add(Long.toString(rowsToDelete.getLong(0)));
        rowsToDelete.moveToNext();
    }
    String notInDeleteIds = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN ("
            + TextUtils.join(",", idsToDelete) + ")";
    // Now we actually go through the list of rows to be deleted
    // and check if we can delete the artwork image file associated with each one
    rowsToDelete.moveToFirst();
    while (!rowsToDelete.isAfterLast()) {
        Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowsToDelete.getLong(0));
        String imageUri = rowsToDelete.getString(1);
        String token = rowsToDelete.getString(2);
        if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) {
            // An empty image URI and token means the artwork is unique to this specific row
            // so we can always delete it when the associated row is deleted
            File artwork = getCacheFileForArtworkUri(artworkUri);
            if (artwork != null && artwork.exists()) {
                artwork.delete();
            }
        } else if (TextUtils.isEmpty(imageUri)) {
            // Check if there are other rows using this same token that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_TOKEN + "=? AND " + notInDeleteIds,
                    new String[] { token }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        } else {
            // Check if there are other rows using this same image URI that aren't
            // in the list of ids to delete
            Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI,
                    new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID },
                    MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI + "=? AND " + notInDeleteIds,
                    new String[] { imageUri }, null);
            if (otherArtwork == null) {
                continue;
            }
            if (otherArtwork.getCount() == 0) {
                // There's no non-deleted rows that reference this same artwork URI
                // so we can delete the artwork
                File artwork = getCacheFileForArtworkUri(artworkUri);
                if (artwork != null && artwork.exists()) {
                    artwork.delete();
                }
            }
            otherArtwork.close();
        }
        rowsToDelete.moveToNext();
    }
    rowsToDelete.close();
    int count = db.delete(MuzeiContract.Artwork.TABLE_NAME, finalWhere, selectionArgs);
    if (count > 0) {
        notifyChange(uri);
    }
    return count;
}

From source file:com.cenkgun.chatty.MainActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                final Uri uri = data.getData();
                Log.d(TAG, "Uri: " + uri.toString());

                ChattyMessage tempMessage = new ChattyMessage(null, mUsername, mPhotoUrl,
                        dateFormat.format(date),

                        LOADING_IMAGE_URL);
                mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(tempMessage,
                        new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError,
                                    DatabaseReference databaseReference) {
                                if (databaseError == null) {
                                    String key = databaseReference.getKey();
                                    StorageReference storageReference = FirebaseStorage.getInstance()
                                            .getReference(mFirebaseUser.getUid()).child(key)
                                            .child(uri.getLastPathSegment());

                                    putImageInStorage(storageReference, uri, key);
                                } else {
                                    Log.w(TAG, "Unable to write message to database.",
                                            databaseError.toException());
                                }//from   w  w w. ja va2  s.  c om
                            }
                        });
            }
        }
    } else if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Check how many invitations were sent and log.
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            Log.d(TAG, "Invitations sent: " + ids.length);
        } else {
            // Sending failed or it was canceled, show failure message to the user
            Log.d(TAG, "Failed to send invitation.");
        }
    }
}

From source file:de.vanita5.twittnuker.provider.TwidereDataProvider.java

@Override
public ParcelFileDescriptor openFile(final Uri uri, final String mode) throws FileNotFoundException {
    if (uri == null || mode == null)
        throw new IllegalArgumentException();
    final int table_id = getTableId(uri);
    switch (table_id) {
    case VIRTUAL_TABLE_ID_CACHED_IMAGES: {
        return getCachedImageFd(uri.getQueryParameter(QUERY_PARAM_URL));
    }//from  w w w  .j  a v  a 2 s  . c  o m
    case VIRTUAL_TABLE_ID_CACHE_FILES: {
        return getCacheFileFd(uri.getLastPathSegment());
    }
    }
    return null;
}

From source file:nz.ac.auckland.lablet.script.ScriptRunnerActivity.java

@Nullable
private String computeFileName(@NonNull Uri uri) {

    // 'content' scheme will include the file name in the meta data
    if (uri.getScheme().equals("content")) {

        // open the Uri meta data so we can read the file name
        final String[] nameProjection = { MediaColumns.DISPLAY_NAME };
        Cursor uriMetaData = getContentResolver().query(uri, nameProjection, null, null, null);
        if (uriMetaData == null) {
            return null;
        }//www.j av a  2s  .c  o m

        // move to first row of uri meta data and read display name, return if this fails
        final int displayName = 0;
        try {
            return uriMetaData.moveToFirst() ? uriMetaData.getString(displayName) : null;
        } finally {
            uriMetaData.close();
        }
    }

    // 'file' scheme will have the file name stored in the path
    if (uri.getScheme().equals("file")) {
        return uri.getLastPathSegment();
    }

    // unsupported scheme
    return null;
}

From source file:br.com.bioscada.apps.biotracks.services.TrackRecordingService.java

/**
 * Starts a new track.//from  w  ww  . j av  a 2  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();
    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);
    PreferencesUtils.setInt(this, R.string.activity_recognition_type_key,
            PreferencesUtils.ACTIVITY_RECOGNITION_TYPE_DEFAULT);

    // Update database
    track.setId(trackId);
    track.setName(TrackNameUtils.getTrackName(this, trackId, now, null));

    String category = PreferencesUtils.getString(this, R.string.default_activity_key,
            PreferencesUtils.DEFAULT_ACTIVITY_DEFAULT);
    track.setCategory(category);
    track.setIcon(TrackIconUtils.getIconValue(this, category));
    track.setTripStatistics(trackTripStatisticsUpdater.getTripStatistics());
    myTracksProviderUtils.updateTrack(track);
    insertWaypoint(WaypointCreationRequest.DEFAULT_START_TRACK);

    startRecording(true);
    return trackId;
}

From source file:org.inframiner.firebase.starter.MainActivity.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d(TAG, "onActivityResult: requestCode=" + requestCode + ", resultCode=" + resultCode);

    if (requestCode == REQUEST_IMAGE) {
        if (resultCode == RESULT_OK) {
            if (data != null) {
                final Uri uri = data.getData();
                Log.d(TAG, "Uri: " + uri.toString());

                FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
                        LOADING_IMAGE_URL);
                mFirebaseDatabaseReference.child(MESSAGES_CHILD).push().setValue(tempMessage,
                        new DatabaseReference.CompletionListener() {
                            @Override
                            public void onComplete(DatabaseError databaseError,
                                    DatabaseReference databaseReference) {
                                if (databaseError == null) {
                                    String key = databaseReference.getKey();
                                    StorageReference storageReference = FirebaseStorage.getInstance()
                                            .getReference(mFirebaseUser.getUid()).child(key)
                                            .child(uri.getLastPathSegment());

                                    putImageInStorage(storageReference, uri, key);
                                } else {
                                    Log.w(TAG, "Unable to write message to database.",
                                            databaseError.toException());
                                }/*  w  ww  . j  a  va 2 s  . c  om*/
                            }
                        });
            }
        }
    } else if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            Bundle payload = new Bundle();
            payload.putString(FirebaseAnalytics.Param.VALUE, "sent");
            mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE, payload);

            // Check how many invitations were sent and log.
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            Log.d(TAG, "Invitations send: " + ids.length);
        } else {
            Bundle payload = new Bundle();
            payload.putString(FirebaseAnalytics.Param.VALUE, "not sent");
            mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE, payload);

            // Sending failed or it was canceled, show failure message to the user
            Log.d(TAG, "Failed to send invitation.");
        }
    }
}

From source file:nu.yona.app.ui.YonaActivity.java

private void showContactDetails(final Intent data) {
    final RegisterUser user = new RegisterUser();
    new AsyncTask<Void, Void, Object>() {

        @Override/*  w  w  w.  ja  v a2  s.  com*/
        protected Object doInBackground(Void... params) {
            try {
                Uri result = data.getData();
                String id = result.getLastPathSegment();

                //To get email address of user
                Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + "=?", new String[] { id },
                        null);

                if (cursor.moveToFirst()) {
                    user.setEmailAddress(cursor
                            .getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
                }
                cursor.close();

                // To get contact name etc of user
                String whereName = ContactsContract.Data.MIMETYPE + " = ? AND "
                        + ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID + " = ? ";
                String[] whereNameParams = new String[] {
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE, id };
                Cursor nameCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, whereName,
                        whereNameParams, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
                while (nameCur.moveToNext()) {
                    user.setFirstName(nameCur.getString(nameCur
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME)));
                    user.setLastName(nameCur.getString(nameCur
                            .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME)));

                }
                nameCur.close();

                // To get Mobile number of contact
                Cursor phoneCur = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { id },
                        null);
                List<String> numberList = new ArrayList<String>();
                phoneCur.moveToFirst();
                do {
                    String number = phoneCur
                            .getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    number = TextUtils.isEmpty(number) ? getString(R.string.blank)
                            : number.replace(getString(R.string.space), getString(R.string.blank));
                    numberList.add(number);
                } while (phoneCur.moveToNext());
                if (numberList.size() == 1) {
                    user.setMobileNumber(numberList.get(0));
                } else {
                    user.setMultipleNumbers(numberList);
                }
                phoneCur.close();
            } catch (Exception e) {
                AppUtils.reportException(YonaActivity.class.getSimpleName(), e, Thread.currentThread());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            showLoadingView(false, null);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    YonaApplication.getEventChangeManager()
                            .notifyChange(EventChangeManager.EVENT_CONTAT_CHOOSED, user);
                }
            }, AppConstant.TIMER_DELAY);
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

From source file:br.com.bioscada.apps.biotracks.services.TrackRecordingService.java

/**
 * Inserts a location.//from  w  ww . ja v a  2 s. c o 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());
        ActivityType activityType = CalorieUtils.getActivityType(context, track.getCategory());
        trackTripStatisticsUpdater.addLocation(location, recordingDistanceInterval, true, activityType, weight);
        markerTripStatisticsUpdater.addLocation(location, recordingDistanceInterval, true, activityType,
                weight);
        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);
    }
    splitExecutor.update();
    voiceSplitExecutor.update();
    voice1Executor.update();
    voice2Executor.update();
    sendTrackBroadcast(R.string.track_update_broadcast_action, track.getId());
}