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:com.ziyou.selftravel.download.DownloadManager.java

/** {@hide} */
public long addCompletedDownload(String title, String description, boolean isMediaScannerScannable,
        String mimeType, String path, long length, boolean showNotification, boolean allowWrite) {
    // make sure the input args are non-null/non-zero
    validateArgumentIsNonEmpty("title", title);
    validateArgumentIsNonEmpty("description", description);
    validateArgumentIsNonEmpty("path", path);
    validateArgumentIsNonEmpty("mimeType", mimeType);
    if (length < 0) {
        throw new IllegalArgumentException(" invalid value for param: totalBytes");
    }/*from   w  w  w. j  av  a  2 s  .com*/

    // if there is already an entry with the given path name in
    // downloads.db, return its id
    Request request = new Request(NON_DOWNLOADMANAGER_DOWNLOAD).setTitle(title).setDescription(description)
            .setMimeType(mimeType);
    ContentValues values = request.toContentValues(null);
    values.put(Downloads.Impl.COLUMN_DESTINATION, Downloads.Impl.DESTINATION_NON_DOWNLOADMANAGER_DOWNLOAD);
    values.put(Downloads.Impl._DATA, path);
    values.put(Downloads.Impl.COLUMN_STATUS, Downloads.Impl.STATUS_SUCCESS);
    values.put(Downloads.Impl.COLUMN_TOTAL_BYTES, length);
    values.put(Downloads.Impl.COLUMN_MEDIA_SCANNED,
            (isMediaScannerScannable) ? Request.SCANNABLE_VALUE_YES : Request.SCANNABLE_VALUE_NO);
    values.put(Downloads.Impl.COLUMN_VISIBILITY,
            (showNotification) ? Request.VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION : Request.VISIBILITY_HIDDEN);
    values.put(Downloads.Impl.COLUMN_ALLOW_WRITE, allowWrite ? 1 : 0);
    Uri downloadUri = mResolver.insert(Downloads.Impl.CONTENT_URI, values);
    if (downloadUri == null) {
        return -1;
    }
    return Long.parseLong(downloadUri.getLastPathSegment());
}

From source file:com.android.app.MediaPlaybackActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode != RESULT_OK) {
        return;/*  w  w w. j  av  a 2s. c  o m*/
    }
    switch (requestCode) {
    case NEW_PLAYLIST:
        Uri uri = intent.getData();
        if (uri != null) {
            long[] list = new long[1];
            list[0] = MusicUtils.getCurrentAudioId();
            int playlist = Integer.parseInt(uri.getLastPathSegment());
            MusicUtils.addToPlaylist(this, list, playlist);
        }
        break;
    }
}

From source file:com.chatwing.whitelabel.activities.CommunicationActivity.java

private void processEvent(Event event) {
    String name = event.getName();
    LogUtils.v("event " + event.getParams());
    if (name.equals(EventParser.EVENT_DELETE_MESSAGE)) {
        mCurrentCommunicationMode.processDeleteMessageEvent(event);
    } else if (name.equals(EventParser.EVENT_DELETE_MESSAGE_BY_SOCIAL)) {
        mCurrentCommunicationMode.processDeleteMessagesBySocialAccountEvent(event);
    } else if (name.equals(EventParser.EVENT_DELETE_MESSAGE_BY_IP)) {
        mCurrentCommunicationMode.processDeleteMessagesByIPEvent(event);
    } else if (name.equals(EventParser.EVENT_NEW_MESSAGE)
            || name.equals(EventParser.EVENT_NETWORK_NEW_MESSAGE)) {
        Message message = (Message) event.getParams();
        message.setStatus(Message.Status.PUBLISHED);

        if (!isFromMe(message)) {
            // New message, insert it into DB.
            Uri uri = ChatWingContentProvider.getMessagesUri();
            ContentValues contentValues = MessageTable.getContentValues(message);
            Uri result = getContentResolver().insert(uri, contentValues);
            if ("-1".equals(result.getLastPathSegment())) {
                // Failed to insert the message. Stop here.
                LogUtils.e("Insert message failed ");
                return;
            }/* w w  w  .  j a  va  2 s .  com*/
        }

        boolean added;
        boolean isInCurrentCommunicationBox = mCurrentCommunicationMode.isInCurrentCommunicationBox(message);

        if (!isInCurrentCommunicationBox) {
            added = mCurrentCommunicationMode.processMessageNotInCurrentCommunicationBox(message);
        } else {
            CommunicationMessagesFragment fragment = getCommunicationMessagesFragment();
            added = (fragment != null && fragment.addNewMessage(message));
            mCurrentCommunicationMode.processMessageInCurrentCommunicationBox(message);
        }

        //Handle sound when app is visible
        //When app not visible chatservice will handle it
        if (mUserManager.isSoundEnabled() && (!appIsNotVisible() && !isInCurrentCommunicationBox)) {
            mSoundEffectsPool.play(mNewMessageSoundId, 1.0f, 1.0f, 0, 0, 1);
        }
    }
}

