Example usage for android.content ContentUris withAppendedId

List of usage examples for android.content ContentUris withAppendedId

Introduction

In this page you can find the example usage for android.content ContentUris withAppendedId.

Prototype

public static Uri withAppendedId(Uri contentUri, long id) 

Source Link

Document

Appends the given ID to the end of the path.

Usage

From source file:com.android.emailcommon.utility.AttachmentUtilities.java

/**
 * In support of deleting a message, find all attachments and delete associated attachment
 * files.//  w w  w  .  j  av  a 2  s .  c  o m
 * @param context
 * @param accountId the account for the message
 * @param messageId the message
 */
public static void deleteAllAttachmentFiles(Context context, long accountId, long messageId) {
    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor c = context.getContentResolver().query(uri, Attachment.ID_PROJECTION, null, null, null);
    try {
        while (c.moveToNext()) {
            long attachmentId = c.getLong(Attachment.ID_PROJECTION_COLUMN);
            File attachmentFile = getAttachmentFilename(context, accountId, attachmentId);
            // Note, delete() throws no exceptions for basic FS errors (e.g. file not found)
            // it just returns false, which we ignore, and proceed to the next file.
            // This entire loop is best-effort only.
            attachmentFile.delete();
        }
    } finally {
        c.close();
    }
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
* From:// w  w  w  . j  a  va 2s  .  c om
* https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
*
* MODIFIED FOR MAGE:
*
* - Removed LocalStorageProvider references
* - Added and modified to use isDocumentUri and getDocumentId methods with KITKAT target api annotation
* - Added ExternalStorageProvider SD card handler section in the getPath method
* - Added getFileIfExists method
*
 * 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.
* @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 && isDocumentUri(context, uri)) {

        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // Handle SD cards
            File file = getFileIfExists("/storage/extSdCard", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/usbcard1", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }
            file = getFileIfExists("/storage/sdcard0", split[1]);
            if (file != null) {
                return file.getAbsolutePath();
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = 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 = 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.chen.emailcommon.utility.AttachmentUtilities.java

/**
 * In support of deleting a message, find all attachments and delete associated cached
 * attachment files./*from   w  w  w.j ava  2 s. co m*/
 * @param context
 * @param accountId the account for the message
 * @param messageId the message
 */
public static void deleteAllCachedAttachmentFiles(Context context, long accountId, long messageId) {
    final Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    final Cursor c = context.getContentResolver().query(uri, ATTACHMENT_CACHED_FILE_PROJECTION, null, null,
            null);
    try {
        while (c.moveToNext()) {
            final String fileName = c.getString(0);
            if (!TextUtils.isEmpty(fileName)) {
                final File cachedFile = new File(fileName);
                // Note, delete() throws no exceptions for basic FS errors (e.g. file not found)
                // it just returns false, which we ignore, and proceed to the next file.
                // This entire loop is best-effort only.
                cachedFile.delete();
            }
        }
    } finally {
        c.close();
    }
}

From source file:com.nnm.smsviet.Message.java

/**
 * Fetch MMS parts./*from  w w  w.  ja  va  2 s  . c  o m*/
 * 
 * @param context
 *            {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(this.id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);
        Log.d(TAG, "part: " + pid + " " + ct);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        try {
            is = cr.openInputStream(uri);
        } catch (IOException e) {
            Log.e(TAG, "Failed to load part data", e);
        }
        if (is == null) {
            Log.i(TAG, "InputStream for part " + pid + " is null");
            if (iText >= 0 && ct.startsWith("text/")) {
                this.body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            this.picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            this.contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            this.picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            this.contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            this.body = this.fetchPart(is);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                Log.e(TAG, "Failed to close stream", e);
            } // Ignore
        }
    } while (cursor.moveToNext());
}

From source file:com.fututel.ui.account.AccountsEditListFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    // Use custom drag and drop view
    View v = inflater.inflate(R.layout.accounts_edit_list, container, false);

    final DragnDropListView lv = (DragnDropListView) v.findViewById(android.R.id.list);

    lv.setGrabberId(R.id.grabber);/*from  w w w  . ja v  a  2s  . c om*/
    // Setup the drop listener
    lv.setOnDropListener(new DropListener() {
        @Override
        public void drop(int from, int to) {
            Log.d(THIS_FILE, "Drop from " + from + " to " + to);
            int hvC = lv.getHeaderViewsCount();
            from = Math.max(0, from - hvC);
            to = Math.max(0, to - hvC);

            int i;
            // First of all, compute what we get before move
            ArrayList<Long> orderedList = new ArrayList<Long>();
            CursorAdapter ad = (CursorAdapter) getListAdapter();
            for (i = 0; i < ad.getCount(); i++) {
                orderedList.add(ad.getItemId(i));
            }
            // Then, invert in the current list the two items ids
            Long moved = orderedList.remove(from);
            orderedList.add(to, moved);

            // Finally save that in db
            if (getActivity() != null) {
                ContentResolver cr = getActivity().getContentResolver();
                for (i = 0; i < orderedList.size(); i++) {
                    Uri uri = ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, orderedList.get(i));
                    ContentValues cv = new ContentValues();
                    cv.put(SipProfile.FIELD_PRIORITY, i);
                    cr.update(uri, cv, null, null);
                }
            }
        }
    });

    OnClickListener addClickButtonListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            onClickAddAccount();
        }
    };
    // Header view
    //mHeaderView = inflater.inflate(R.layout.generic_add_header_list, container, false);
    //mHeaderView.setOnClickListener(addClickButtonListener); //rangdong

    // Empty view
    Button bt = (Button) v.findViewById(android.R.id.empty);
    bt.setOnClickListener(addClickButtonListener);

    return v;
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Fetch MMS parts./*  w  w w  . j  a v a 2s. c  om*/
 *
 * @param context {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        if (uri == null) {

            continue;
        }
        try {
            is = cr.openInputStream(uri);
        } catch (IOException | NullPointerException e) {

        }
        if (is == null) {

            if (iText >= 0 && ct != null && ct.startsWith("text/")) {
                body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            body = fetchPart(is);
        }

        try {
            is.close();
        } catch (IOException e) {
        } // Ignore
    } while (cursor.moveToNext());
}

