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:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

private static Bitmap getArtworkFromFile(Context context, long songid, long albumid) {
    Bitmap bm = null;/*from   w  w  w .  j  a  v a 2s . c  o  m*/
    byte[] art = null;
    String path = null;

    if (albumid < 0 && songid < 0) {
        throw new IllegalArgumentException("Must specify an album or a song id");
    }

    try {
        if (albumid < 0) {
            Uri uri = Uri.parse("content://media/external/audio/media/" + songid + "/albumart");
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
            if (pfd != null) {
                FileDescriptor fd = pfd.getFileDescriptor();
                bm = BitmapFactory.decodeFileDescriptor(fd);
            }
        } else {
            Uri uri = ContentUris.withAppendedId(sArtworkUri, albumid);
            ParcelFileDescriptor pfd = context.getContentResolver().openFileDescriptor(uri, "r");
            if (pfd != null) {
                FileDescriptor fd = pfd.getFileDescriptor();
                bm = BitmapFactory.decodeFileDescriptor(fd);
            }
        }
    } catch (IllegalStateException | FileNotFoundException ex) {
    }
    if (bm != null) {
        mCachedBit = bm;
    }
    return bm;
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use.
 * @param id The id of the album./*from w w w . j  av  a2 s .  com*/
 * @return The song count for an album.
 */
public static String getSongCountForAlbum(final Context context, final long id) {
    if (id == -1) {
        return null;
    }
    try {
        Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, id);
        Cursor cursor = context.getContentResolver().query(uri, new String[] { AlbumColumns.NUMBER_OF_SONGS },
                null, null, null);
        return getFirstStringResult(cursor, true);
    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}

From source file:net.impjq.providers.downloads.DownloadThread.java

private void notifyThroughDatabase(int status, boolean countRetry, int retryAfter, int redirectCount,
        boolean gotData, String filename, String uri, String mimeType) {
    ContentValues values = new ContentValues();
    values.put(Downloads.Impl.COLUMN_STATUS, status);
    values.put(Downloads.Impl._DATA, filename);
    if (uri != null) {
        values.put(Downloads.Impl.COLUMN_URI, uri);
    }// w w  w .jav a 2s . com
    values.put(Downloads.Impl.COLUMN_MIME_TYPE, mimeType);
    values.put(Downloads.Impl.COLUMN_LAST_MODIFICATION, System.currentTimeMillis());
    values.put(Constants.RETRY_AFTER_X_REDIRECT_COUNT, retryAfter + (redirectCount << 28));
    if (!countRetry) {
        values.put(Constants.FAILED_CONNECTIONS, 0);
    } else if (gotData) {
        values.put(Constants.FAILED_CONNECTIONS, 1);
    } else {
        values.put(Constants.FAILED_CONNECTIONS, mInfo.mNumFailed + 1);
    }

    mContext.getContentResolver().update(ContentUris.withAppendedId(Downloads.Impl.CONTENT_URI, mInfo.mId),
            values, null, null);
}

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

private ParcelFileDescriptor openFileArtwork(@NonNull final Uri uri, @NonNull final String mode)
        throws FileNotFoundException {
    String[] projection = { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI };
    final boolean isWriteOperation = mode.contains("w");
    final File file;
    if (!UserManagerCompat.isUserUnlocked(getContext())) {
        if (isWriteOperation) {
            Log.w(TAG, "Wallpaper is read only until the user is unlocked");
            return null;
        }// w  w w. j a v  a 2  s .c  o m
        file = DirectBootCacheJobService.getCachedArtwork(getContext());
    } else if (!isWriteOperation && MuzeiProvider.uriMatcher.match(uri) == MuzeiProvider.ARTWORK) {
        // If it isn't a write operation, then we should attempt to find the latest artwork
        // that does have a cached artwork file. This prevents race conditions where
        // an external app attempts to load the latest artwork while an art source is inserting a
        // new artwork
        Cursor data = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, projection, null, null, null);
        if (data == null) {
            return null;
        }
        if (!data.moveToFirst()) {
            if (!getContext().getPackageName().equals(getCallingPackage())) {
                Log.w(TAG, "You must insert at least one row to read or write artwork");
            }
            return null;
        }
        File foundFile = null;
        while (!data.isAfterLast()) {
            Uri possibleArtworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI,
                    data.getLong(0));
            File possibleFile = getCacheFileForArtworkUri(possibleArtworkUri);
            if (possibleFile != null && possibleFile.exists()) {
                foundFile = possibleFile;
                break;
            }
            data.moveToNext();
        }
        file = foundFile;
    } else {
        file = getCacheFileForArtworkUri(uri);
    }
    if (file == null) {
        throw new FileNotFoundException("Could not create artwork file");
    }
    if (file.exists() && file.length() > 0 && isWriteOperation) {
        Context context = getContext();
        if (context == null) {
            return null;
        }
        if (!context.getPackageName().equals(getCallingPackage())) {
            Log.w(TAG, "Writing to an existing artwork file is not allowed: insert a new row");
        }
        cleanupCachedFiles();
        return null;
    }
    try {
        return ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode(mode), openFileHandler,
                new ParcelFileDescriptor.OnCloseListener() {
                    @Override
                    public void onClose(final IOException e) {
                        if (isWriteOperation) {
                            if (e != null) {
                                Log.e(TAG, "Error closing " + file + " for " + uri, e);
                                if (file.exists()) {
                                    if (!file.delete()) {
                                        Log.w(TAG, "Unable to delete " + file);
                                    }
                                }
                            } else {
                                // The file was successfully written, notify listeners of the new artwork
                                notifyChange(uri);
                                cleanupCachedFiles();
                            }
                        }

                    }
                });
    } catch (IOException e) {
        Log.e(TAG, "Error opening artwork " + uri, e);
        throw new FileNotFoundException("Error opening artwork " + uri);
    }
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use.
 * @param id The id of the album./*from  ww w  .j a v  a 2  s .  c  o m*/
 * @return The release date for an album.
 */
