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.catrobat.catroid.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 .  java  2  s  .  com*/
 * <p/>
 * <p/>
 * solution according to:
 * http://stackoverflow.com/questions/19834842/android-gallery-on-kitkat-returns-different-uri
 * -for-intent-action-get-content
 */
@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
        } else if (isDownloadsDocument(uri)) {
            // DownloadsProvider

            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);
        } else if (isMediaDocument(uri)) {
            // MediaProvider
            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);
        }
    } else if ("content".equalsIgnoreCase(uri.getScheme())) {
        // MediaStore (and general)

        // Return the remote address
        if (isGooglePhotosUri(uri)) {
            return uri.getLastPathSegment();
        }
        return getDataColumn(context, uri, null, null);
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        // File
        return uri.getPath();
    }

    return null;
}

From source file:org.odk.collect.android.utilities.MediaUtils.java

@SuppressLint("NewApi")
/**//from   ww w . j a  va2 s . c  o  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.google.android.apps.muzei.provider.MuzeiProvider.java

private Cursor querySource(@NonNull final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    ContentResolver contentResolver = getContext() != null ? getContext().getContentResolver() : null;
    if (contentResolver == null) {
        return null;
    }/* ww w  .j  av  a 2s. c om*/
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Sources.TABLE_NAME);
    qb.setProjectionMap(allSourcesColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == SOURCE_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <sourceId>"
        // to the where clause, so that it selects that single source
        qb.appendWhere(BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.DEFAULT_SORT_ORDER;
    else
        orderBy = sortOrder;
    final Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, orderBy, null);
    c.setNotificationUri(contentResolver, uri);
    return c;
}

From source file:com.futurologeek.smartcrossing.crop.CropImageActivity.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];
            }//w  w  w.j  a  va2s  .  co  m
        }
        // 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:de.vanita5.twittnuker.provider.TwidereDataProvider.java

@Override
public Cursor query(final Uri uri, final String[] projection, final String selection,
        final String[] selectionArgs, final String sortOrder) {
    try {/*from   w w w . j a  va  2  s . c om*/
        final int tableId = getTableId(uri);
        final String table = getTableNameById(tableId);
        switch (tableId) {
        case VIRTUAL_TABLE_ID_DATABASE_READY: {
            if (mDatabaseWrapper.isReady())
                return new MatrixCursor(projection != null ? projection : new String[0]);
            return null;
        }
        case VIRTUAL_TABLE_ID_ALL_PREFERENCES: {
            return getPreferencesCursor(mPreferences, null);
        }
        case VIRTUAL_TABLE_ID_PREFERENCES: {
            return getPreferencesCursor(mPreferences, uri.getLastPathSegment());
        }
        case VIRTUAL_TABLE_ID_DNS: {
            return getDNSCursor(uri.getLastPathSegment());
        }
        case VIRTUAL_TABLE_ID_CACHED_IMAGES: {
            return getCachedImageCursor(uri.getQueryParameter(QUERY_PARAM_URL));
        }
        case VIRTUAL_TABLE_ID_NOTIFICATIONS: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() == 2)
                return getNotificationsCursor(ParseUtils.parseInt(segments.get(1), -1));
            else
                return getNotificationsCursor();
        }
        case VIRTUAL_TABLE_ID_UNREAD_COUNTS: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() == 2)
                return getUnreadCountsCursor(ParseUtils.parseInt(segments.get(1), -1));
            else
                return getUnreadCountsCursor();
        }
        case VIRTUAL_TABLE_ID_UNREAD_COUNTS_BY_TYPE: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 3)
                return null;
            return getUnreadCountsCursorByType(segments.get(2));
        }
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 4)
                return null;
            final long accountId = ParseUtils.parseLong(segments.get(2));
            final long conversationId = ParseUtils.parseLong(segments.get(3));
            final SQLSelectQuery query = ConversationQueryBuilder.buildByConversationId(projection, accountId,
                    conversationId, selection, sortOrder);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, DirectMessages.CONTENT_URI);
            return c;
        }
        case TABLE_ID_DIRECT_MESSAGES_CONVERSATION_SCREEN_NAME: {
            final List<String> segments = uri.getPathSegments();
            if (segments.size() != 4)
                return null;
            final long accountId = ParseUtils.parseLong(segments.get(2));
            final String screenName = segments.get(3);
            final SQLSelectQuery query = ConversationQueryBuilder.buildByScreenName(projection, accountId,
                    screenName, selection, sortOrder);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, DirectMessages.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_RELATIONSHIP: {
            final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1);
            final SQLSelectQuery query = CachedUsersQueryBuilder.buildWithRelationship(projection, selection,
                    sortOrder, accountId);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, CachedUsers.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_CACHED_USERS_WITH_SCORE: {
            final long accountId = ParseUtils.parseLong(uri.getLastPathSegment(), -1);
            final SQLSelectQuery query = CachedUsersQueryBuilder.buildWithScore(projection, selection,
                    sortOrder, accountId);
            final Cursor c = mDatabaseWrapper.rawQuery(query.getSQL(), selectionArgs);
            setNotificationUri(c, CachedUsers.CONTENT_URI);
            return c;
        }
        case VIRTUAL_TABLE_ID_DRAFTS_UNSENT: {
            final TwittnukerApplication app = TwittnukerApplication.getInstance(getContext());
            final AsyncTwitterWrapper twitter = app.getTwitterWrapper();
            final RawItemArray sendingIds = new RawItemArray(twitter.getSendingDraftIds());
            final Expression where;
            if (selection != null) {
                where = Expression.and(new Expression(selection),
                        Expression.notIn(new Column(Drafts._ID), sendingIds));
            } else {
                where = Expression.and(Expression.notIn(new Column(Drafts._ID), sendingIds));
            }
            final Cursor c = mDatabaseWrapper.query(Drafts.TABLE_NAME, projection, where.getSQL(),
                    selectionArgs, null, null, sortOrder);
            setNotificationUri(c, getNotificationUri(tableId, uri));
            return c;
        }
        }
        if (table == null)
            return null;
        final Cursor c = mDatabaseWrapper.query(table, projection, selection, selectionArgs, null, null,
                sortOrder);
        setNotificationUri(c, getNotificationUri(tableId, uri));
        return c;
    } catch (final SQLException e) {
        throw new IllegalStateException(e);
    }
}

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

