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:Main.java

@SuppressLint("NewApi")
public static String getRealPathFromURI_API11_And_Above(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 w  ww . j  ava  2  s.c o 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.bt.download.android.gui.Librarian.java

public FileDescriptor getFileDescriptor(Uri uri) {
    FileDescriptor fd = null;/* w  w w  .j a  va2  s.  co  m*/
    try {
        if (uri != null) {
            if (uri.toString().startsWith("file://")) {
                fd = getFileDescriptor(new File(uri.getPath()));
            } else {
                TableFetcher fetcher = TableFetchers.getFetcher(uri);

                fd = new FileDescriptor();
                fd.fileType = fetcher.getFileType();
                fd.id = Integer.valueOf(uri.getLastPathSegment());
            }
        }
    } catch (Throwable e) {
        fd = null;
        // sometimes uri.getLastPathSegment() is not an integer
        e.printStackTrace();
    }
    return fd;
}

From source file:com.xandy.calendar.AllInOneActivity.java

private void initFragments(long timeMillis, int viewType, Bundle icicle) {
    if (DEBUG) {//from   ww  w.  jav a  2  s . c o m
        Log.d(TAG, "Initializing to " + timeMillis + " for view " + viewType);
    }
    //        FragmentTransaction ft = getFragmentManager().beginTransaction();
    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();

    if (mShowCalendarControls) {
        Fragment miniMonthFrag = new MonthByWeekFragment(timeMillis, true);
        ft.replace(R.id.mini_month, miniMonthFrag);
        mController.registerEventHandler(R.id.mini_month, (EventHandler) miniMonthFrag);

        Fragment selectCalendarsFrag = new SelectVisibleCalendarsFragment();
        ft.replace(R.id.calendar_list, selectCalendarsFrag);
        mController.registerEventHandler(R.id.calendar_list, (EventHandler) selectCalendarsFrag);
    }
    if (!mShowCalendarControls || viewType == ViewType.EDIT) {
        mMiniMonth.setVisibility(View.GONE);
        mCalendarsList.setVisibility(View.GONE);
    }

    EventInfo info = null;
    if (viewType == ViewType.EDIT) {
        mPreviousView = GeneralPreferences.getSharedPreferences(this).getInt(GeneralPreferences.KEY_START_VIEW,
                GeneralPreferences.DEFAULT_START_VIEW);

        long eventId = -1;
        Intent intent = getIntent();
        Uri data = intent.getData();
        if (data != null) {
            try {
                eventId = Long.parseLong(data.getLastPathSegment());
            } catch (NumberFormatException e) {
                if (DEBUG) {
                    Log.d(TAG, "Create new event");
                }
            }
        } else if (icicle != null && icicle.containsKey(BUNDLE_KEY_EVENT_ID)) {
            eventId = icicle.getLong(BUNDLE_KEY_EVENT_ID);
        }

        long begin = intent.getLongExtra(EXTRA_EVENT_BEGIN_TIME, -1);
        long end = intent.getLongExtra(EXTRA_EVENT_END_TIME, -1);
        info = new EventInfo();
        if (end != -1) {
            info.endTime = new Time();
            info.endTime.set(end);
        }
        if (begin != -1) {
            info.startTime = new Time();
            info.startTime.set(begin);
        }
        info.id = eventId;
        // We set the viewtype so if the user presses back when they are
        // done editing the controller knows we were in the Edit Event
        // screen. Likewise for eventId
        mController.setViewType(viewType);
        mController.setEventId(eventId);
    } else {
        mPreviousView = viewType;
    }

    setMainPane(ft, R.id.main_pane, viewType, timeMillis, true);
    ft.commit(); // this needs to be after setMainPane()

    Time t = new Time(mTimeZone);
    t.set(timeMillis);
    if (viewType == ViewType.AGENDA && icicle != null) {
        mController.sendEvent(this, EventType.GO_TO, t, null, icicle.getLong(BUNDLE_KEY_EVENT_ID, -1),
                viewType);
    } else if (viewType != ViewType.EDIT) {
        mController.sendEvent(this, EventType.GO_TO, t, null, -1, viewType);
    }
}

From source file:Main.java

@SuppressLint("NewApi")
/**/*from  w w w  .j  av a  2 s  .  co  m*/
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.<br>
 * <br>
 * Callers should check whether the path is local before assuming it
 * represents a local file.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= 19;

    // 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];
            }

            // 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.piusvelte.sonet.core.SonetCreatePost.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*w  w w  . j a  v a 2  s .c o  m*/
    if (intent != null) {
        String action = intent.getAction();
        if ((action != null) && action.equals(Intent.ACTION_SEND)) {
            if (intent.hasExtra(Intent.EXTRA_STREAM))
                getPhoto((Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM));
            if (intent.hasExtra(Intent.EXTRA_TEXT)) {
                final String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                mMessage.setText(text);
                mCount.setText(Integer.toString(text.length()));
            }
            chooseAccounts();
        } else {
            Uri data = intent.getData();
            if ((data != null) && data.toString().contains(Accounts.getContentUri(this).toString())) {
                // default to the account passed in, but allow selecting additional accounts
                Cursor account = this.getContentResolver().query(Accounts.getContentUri(this),
                        new String[] { Accounts._ID, Accounts.SERVICE }, Accounts._ID + "=?",
                        new String[] { data.getLastPathSegment() }, null);
                if (account.moveToFirst())
                    mAccountsService.put(account.getLong(0), account.getInt(1));
                account.close();
            } else if (intent.hasExtra(Widgets.INSTANT_UPLOAD)) {
                // check if a photo path was passed and prompt user to select the account
                setPhoto(intent.getStringExtra(Widgets.INSTANT_UPLOAD));
                chooseAccounts();
            }
        }
    }
}