public static String getReleaseDateForAlbum(final Context context, final long id) {
    if (id == -1) {
        return null;
    }
    try {
        Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, id);
        Cursor cursor = context.getContentResolver().query(uri, new String[] { AlbumColumns.FIRST_YEAR }, null,
                null, null);
        return getFirstStringResult(cursor, true);
    } catch (Throwable e) {
        // ignore this error since it's not critical
        LOG.error("Error getting release date for album", e);
        return null;
    }
}

From source file:com.android.contacts.ContactSaveService.java

private void renameGroup(Intent intent) {
    long groupId = intent.getLongExtra(EXTRA_GROUP_ID, -1);
    String label = intent.getStringExtra(EXTRA_GROUP_LABEL);

    if (groupId == -1) {
        Log.e(TAG, "Invalid arguments for renameGroup request");
        return;//from w w  w.  j  a va 2  s. c  om
    }

    ContentValues values = new ContentValues();
    values.put(Groups.TITLE, label);
    final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, groupId);
    getContentResolver().update(groupUri, values, null, null);

    Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
    callbackIntent.setData(groupUri);
    deliverCallback(callbackIntent);
}

From source file:org.deviceconnect.android.deviceplugin.host.HostDeviceService.java

/**
 * ???(Id?)./*from w ww. j ava2  s .  c  o  m*/
 * 
 * @param response ?
 * @param mediaId MediaID
 */