public void upload(Uri uriP) throws Exception {
    // If we are logged on
    if (server.isConnected()) {
        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(getSharedDirectory(false).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 {
                filePart.setContentType("application/x-bittorrent");
            }//www.  j a  v  a2 s. c  om

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

            // Set the content
            filePart.setContent(buffer);
            builder.addPart(filePart);
            // Execute
            JSONObject json;
            synchronized (server) {
                json = server.sendMultiPart(DM_URI_NEW, builder);
            }
            if (json != null) {
                boolean success = json.getBoolean("success");
                // If successful then build details list
                if (!success) {
                    String reason = "";
                    if (json.has("reason")) {
                        reason = json.getString("reason");
                    } else if (json.has("errno")) {
                        JSONObject err = json.getJSONObject("errno");
                        reason = err.getString("key");
                    }
                    throw new DSMException(reason);
                }
            }
        }
    }
}

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

private int deleteSource(@NonNull final Uri uri, final String selection, final String[] selectionArgs) {
    // Opens the database object in "write" mode.
    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    int count;//  ww  w.ja v  a  2s .c  o m
    // Does the delete based on the incoming URI pattern.
    switch (MuzeiProvider.uriMatcher.match(uri)) {
    case SOURCES:
        // If the incoming pattern matches the general pattern for
        // sources, does a delete based on the incoming "where"
        // column and arguments.
        count = db.delete(MuzeiContract.Sources.TABLE_NAME, selection, selectionArgs);
        break;
    case SOURCE_ID:
        // If the incoming URI matches a single source ID, does the
        // delete based on the incoming data, but modifies the where
        // clause to restrict it to the particular source ID.
        String finalWhere = BaseColumns._ID + " = " + uri.getLastPathSegment();
        // If there were additional selection criteria, append them to the final WHERE clause
        if (selection != null)
            finalWhere = finalWhere + " AND " + selection;
        count = db.delete(MuzeiContract.Sources.TABLE_NAME, finalWhere, selectionArgs);
        break;
    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }
    if (count > 0) {
        notifyChange(uri);
    }
    return count;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

public Cursor queryFeedMembers(String[] projection, String selection, String[] selectionArgs, Uri feedUri,
        String appId) {//from  w w  w . j av  a  2 s .  c o m
    // TODO: Check appId against feed?

    String feedName = feedUri.getLastPathSegment();
    int sep = feedName.indexOf(':');
    if (sep >= 0) {
        feedName = feedName.substring(0, sep);
    }
    FeedType type = Feed.typeOf(feedUri);
    if (feedName != null && !feedName.equals(Feed.FEED_NAME_GLOBAL)) {
        String feedInnerQuery;
        String[] feedInnerArgs = null;
        switch (type) {
        case APP:
            feedInnerQuery = new StringBuilder().append(" SELECT DISTINCT " + DbObject.CONTACT_ID)
                    .append(" FROM " + DbObject.TABLE).append(" WHERE " + DbObject.APP_ID + " = ?").toString();
            feedInnerArgs = new String[] { appId };
            break;
        default:
            feedInnerQuery = new StringBuilder().append("SELECT M." + GroupMember.CONTACT_ID)
                    .append(" FROM " + GroupMember.TABLE + " M, ").append(Group.TABLE + " G").append(" WHERE ")
                    .append("M." + GroupMember.GROUP_ID + " = G." + Group._ID).append(" AND ")
                    .append("G." + Group.FEED_NAME + " = ?").toString();
            feedInnerArgs = new String[] { feedName };
            break;
        }
        String forFeed = Contact._ID + " IN ( " + feedInnerQuery + ")";
        selection = andClauses(selection, forFeed);
        selectionArgs = andArguments(selectionArgs, feedInnerArgs);
    }

    String groupBy = null;
    String having = null;
    String orderBy = null;
    return getReadableDatabase().query(Contact.TABLE, projection, selection, selectionArgs, groupBy, having,
            orderBy);
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

public void deleteObjByHash(Uri feedUri, long hash) {
    getWritableDatabase().delete(DbObject.TABLE, DbObject.HASH + " = ? AND " + DbObject.FEED_NAME + " = ?",
            new String[] { String.valueOf(hash), feedUri.getLastPathSegment() });
}

From source file:org.thomnichols.android.gmarks.GmarksProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    //        Log.d(TAG, "Managed query: " + uri);
    String groupBy = null;//from   w w  w  . j ava2  s.  com
    String orderBy = null;
    String limit = null;
    switch (sUriMatcher.match(uri)) {
    case BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);

        String labelID = uri.getQueryParameter("label_id");
        if (labelID != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelID });
        }
        break;

    case BOOKMARK_SEARCH_URI:
    case BOOKMARK_SEARCH_SUGGEST_URI:
        String query = null;
        if (sUriMatcher.match(uri) == BOOKMARK_SEARCH_SUGGEST_URI) {
            qb.setProjectionMap(searchSuggestProjectionMap);
            // path looks like "search_suggest_query/[query]?limit=50
            query = uri.getLastPathSegment();
            limit = uri.getQueryParameter("limit");
            if (sortOrder == null)
                sortOrder = Bookmark.Columns.SORT_MODIFIED;
        } else
            query = uri.getQueryParameter("q");

        if (query != null) {
            qb.setTables("bookmarks join bookmarks_FTS on bookmarks._id = bookmarks_FTS.docid");
            qb.appendWhere("bookmarks_FTS MATCH ?");
            if (selectionArgs == null)
                selectionArgs = new String[] { query };
            else
                selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { query });
        } else if (selectionArgs == null || selectionArgs.length < 1)
            throw new IllegalArgumentException("No search criteria given for query!");
        break;

    case BOOKMARK_ID_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(bookmarksProjectionMap);
        qb.appendWhere(Bookmark.Columns._ID + "=" + uri.getPathSegments().get(1));
        break;

    case LABELS_URI:
        qb.setTables("labels join bookmark_labels on labels._id = bookmark_labels.label_id");
        groupBy = "label";
        if (sortOrder == null)
            sortOrder = Label.Columns.DEFAULT_SORT_ORDER;
        qb.setProjectionMap(labelsProjectionMap);
        break;

    case LIVE_FOLDER_BOOKMARKS_URI:
        qb.setTables(BOOKMARKS_TABLE_NAME);
        qb.setProjectionMap(sLiveFolderProjectionMap);
        String labelId = uri.getQueryParameter("label_id");
        if (labelId != null) {
            qb.setTables("bookmarks join bookmark_labels on bookmarks._id = bookmark_labels.bookmark_id");
            qb.appendWhere("bookmark_labels.label_id=?");
            selectionArgs = (String[]) ArrayUtils.addAll(selectionArgs, new String[] { labelId });
        }
        sortOrder = "modified DESC"; // for some reason this gets set to 'name ASC'
        break;

    case BOOKMARK_LISTS_URI:
        qb.setTables(BookmarkList.TABLE_NAME);
        qb.setProjectionMap(listsProjectionMap);
        if (sortOrder == null)
            sortOrder = BookmarkList.Columns.DEFAULT_SORT_ORDER;
        String type = uri.getQueryParameter(BookmarkList.PARAM_CATEGORY);
        if (BookmarkList.LISTS_PRIVATE.equals(type))
            qb.appendWhere("owned=1");
        else if (BookmarkList.LISTS_SHARED.equals(type))
            qb.appendWhere("shared=1");
        else if (BookmarkList.LISTS_PUBLIC.equals(type))
            qb.appendWhere("publshed=1");
        break;

    default:
        throw new IllegalArgumentException("Unknown URI " + uri);
    }

    // If no sort order is specified use the default
    if (TextUtils.isEmpty(sortOrder)) {
        orderBy = Bookmark.Columns.DEFAULT_SORT_ORDER;
    } else {
        orderBy = sortOrder;
    }

    // Get the database and run the query
    SQLiteDatabase db = dbHelper.getReadableDatabase();
    Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, orderBy, limit);

    // Tell the cursor what uri to watch, so it knows when its source data changes
    c.setNotificationUri(getContext().getContentResolver(), uri);
    return c;
}