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.sumatone.cloud.securecloud.Fragments.UploadFragment.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  a2s.c o  m
 *
 * @param context The context.
 * @param uri     The Uri to query.
 * @author paulburke
 */

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);
            Log.d("isKitkat-isExt", docId);
            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);

            Log.d("isKitkat-isDownload", id);
            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);
            Log.d("isKitkat-isMedia", docId);
            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)) {
            Log.d("isGPhoto", String.valueOf(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:uk.org.ngo.squeezer.service.SqueezeService.java

/**
 * Tries to get the path relative to the server music library.
 * <p>//  w ww .  j  a v  a2s .co m
 * If this is not possible resort to the last path segment of the server path.
 * In both cases replace dangerous characters by safe ones.
 */
private String getLocalFile(@NonNull Uri serverUrl) {
    String serverPath = serverUrl.getPath();
    String mediaDir = null;
    String path = null;
    for (String dir : cli.getMediaDirs()) {
        if (serverPath.startsWith(dir)) {
            mediaDir = dir;
            break;
        }
    }
    if (mediaDir != null)
        path = serverPath.substring(mediaDir.length(), serverPath.length());
    else
        path = serverUrl.getLastPathSegment();

    // Convert VFAT-unfriendly characters to "_".
    return path.replaceAll("[?<>\\\\:*|\"]", "_");
}

From source file:com.tct.mail.providers.Attachment.java

public static String getPath(final Context context, final Uri uri) {
    // DocumentProvider
    if (DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }/*from   w w  w.j  a va 2s. 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:edu.stanford.mobisocial.dungbeetle.DBHelper.java

public void markOrDeleteFeedObjs(Uri feedUri, long[] hashes, boolean force) {
    StringBuilder hashBuilder = new StringBuilder();
    for (long hash : hashes) {
        hashBuilder.append(",").append(hash);
    }/*from ww w.jav  a 2s  . c o  m*/
    String hashList = "(" + hashBuilder.substring(1) + ")";
    String feedName = feedUri.getLastPathSegment();

    final String FEED = DbObject.FEED_NAME;
    final String CONTACT = DbObject.CONTACT_ID;
    final String HASH = DbObject.HASH;

    if (force) {
        String[] selectionArgs = new String[] { feedName };
        getWritableDatabase().delete(DbObject.TABLE, HASH + " in " + hashList + " AND " + FEED + " = ?",
                selectionArgs);
    } else {
        String[] selectionArgs = new String[] { Long.toString(Contact.MY_ID), feedName };
        getWritableDatabase().delete(DbObject.TABLE,
                CONTACT + " != ? AND " + HASH + " in " + hashList + " AND " + FEED + " = ?", selectionArgs);

        ContentValues cv = new ContentValues();
        cv.put(DbObject.DELETED, 1);
        getWritableDatabase().update(DbObject.TABLE, cv,
                CONTACT + " = ? AND " + HASH + " in " + hashList + " AND " + FEED + " = ?", selectionArgs);
    }

    /*
     * Update the feed modification in case the latest obj was deleted.
     */
    long objId = getFeedLastVisibleId(feedName);
    ContentValues modifiedCv = new ContentValues();
    modifiedCv.put(Group.LAST_UPDATED, new Date().getTime());
    modifiedCv.put(Group.LAST_OBJECT_ID, objId);
    int rows = getWritableDatabase().update(Group.TABLE, modifiedCv, Group.FEED_NAME + " = ?",
            new String[] { feedName });
    Log.d(TAG, "Updating obj on " + feedName + " with " + objId + ", set " + rows);
    mContext.getContentResolver().notifyChange(Feed.feedListUri(), null);
}

From source file:com.iceteck.silicompressorr.FileUtils.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 w w  w .j  a v  a 2 s .  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.
 * @see #isLocal(String)
 * @see #getFile(Context, Uri)
 * @author paulburke
 */
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 (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && 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.nextgis.ngm_clink_monitoring.fragments.CreateObjectFragment.java

protected void createObjectTask() throws IOException {
    GISApplication app = (GISApplication) getActivity().getApplication();

    Uri uri = Uri.parse("content://" + FoclSettingsConstantsUI.AUTHORITY + "/" + mObjectLayerName);
    Log.d(TAG, "CreateObjectFragment, createObject(), uri: " + uri.toString());

    ContentValues values = new ContentValues();

    long builtDate = mAccurateLocation.getTime() + app.getGpsTimeOffset();
    values.put(FoclConstants.FIELD_BUILT_DATE, builtDate);
    Log.d(TAG, "CreateObjectFragment, createObject(), builtDate: " + builtDate);

    String descriptionText = mDescription.getText().toString();
    values.put(FoclConstants.FIELD_DESCRIPTION, descriptionText);
    Log.d(TAG, "CreateObjectFragment, createObject(), descriptionText: " + descriptionText);

    try {//from  w  w  w  . java  2s  . c o m
        GeoPoint pt = new GeoPoint(mAccurateLocation.getLongitude(), mAccurateLocation.getLatitude());
        pt.setCRS(CRS_WGS84);
        pt.project(CRS_WEB_MERCATOR);
        GeoMultiPoint mpt = new GeoMultiPoint();
        mpt.add(pt);
        values.put(FIELD_GEOM, mpt.toBlob());
        Log.d(TAG, "CreateObjectFragment, createObject(), pt: " + pt.toString());

    } catch (IOException e) {
        e.printStackTrace();
    }

    String value;

    switch (mFoclStructLayerType) {
    case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CABLE_POINT:
        if (0 == mObjectCount || mNewStartPoint) {
            values.put(FIELD_START_POINT, true);
        }
        value = mLayingMethod.getValue();
        values.put(FIELD_LAYING_METHOD, value);
        Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_LAYING_METHOD: " + value);
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_FOSC:
        value = mFoscType.getValue();
        values.put(FIELD_FOSC_TYPE, value);
        Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_FOSC_TYPE: " + value);

        value = mFoscPlacement.getValue();
        values.put(FIELD_FOSC_PLACEMENT, value);
        Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_FOSC_PLACEMENT: " + value);
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_OPTICAL_CROSS:
        //                value = mOpticalCrossType.getValue();
        //                values.put(FIELD_OPTICAL_CROSS_TYPE, value);
        //                Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_OPTICAL_CROSS_TYPE: " + value);
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_ACCESS_POINT:
        break;

    case FoclConstants.LAYERTYPE_FOCL_REAL_SPECIAL_TRANSITION_POINT:
        value = mSpecialLayingMethod.getValue();
        values.put(FIELD_SPECIAL_LAYING_METHOD, value);
        Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_SPECIAL_LAYING_METHOD: " + value);

        value = mMarkType.getValue();
        values.put(FIELD_MARK_TYPE, value);
        Log.d(TAG, "CreateObjectFragment, createObject(), FIELD_MARK_TYPE: " + value);
        break;
    }

    Uri result = getActivity().getContentResolver().insert(uri, values);

    if (result == null) {
        Log.d(TAG, "CreateObjectFragment, createObject(), Layer: " + mObjectLayerName + ", insert FAILED");
        throw new IOException(getString(R.string.object_creation_error));

    } else {

        if (mFoclStruct.getStatus().equals(FoclConstants.FIELD_VALUE_STATUS_PROJECT)) {
            mFoclStruct.setStatus(FoclConstants.FIELD_VALUE_STATUS_IN_PROGRESS);
            mFoclStruct.setIsStatusChanged(true);
            mFoclStruct.setStatusUpdateTime(builtDate);
            mFoclStruct.save();
        }

        mObjectId = Long.parseLong(result.getLastPathSegment());
        Log.d(TAG, "CreateObjectFragment, createObject(), Layer: " + mObjectLayerName + ", id: " + mObjectId
                + ", insert result: " + result);
        writePhotoAttaches();
    }

    try {
        mLogcatWriter.writeLogcat(app.getMainLogcatFilePath());
        mLogcatWriter.stopLogcat();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.vegnab.vegnab.MainVNActivity.java

void logPurchaseActivity(ContentValues cv) {
    // create a new record with whatever fields are provided in ContentValues
    Uri uri, purchUri = Uri.withAppendedPath(ContentProvider_VegNab.CONTENT_URI, "purchases");
    ContentResolver rs = getContentResolver();
    // create a new record
    uri = rs.insert(purchUri, cv);//from   w w w . j ava  2  s  .  c  o  m
    mNewPurcRecId = Long.parseLong(uri.getLastPathSegment());
    if (LDebug.ON)
        Log.d(LOG_TAG, "mNewPurcRecId of new record stored in DB: " + mNewPurcRecId);
}

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

private Cursor queryArtwork(@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;
    }//  w w  w .ja  va 2 s  .c  o m
    final SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
    qb.setTables(MuzeiContract.Artwork.TABLE_NAME + " INNER JOIN " + MuzeiContract.Sources.TABLE_NAME + " ON "
            + MuzeiContract.Artwork.TABLE_NAME + "." + MuzeiContract.Artwork.COLUMN_NAME_SOURCE_COMPONENT_NAME
            + "=" + MuzeiContract.Sources.TABLE_NAME + "." + MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME);
    qb.setProjectionMap(allArtworkColumnProjectionMap);
    final SQLiteDatabase db = databaseHelper.getReadableDatabase();
    if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) {
        // If the incoming URI is for a single source identified by its ID, appends "_ID = <artworkId>"
        // to the where clause, so that it selects that single piece of artwork
        qb.appendWhere(
                MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + "=" + uri.getLastPathSegment());
    }
    String orderBy;
    if (TextUtils.isEmpty(sortOrder))
        orderBy = MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED + " DESC, "
                + MuzeiContract.Artwork.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.android.messaging.mmslib.pdu.PduPersister.java

/**
 * Update all parts of a PDU.//from  w  ww  .java 2 s .c  o  m
 *
 * @param uri            The PDU which need to be updated.
 * @param body           New message body of the PDU.
 * @param preOpenedFiles if not null, a map of preopened InputStreams for the parts.
 * @throws MmsException Bad URI or updating failed.
 */
public void updateParts(final Uri uri, final PduBody body, final Map<Uri, InputStream> preOpenedFiles)
        throws MmsException {
    try {
        PduCacheEntry cacheEntry;
        synchronized (PDU_CACHE_INSTANCE) {
            if (PDU_CACHE_INSTANCE.isUpdating(uri)) {
                if (LOCAL_LOGV) {
                    LogUtil.v(TAG, "updateParts: " + uri + " blocked by isUpdating()");
                }
                try {
                    PDU_CACHE_INSTANCE.wait();
                } catch (final InterruptedException e) {
                    Log.e(TAG, "updateParts: ", e);
                }
                cacheEntry = PDU_CACHE_INSTANCE.get(uri);
                if (cacheEntry != null) {
                    ((MultimediaMessagePdu) cacheEntry.getPdu()).setBody(body);
                }
            }
            // Tell the cache to indicate to other callers that this item
            // is currently being updated.
            PDU_CACHE_INSTANCE.setUpdating(uri, true);
        }

        final ArrayList<PduPart> toBeCreated = new ArrayList<PduPart>();
        final ArrayMap<Uri, PduPart> toBeUpdated = new ArrayMap<Uri, PduPart>();

        final int partsNum = body.getPartsNum();
        final StringBuilder filter = new StringBuilder().append('(');
        for (int i = 0; i < partsNum; i++) {
            final PduPart part = body.getPart(i);
            final Uri partUri = part.getDataUri();
            if ((partUri == null) || !partUri.getAuthority().startsWith("mms")) {
                toBeCreated.add(part);
            } else {
                toBeUpdated.put(partUri, part);

                // Don't use 'i > 0' to determine whether we should append
                // 'AND' since 'i = 0' may be skipped in another branch.
                if (filter.length() > 1) {
                    filter.append(" AND ");
                }

                filter.append(Part._ID);
                filter.append("!=");
                DatabaseUtils.appendEscapedSQLString(filter, partUri.getLastPathSegment());
            }
        }
        filter.append(')');

        final long msgId = ContentUris.parseId(uri);

        // Remove the parts which doesn't exist anymore.
        SqliteWrapper.delete(mContext, mContentResolver, Uri.parse(Mms.CONTENT_URI + "/" + msgId + "/part"),
                filter.length() > 2 ? filter.toString() : null, null);

        // Create new parts which didn't exist before.
        for (final PduPart part : toBeCreated) {
            persistPart(part, msgId, preOpenedFiles);
        }

        // Update the modified parts.
        for (final Map.Entry<Uri, PduPart> e : toBeUpdated.entrySet()) {
            updatePart(e.getKey(), e.getValue(), preOpenedFiles);
        }
    } finally {
        synchronized (PDU_CACHE_INSTANCE) {
            PDU_CACHE_INSTANCE.setUpdating(uri, false);
            PDU_CACHE_INSTANCE.notifyAll();
        }
    }
}

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

private int updateSource(@NonNull final Uri uri, final ContentValues values, final String selection,
        final String[] selectionArgs) {
    Context context = getContext();
    if (context == null) {
        return 0;
    }/*from w ww  . j  a  va2s . c o m*/

    // Only Muzei can set the IS_SELECTED field
    if (values.containsKey(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED)) {
        if (!context.getPackageName().equals(getCallingPackage())) {
            Log.w(TAG, "Only Muzei can set the " + MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED
                    + " column. Ignoring the value in " + values);
            values.remove(MuzeiContract.Sources.COLUMN_NAME_IS_SELECTED);
        }
    }

    final SQLiteDatabase db = databaseHelper.getWritableDatabase();
    String finalWhere = selection;
    String[] finalSelectionArgs = selectionArgs;
    if (MuzeiProvider.uriMatcher.match(uri) == SOURCE_ID) {
        // If the incoming URI matches a single source ID, does the update based on the incoming data, but
        // modifies the where clause to restrict it to the particular source ID.
        finalWhere = DatabaseUtils.concatenateWhere(finalWhere,
                BaseColumns._ID + " = " + uri.getLastPathSegment());
    }
    String callingPackageName = getCallingPackage();
    if (!context.getPackageName().equals(callingPackageName)) {
        // Only allow other apps to update their own source
        finalWhere = DatabaseUtils.concatenateWhere(finalWhere,
                MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME + " LIKE ?");
        finalSelectionArgs = DatabaseUtils.appendSelectionArgs(finalSelectionArgs,
                new String[] { callingPackageName + "/%" });
    }
    int count = db.update(MuzeiContract.Sources.TABLE_NAME, values, finalWhere, finalSelectionArgs);
    if (count > 0) {
        notifyChange(uri);
    } else if (values.containsKey(MuzeiContract.Sources.COLUMN_NAME_COMPONENT_NAME)) {
        insertSource(MuzeiContract.Sources.CONTENT_URI, values);
        count = 1;
    }
    return count;
}