From source file:com.intel.xdk.camera.Camera.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.//  w  ww .  j  a va  2  s.  c om
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
@SuppressLint("NewApi")
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];
            }

            // 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 getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:edu.cens.loci.ui.PlaceViewActivity.java

private void updateListForSuggestedPlace() {

    updatePlaceName();/*from  w  ww  .  ja va2  s.c  o m*/
    updateMapView(mDbUtils.getPlacePositionEstimate(mPlace.placeId));

    ArrayList<ViewEntry> items = new ArrayList<ViewEntry>();

    // recent visit time
    String recentVisitTime = getRecentVisitSubstring(); //"May 4, 3:00pm, 1hr";
    items.add(new ViewEntry(LIST_ACTION_VIEW_VISITS, R.drawable.ic_clock_strip_desk_clock, "View recent visits",
            recentVisitTime, null));

    String apsAbstract = "Not available";
    // wifis
    if (mPlace.wifis.size() > 0)
        //apsAbstract = getWifiInfoSubstring(5, mPlace.wifis.get(0).toJsonString());
        apsAbstract = mPlace.wifis.get(0).getWifiInfoSubstring(5);

    //String apsAbstract = getWifiInfoSubstring(5); //"CENSTemp, UCLAWAN, Go away this Wifi is mine and not yours";
    ViewEntry entry = new ViewEntry(LIST_ACTION_VIEW_WIFIS, R.drawable.ic_settings_wireless, "View Wi-Fi APs",
            apsAbstract, null);
    try {
        if (mPlace.wifis != null && mPlace.wifis.size() > 0)
            entry.extra_string = mPlace.wifis.get(0).toJsonObject().toString();
        else
            entry.extra_string = "";
    } catch (JSONException e) {
        MyLog.e(LociConfig.D.JSON, TAG, "updateListForSuggestedPlace: json failed.");
        entry.extra_string = "";
    }

    items.add(entry);

    // Add
    //Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT, ContentUris.withAppendedId(Places.CONTENT_URI, mPlace.placeId));
    Intent intent = new Intent(Intents.UI.ACTION_CREATE_OR_ADDTO_FROM_SUGGESTED_PLACE,
            ContentUris.withAppendedId(Places.CONTENT_URI, mPlace.placeId));
    intent.putExtra(UI.TITLE_EXTRA_KEY, "Places");
    //intent.setType(Places.CONTENT_TYPE);
    intent.putExtra(UI.FILTER_STATE_EXTRA_KEY, Constants.Intents.UI.FILTER_STATE_REGISTERED);
    intent.putExtra(UI.FILTER_TYPE_EXTRA_KEY,
            Constants.Intents.UI.FILTER_TYPE_GPS | Constants.Intents.UI.FILTER_TYPE_WIFI);
    if (mPlace.wifis == null || mPlace.wifis.size() == 0) {
        intent.putExtra(UI.LIST_ORDER_EXTRA_KEY, PlacesList.LIST_ORDER_TYPE_NAME);
    } else {
        intent.putExtra(UI.LIST_ORDER_EXTRA_KEY, PlacesList.LIST_ORDER_TYPE_WIFI_SIMILARITY);
        intent.putExtra(UI.LIST_ORDER_EXTRA_WIFI_KEY, mPlace.wifis.get(0).toJsonString());
    }
    items.add(new ViewEntry(LIST_ACTION_ADD, R.drawable.sym_action_add, "Add place", null, intent));

    // delete
    items.add(new ViewEntry(LIST_ACTION_DELETE, R.drawable.ic_menu_delete, "Delete suggestion", null,
            new Intent()));

    ViewEntryAdapter adapter = new ViewEntryAdapter(this, R.layout.place_view_list_item, items);
    mListView.setAdapter(adapter);
}