From source file:com.jtechme.apphub.FDroid.java

private void handleSearchOrAppViewIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        performSearch(query);/*w  ww.ja  v  a  2  s .c  o m*/
        return;
    }

    final Uri data = intent.getData();
    if (data == null) {
        return;
    }

    final String scheme = data.getScheme();
    final String path = data.getPath();
    String packageName = null;
    String query = null;
    if (data.isHierarchical()) {
        final String host = data.getHost();
        if (host == null) {
            return;
        }
        switch (host) {
        case "f-droid.org":
            if (path.startsWith("/repository/browse")) {
                // http://f-droid.org/repository/browse?fdfilter=search+query
                query = UriCompat.getQueryParameter(data, "fdfilter");

                // http://f-droid.org/repository/browse?fdid=packageName
                packageName = UriCompat.getQueryParameter(data, "fdid");
            } else if (path.startsWith("/app")) {
                // http://f-droid.org/app/packageName
                packageName = data.getLastPathSegment();
                if ("app".equals(packageName)) {
                    packageName = null;
                }
            }
            break;
        case "details":
            // market://details?id=app.id
            packageName = UriCompat.getQueryParameter(data, "id");
            break;
        case "search":
            // market://search?q=query
            query = UriCompat.getQueryParameter(data, "q");
            break;
        case "play.google.com":
            if (path.startsWith("/store/apps/details")) {
                // http://play.google.com/store/apps/details?id=app.id
                packageName = UriCompat.getQueryParameter(data, "id");
            } else if (path.startsWith("/store/search")) {
                // http://play.google.com/store/search?q=foo
                query = UriCompat.getQueryParameter(data, "q");
            }
            break;
        case "apps":
        case "amazon.com":
        case "www.amazon.com":
            // amzn://apps/android?p=app.id
            // http://amazon.com/gp/mas/dl/android?s=app.id
            packageName = UriCompat.getQueryParameter(data, "p");
            query = UriCompat.getQueryParameter(data, "s");
            break;
        }
    } else if ("fdroid.app".equals(scheme)) {
        // fdroid.app:app.id
        packageName = data.getSchemeSpecificPart();
    } else if ("fdroid.search".equals(scheme)) {
        // fdroid.search:query
        query = data.getSchemeSpecificPart();
    }

    if (!TextUtils.isEmpty(query)) {
        // an old format for querying via packageName
        if (query.startsWith("pname:"))
            packageName = query.split(":")[1];

        // sometimes, search URLs include pub: or other things before the query string
        if (query.contains(":"))
            query = query.split(":")[1];
    }

    if (!TextUtils.isEmpty(packageName)) {
        Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'");
        Intent intentToInvoke = new Intent(this, AppDetails.class);
        intentToInvoke.putExtra(AppDetails.EXTRA_APPID, packageName);
        startActivity(intentToInvoke);
    } else if (!TextUtils.isEmpty(query)) {
        Utils.debugLog(TAG, "FDroid launched via search link for '" + query + "'");
        performSearch(query);
    }
}

From source file:org.dicadeveloper.runnerapp.services.TrackRecordingService.java