From source file:nl.mpcjanssen.simpletask.Simpletask.java

@Override
protected void onNewIntent(@NotNull Intent intent) {
    super.onNewIntent(intent);
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        Intent currentIntent = getIntent();
        currentIntent.putExtra(SearchManager.QUERY, intent.getStringExtra(SearchManager.QUERY));
        setIntent(currentIntent);/*  www.j ava2 s . c o m*/
        options_menu.findItem(R.id.search).collapseActionView();
    } else if (CalendarContract.ACTION_HANDLE_CUSTOM_EVENT.equals(intent.getAction())) {
        Uri uri = Uri.parse(intent.getStringExtra(CalendarContract.EXTRA_CUSTOM_APP_URI));
        String search = uri.getLastPathSegment();
        // TODO: activate search
    } else if (intent.getExtras() != null) {
        // Only change intent if it actually contains a filter
        setIntent(intent);
    }
    Log.v(TAG, "onNewIntent: " + intent);

}

From source file:org.awesomeapp.messenger.ui.ConversationDetailActivity.java

public void handleSendDelete(IChatSession session, Uri contentUri, String defaultType, boolean delete,
        boolean resizeImage, boolean importContent) {
    try {/* w w w .j  av  a2  s.c  om*/

        // import
        SystemServices.FileInfo info = SystemServices.getFileInfoFromURI(this, contentUri);

        if (info.type == null)
            info.type = defaultType;

        String sessionId = mConvoView.getChatId() + "";

        Uri vfsUri;
        if (resizeImage)
            vfsUri = SecureMediaStore.resizeAndImportImage(this, sessionId, contentUri, info.type);
        else if (importContent) {

            if (contentUri.getScheme() == null || contentUri.getScheme().equals("assets"))
                vfsUri = SecureMediaStore.importContent(sessionId, info.path,
                        getResources().getAssets().open(info.path));
            else if (contentUri.getScheme().startsWith("http")) {
                vfsUri = SecureMediaStore.importContent(sessionId, contentUri.getLastPathSegment(),
                        new URL(contentUri.toString()).openConnection().getInputStream());
            } else
                vfsUri = SecureMediaStore.importContent(sessionId, info.path);
        } else {
            vfsUri = contentUri;
        }

        // send
        boolean sent = handleSendData(session, vfsUri, info.type);
        if (!sent) {
            // not deleting if not sent
            return;
        }
        // autu delete
        if (delete) {
            boolean deleted = delete(contentUri);
            if (!deleted) {
                throw new IOException("Error deleting " + contentUri);
            }
        }
    } catch (Exception e) {
        //  Toast.makeText(this, "Error sending file", Toast.LENGTH_LONG).show(); // TODO i18n
        Log.e(ImApp.LOG_TAG, "error sending file", e);
    }
}

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

@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
    int nbRowsDeleted;

    switch (URI_MATCHER.match(uri)) {
    // Delete all group-data links
    case CatalogContract.Provider.CODE_GROUP:

        // group/*from   w w w.  ja v a 2  s .  c  om*/
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataLinkGroup.TABLE_NAME, null, null);

        // data
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataSimple.TABLE_NAME, null, null);

        // details
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataDetails.TABLE_NAME, null, null);

        break;

    // Delete a particular group-data link
    case CatalogContract.Provider.CODE_GROUP_ID:
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase().delete(
                CatalogContract.DataBaseDataLinkGroup.TABLE_NAME,
                CatalogContract.DataBaseDataLinkGroup.ATT_GROUP_ID + "=?",
                new String[] { uri.getLastPathSegment() });

        break;

    // Delete all data
    case CatalogContract.Provider.CODE_DATA:
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataSimple.TABLE_NAME, null, null);
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataLinkGroup.TABLE_NAME, null, null);
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, null, null);

        break;

    // Delete all data details
    case CatalogContract.Provider.CODE_DATA_DETAILS:
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataDetails.TABLE_NAME, null, null);
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseDataLinkGroup.TABLE_NAME, null, null);
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase()
                .delete(CatalogContract.DataBaseSyncStatusGroup.TABLE_NAME, null, null);

        break;

    // Delete a data
    case CatalogContract.Provider.CODE_DATA_ID:

        // data
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase().delete(
                CatalogContract.DataBaseDataSimple.TABLE_NAME, CatalogContract.DataBaseData.ATT_DATA_ID + "=?",
                new String[] { uri.getLastPathSegment() });

        // group link
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase().delete(
                CatalogContract.DataBaseDataLinkGroup.TABLE_NAME,
                CatalogContract.DataBaseDataLinkGroup.ATT_DATA_ID + "=?",
                new String[] { uri.getLastPathSegment() });

        break;

    // Delete a data
    case CatalogContract.Provider.CODE_DATA_DETAILS_ID:

        // data
        nbRowsDeleted = mDatabaseHelper.getWritableDatabase().delete(
                CatalogContract.DataBaseDataDetails.TABLE_NAME, CatalogContract.DataBaseData.ATT_DATA_ID + "=?",
                new String[] { uri.getLastPathSegment() });

        // group link
        nbRowsDeleted += mDatabaseHelper.getWritableDatabase().delete(
                CatalogContract.DataBaseDataLinkGroup.TABLE_NAME,
                CatalogContract.DataBaseDataLinkGroup.ATT_DATA_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 nbRowsDeleted;
}