From source file:com.xorcode.andtweet.TweetListActivity.java

@Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);

    // Get the adapter context menu information
    AdapterView.AdapterContextMenuInfo info;
    try {/*from  w ww. ja  va 2 s.c  om*/
        info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    } catch (ClassCastException e) {
        Log.e(TAG, "bad menuInfo", e);
        return;
    }

    int m = 0;

    // Add menu items
    menu.add(0, CONTEXT_MENU_ITEM_REPLY, m++, R.string.menu_item_reply);
    menu.add(0, CONTEXT_MENU_ITEM_RETWEET, m++, R.string.menu_item_retweet);
    menu.add(0, CONTEXT_MENU_ITEM_SHARE, m++, R.string.menu_item_share);
    // menu.add(0, CONTEXT_MENU_ITEM_DIRECT_MESSAGE, m++,
    // R.string.menu_item_direct_message);
    // menu.add(0, CONTEXT_MENU_ITEM_UNFOLLOW, m++,
    // R.string.menu_item_unfollow);
    // menu.add(0, CONTEXT_MENU_ITEM_BLOCK, m++, R.string.menu_item_block);
    // menu.add(0, CONTEXT_MENU_ITEM_PROFILE, m++,
    // R.string.menu_item_view_profile);

    // Get the record for the currently selected item
    Uri uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, info.id);
    Cursor c = getContentResolver().query(uri,
            new String[] { Tweets._ID, Tweets.MESSAGE, Tweets.AUTHOR_ID, Tweets.FAVORITED }, null, null, null);
    try {
        c.moveToFirst();
        menu.setHeaderTitle(c.getString(c.getColumnIndex(Tweets.MESSAGE)));
        if (c.getInt(c.getColumnIndex(Tweets.FAVORITED)) == 1) {
            menu.add(0, CONTEXT_MENU_ITEM_DESTROY_FAVORITE, m++, R.string.menu_item_destroy_favorite);
        } else {
            menu.add(0, CONTEXT_MENU_ITEM_FAVORITE, m++, R.string.menu_item_favorite);
        }
        if (MyPreferences.getDefaultSharedPreferences().getString(MyPreferences.KEY_TWITTER_USERNAME, null)
                .equals(c.getString(c.getColumnIndex(Tweets.AUTHOR_ID)))) {
            menu.add(0, CONTEXT_MENU_ITEM_DESTROY_STATUS, m++, R.string.menu_item_destroy_status);
        }
    } catch (Exception e) {
        Log.e(TAG, "onCreateContextMenu: " + e.toString());
    } finally {
        if (c != null && !c.isClosed())
            c.close();
    }
}

From source file:com.almalence.googsharing.Thumbnail.java

public static Media getLastImageThumbnail(ContentResolver resolver) {
    Media internalMedia = null;//from  w w w.j  ava2  s .com
    Media externalMedia = null;

    String name = getName();

    try {
        Uri baseUri = Images.Media.INTERNAL_CONTENT_URI;

        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { ImageColumns._ID, ImageColumns.ORIENTATION,
                ImageColumns.DATE_TAKEN };

        String selection = ImageColumns.DATA + " like '%" + name + "%' AND " + ImageColumns.MIME_TYPE
                + "='image/jpeg'";
        String order = ImageColumns.DATE_TAKEN + " DESC," + ImageColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                internalMedia = new Media(id, cursor.getInt(1), cursor.getLong(2),
                        ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    try {
        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { ImageColumns._ID, ImageColumns.ORIENTATION,
                ImageColumns.DATE_TAKEN };

        String selection = ImageColumns.DATA + " like '%" + name + "%' AND " + ImageColumns.MIME_TYPE
                + "='image/jpeg'";
        String order = ImageColumns.DATE_TAKEN + " DESC," + ImageColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                externalMedia = new Media(id, cursor.getInt(1), cursor.getLong(2),
                        ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    if (internalMedia == null) {
        return externalMedia;
    } else if (externalMedia == null) {
        return internalMedia;
    } else {
        return internalMedia.dateTaken > externalMedia.dateTaken ? internalMedia : externalMedia;
    }
}