/**
 * Inserts a location.//from   w  w w . j av  a2s  . c om
 * 
 * @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);
    }
    voiceExecutor.update();
    splitExecutor.update();
    sendTrackBroadcast(R.string.track_update_broadcast_action, track.getId());
}

From source file:ru.innopolis.architecture.gstar.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());

                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());
                                }/*from  ww  w  .  ja  va 2 s. c  o  m*/
                            }
                        });
            }
        }
    } else if (requestCode == REQUEST_INVITE) {
        if (resultCode == RESULT_OK) {
            // Use Firebase Measurement to log that invitation was sent.
            Bundle payload = new Bundle();
            payload.putString(FirebaseAnalytics.Param.VALUE, "inv_sent");

            // Check how many invitations were sent and log.
            String[] ids = AppInviteInvitation.getInvitationIds(resultCode, data);
            Log.d(TAG, "Invitations sent: " + ids.length);
        } else {
            // Use Firebase Measurement to log that invitation was not sent
            Bundle payload = new Bundle();
            payload.putString(FirebaseAnalytics.Param.VALUE, "inv_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:org.fdroid.fdroid.FDroid.java

private void handleSearchOrAppViewIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        performSearch(query);/*from   w  ww . j  a  v  a 2 s.com*/
        return;
    }

    final Uri data = intent.getData();
    if (data == null) {
        return;
    }

    final String scheme = data.getScheme();
    final String path = data.getPath();
    String packageName = null;
    String query = null;
    if (data.isHierarchical()) {
        final String host = data.getHost();
        if (host == null) {
            return;
        }
        switch (host) {
        case "f-droid.org":
            if (path.startsWith("/repository/browse")) {
                // http://f-droid.org/repository/browse?fdfilter=search+query
                query = UriCompat.getQueryParameter(data, "fdfilter");

                // http://f-droid.org/repository/browse?fdid=packageName
                packageName = UriCompat.getQueryParameter(data, "fdid");
            } else if (path.startsWith("/app")) {
                // http://f-droid.org/app/packageName
                packageName = data.getLastPathSegment();
                if ("app".equals(packageName)) {
                    packageName = null;
                }
            }
            break;
        case "details":
            // market://details?id=app.id
            packageName = UriCompat.getQueryParameter(data, "id");
            break;
        case "search":
            // market://search?q=query
            query = UriCompat.getQueryParameter(data, "q");
            break;
        case "play.google.com":
            if (path.startsWith("/store/apps/details")) {
                // http://play.google.com/store/apps/details?id=app.id
                packageName = UriCompat.getQueryParameter(data, "id");
            } else if (path.startsWith("/store/search")) {
                // http://play.google.com/store/search?q=foo
                query = UriCompat.getQueryParameter(data, "q");
            }
            break;
        case "apps":
        case "amazon.com":
        case "www.amazon.com":
            // amzn://apps/android?p=app.id
            // http://amazon.com/gp/mas/dl/android?s=app.id
            packageName = UriCompat.getQueryParameter(data, "p");
            query = UriCompat.getQueryParameter(data, "s");
            break;
        }
    } else if ("fdroid.app".equals(scheme)) {
        // fdroid.app:app.id
        packageName = data.getSchemeSpecificPart();
    } else if ("fdroid.search".equals(scheme)) {
        // fdroid.search:query
        query = data.getSchemeSpecificPart();
    }

    if (!TextUtils.isEmpty(query)) {
        // an old format for querying via packageName
        if (query.startsWith("pname:")) {
            packageName = query.split(":")[1];
        }

        // sometimes, search URLs include pub: or other things before the query string
        if (query.contains(":")) {
            query = query.split(":")[1];
        }
    }

    if (!TextUtils.isEmpty(packageName)) {
        Utils.debugLog(TAG, "FDroid launched via app link for '" + packageName + "'");
        Intent intentToInvoke = new Intent(this, AppDetails.class);
        intentToInvoke.putExtra(AppDetails.EXTRA_APPID, packageName);
        startActivity(intentToInvoke);
        finish();
    } else if (!TextUtils.isEmpty(query)) {
        Utils.debugLog(TAG, "FDroid launched via search link for '" + query + "'");
        performSearch(query);
    }
}

From source file:fishlinghu.sporttogether.ChatActivity.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());

                FriendlyMessage tempMessage = new FriendlyMessage(null, mUsername, mPhotoUrl,
                        LOADING_IMAGE_URL);
                mFirebaseDatabaseReference.child("chatrooms").child(roomKey).child("messages").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 ww . j  a  v a 2s.  co m*/
                            }
                        });
            }
        }
    }
}