public void putMediaId(final Intent response, final String mediaId) {
    mCurrentMediaId = mediaId;

    // Video????
    Uri mUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));

    String filePath = getPathFromUri(mUri);

    // null??Audio????
    if (filePath == null) {
        mUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Long.valueOf(mediaId));
        filePath = getPathFromUri(mUri);
    }

    String mMineType = getMIMEType(filePath);

    // ??
    if ("audio/mpeg".equals(mMineType) || "audio/x-wav".equals(mMineType) || "application/ogg".equals(mMineType)
            || "audio/x-ms-wma".equals(mMineType) || "audio/mp3".equals(mMineType)
            || "audio/ogg".equals(mMineType) || "audio/mp4".equals(mMineType)) {
        mMediaPlayer = new MediaPlayer();

        try {
            mSetMediaType = MEDIA_TYPE_MUSIC;
            myCurrentFilePath = filePath;
            myCurrentFileMIMEType = mMineType;
            mMediaStatus = MEDIA_PLAYER_SET;
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
                @Override
                public void onCompletion(final MediaPlayer arg0) {
                    mMediaStatus = MEDIA_PLAYER_STOP;
                    sendOnStatusChangeEvent("stop");
                }
            });
            response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
            response.putExtra(DConnectMessage.EXTRA_VALUE, "regist:" + filePath);
            sendOnStatusChangeEvent("media");
            sendBroadcast(response);
        } catch (IOException e) {
            response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE);
            response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not regist:" + filePath);
            sendBroadcast(response);
        }
    } else if ("video/3gpp".equals(mMineType) || "video/mp4".equals(mMineType) || "video/m4v".equals(mMineType)
            || "video/3gpp2".equals(mMineType) || "video/mpeg".equals(mMineType)) {

        try {

            mSetMediaType = MEDIA_TYPE_VIDEO;
            myCurrentFilePath = filePath;
            myCurrentFileMIMEType = mMineType;

            response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.RESULT_OK);
            response.putExtra(DConnectMessage.EXTRA_VALUE, "regist:" + filePath);
            sendOnStatusChangeEvent("media");
            sendBroadcast(response);
        } catch (Exception e) {
            response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE);
            response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not mount:" + filePath);
            sendBroadcast(response);
        }
    } else {
        response.putExtra(DConnectMessage.EXTRA_RESULT, DConnectMessage.EXTRA_ERROR_CODE);
        response.putExtra(DConnectMessage.EXTRA_VALUE, "can't not open:" + filePath);
        sendBroadcast(response);
    }
}

From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java

/**
 * Create a ContactField JSONObject//  ww  w  . j  av a 2s  .  com
 * 
 * @param contactId
 * @return a JSONObject representing a ContactField
 */
private JSONObject photoQuery(Cursor cursor, String contactId) {
    JSONObject photo = new JSONObject();
    try {
        photo.put("id", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Photo._ID)));
        photo.put("pref", false);
        photo.put("type", "url");
        Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, (new Long(contactId)));
        Uri photoUri = Uri.withAppendedPath(person, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
        photo.put("value", photoUri.toString());
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return photo;
}

From source file:com.android.contacts.common.model.ContactLoader.java

/**
 * Posts a message to the contributing sync adapters that have opted-in, notifying them
 * that the contact has just been loaded
 *///  w  w  w.j a  va  2 s.co  m
private void postViewNotificationToSyncAdapter() {
    Context context = getContext();
    for (RawContact rawContact : mContact.getRawContacts()) {
        final long rawContactId = rawContact.getId();
        if (mNotifiedRawContactIds.contains(rawContactId)) {
            continue; // Already notified for this raw contact.
        }
        mNotifiedRawContactIds.add(rawContactId);
        final AccountType accountType = rawContact.getAccountType(context);
        final String serviceName = accountType.getViewContactNotifyServiceClassName();
        final String servicePackageName = accountType.getViewContactNotifyServicePackageName();
        if (!TextUtils.isEmpty(serviceName) && !TextUtils.isEmpty(servicePackageName)) {
            final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
            final Intent intent = new Intent();
            intent.setClassName(servicePackageName, serviceName);
            intent.setAction(Intent.ACTION_VIEW);
            intent.setDataAndType(uri, RawContacts.CONTENT_ITEM_TYPE);
            try {
                context.startService(intent);
            } catch (Exception e) {
                Log.e(TAG, "Error sending message to source-app", e);
            }
        }
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.menu_edit:
        Intent intent = new Intent(Intent.ACTION_EDIT,
                ContentUris.withAppendedId(Places.CONTENT_URI, mPlace.placeId));
        startActivity(intent);//from   w w w  . j a  v  a2  s .c o  m
        return true;
    case R.id.menu_delete:
        showDialog(DIALOG_CONFIRM_DELETE, null);
        return true;
    case R.id.menu_block:
        showDialog(DIALOG_CONFIRM_BLOCK, null);
        return true;
    case R.id.menu_unblock:
        showDialog(DIALOG_CONFIRM_UNBLOCK, null);
        return true;
    }
    return false;
}