From source file:org.jared.synodroid.ds.protocol.v32.DSHandlerDSM32.java

public byte[] generateMultipart(Uri uriP, String shared) throws Exception {
    if (uriP.getPath() != null) {
        // Create the multipart
        MultipartBuilder builder = new MultipartBuilder(BOUNDARY, DEBUG);

        // The upload_type's part
        builder.addPart(new Part("upload_type").setContent("torrent".getBytes()));
        // The upload_type's part
        builder.addPart(new Part("desttext").setContent(shared.getBytes()));
        // The direction's part
        builder.addPart(new Part("direction").setContent("ASC".getBytes()));
        // The field's part
        builder.addPart(new Part("field").setContent("task_id".getBytes()));

        // The torrent's part
        Part filePart = new Part("torrent");
        filePart.addExtra("filename", uriP.getLastPathSegment());
        if (uriP.getPath().toLowerCase().endsWith("nzb")) {
            filePart.setContentType("application/octet-stream");
        } else {//from  w w w . j  a  v a  2 s. c  o  m
            filePart.setContentType("application/x-bittorrent");
        }

        // Get the stream according to the Uri
        byte[] buffer = StreamFactory.getStream(uriP);

        // Set the content
        filePart.setContent(buffer);
        builder.addPart(filePart);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        builder.writeData(baos);
        return baos.toByteArray();
    }
    return null;
}

From source file:Main.java

/**
 * 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>//from  www.  jav a2s. c o m
 * 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.
 * @author paulburke
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 */
@SuppressLint("NewApi")
public static String getPath(final Context context, final Uri uri) {

    if (DEBUG)
        Log.d(TAG + " File -",
                "Authority: " + uri.getAuthority() + ", Fragment: " + uri.getFragment() + ", Port: "
                        + uri.getPort() + ", Query: " + uri.getQuery() + ", Scheme: " + uri.getScheme()
                        + ", Host: " + uri.getHost() + ", Segments: " + uri.getPathSegments().toString());

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        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:id.ridon.keude.AppDetailsData.java

/**
 * Attempt to extract the appId from the intent which launched this activity.
 * Various different intents could cause us to show this activity, such as:
 * <ul>// w w  w . ja  v a2s.c o m
 *     <li>market://details?id=[app_id]</li>
 *     <li>https://f-droid.org/app/[app_id]</li>
 *     <li>fdroid.app:[app_id]</li>
 * </ul>
 * @return May return null, if we couldn't find the appId. In this case, you will
 * probably want to do something drastic like finish the activity and show some
 * feedback to the user (this method will <em>not</em> do that, it will just return
 * null).
 */
private String getAppIdFromIntent() {
    Intent i = getIntent();
    Uri data = i.getData();
    String appId = null;
    if (data != null) {
        if (data.isHierarchical()) {
            if (data.getHost() != null && data.getHost().equals("details")) {
                // market://details?id=app.id
                appId = data.getQueryParameter("id");
            } else {
                // https://f-droid.org/app/app.id
                appId = data.getLastPathSegment();
                if (appId != null && appId.equals("app")) {
                    appId = null;
                }
            }
        } else {
            // fdroid.app:app.id
            appId = data.getEncodedSchemeSpecificPart();
        }
        Log.d(TAG, "AppDetails launched from link, for '" + appId + "'");
    } else if (!i.hasExtra(EXTRA_APPID)) {
        Log.e(TAG, "No application ID in AppDetails!?");
    } else {
        appId = i.getStringExtra(EXTRA_APPID);
    }
    return appId;
}

From source file:hku.fyp14017.blencode.ui.controller.SoundController.java

/**
 * 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.//from  w w w.ja  v  a2 s  .  c  om
 * <p/>
 * <p/>
 * solution according to:
 * http://stackoverflow.com/questions/19834842/android-gallery-on-kitkat-returns-different-uri
 * -for-intent-action-get-content
 * 
 * @author paulburke
 */
@TargetApi(19)
private static String getPathForVersionAboveEqualsVersion19(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];
            }

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