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:ch.ethz.dcg.jukefox.manager.libraryimport.AndroidAlbumCoverFetcherThread.java

private AlbumFetcherResult extractBitmapsFromMediaProviderCursor(int albumId, Cursor cur) throws Exception {
    int cpAlbumId = cur.getInt(0);
    Uri uri = ContentUris.withAppendedId(sArtworkUri, cpAlbumId);

    if (uri != null) {
        InputStream in = null;// w  w w .j  a  va 2s  .co  m
        try {
            in = contentResolver.openInputStream(uri);
            Bitmap bitmapHigh = AndroidUtils.getBitmapFromInputStream(in,
                    2 * AndroidConstants.COVER_SIZE_HIGH_RES);
            bitmapHigh = resizeBitmap(bitmapHigh, AndroidConstants.COVER_SIZE_HIGH_RES);
            if (bitmapHigh == null) {
                return null;
            }
            // Log.v("Got cover from phone DB", album.getArtists().get(0)
            // .getName()
            // + " - "
            // + album.getName()
            // + " "
            // + cpAlbumId
            // + " HResPath: " + highResPath);
            Bitmap bitmapLow = resizeBitmap(bitmapHigh, AndroidConstants.COVER_SIZE_LOW_RES);
            int color = getColorFromBitmap(bitmapLow);
            String lowResPath = getDefaultCoverPath(true, albumId);
            String highResPath = getDefaultCoverPath(false, albumId);
            saveImage(bitmapHigh, highResPath);
            saveImage(bitmapLow, lowResPath);
            return new AlbumFetcherResult(highResPath, lowResPath, color, AlbumStatus.CONTENT_PROVIDER_COVER,
                    albumId);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                Log.w(TAG, ex);
            }
        }
    }
    return null;
}

From source file:com.amytech.android.library.views.imagechooser.threads.MediaProcessorThread.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];
            }/*from ww w  .j av a 2 s.  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 getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

From source file:com.android.email.LegacyConversions.java

/**
 * Save the body part of a single attachment, to a file in the attachments directory.
 *///from  www . j  a  va  2 s. c  o m
public static void saveAttachmentBody(Context context, Part part, Attachment localAttachment, long accountId)
        throws MessagingException, IOException {
    if (part.getBody() != null) {
        long attachmentId = localAttachment.mId;

        InputStream in = part.getBody().getInputStream();

        File saveIn = AttachmentProvider.getAttachmentDirectory(context, accountId);
        if (!saveIn.exists()) {
            saveIn.mkdirs();
        }
        File saveAs = AttachmentProvider.getAttachmentFilename(context, accountId, attachmentId);
        saveAs.createNewFile();
        FileOutputStream out = new FileOutputStream(saveAs);
        long copySize = IOUtils.copy(in, out);
        in.close();
        out.close();

        // update the attachment with the extra information we now know
        String contentUriString = AttachmentProvider.getAttachmentUri(accountId, attachmentId).toString();

        localAttachment.mSize = copySize;
        localAttachment.mContentUri = contentUriString;

        // update the attachment in the database as well
        ContentValues cv = new ContentValues();
        cv.put(AttachmentColumns.SIZE, copySize);
        cv.put(AttachmentColumns.CONTENT_URI, contentUriString);
        Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId);
        context.getContentResolver().update(uri, cv, null, null);
    }
}

From source file:com.tct.email.LegacyConversions.java

/**
 * Add a single attachment part to the message
 *
 * This will skip adding attachments if they are already found in the attachments table.
 * The heuristic for this will fail (false-positive) if two identical attachments are
 * included in a single POP3 message.//from  www.  j  a v a2s  . c o  m
 * TODO: Fix that, by (elsewhere) simulating an mLocation value based on the attachments
 * position within the list of multipart/mixed elements.  This would make every POP3 attachment
 * unique, and might also simplify the code (since we could just look at the positions, and
 * ignore the filename, etc.)
 *
 * TODO: Take a closer look at encoding and deal with it if necessary.
 *
 * @param context      a context for file operations
 * @param localMessage the attachments will be built against this message
 * @param part         a single attachment part from POP or IMAP
 * @param index        add for pop re-download attachment
 * @param protocol   add to judge if it's pop3,it can be used later
 * @param isInline     add to judge if it's isInline attachment
 */
public static void addOneAttachment(final Context context, final EmailContent.Message localMessage,
        final Part part, int index, String protocol, boolean isInline) throws MessagingException, IOException {
    Attachment localAttachment = mimePartToAttachment(context, part, index, protocol, isInline);
    // TS: Gantao 2015-06-04 EMAIL BUGFIX_1009030 MOD_E
    localAttachment.mMessageKey = localMessage.mId;
    localAttachment.mAccountKey = localMessage.mAccountKey;

    if (DEBUG_ATTACHMENTS) {
        LogUtils.d(Logging.LOG_TAG, "Add attachment " + localAttachment);
    }

    // To prevent duplication - do we already have a matching attachment?
    // The fields we'll check for equality are:
    //  mFileName, mMimeType, mContentId, mMessageKey, mLocation
    // NOTE:  This will false-positive if you attach the exact same file, twice, to a POP3
    // message.  We can live with that - you'll get one of the copies.
    final Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, localMessage.mId);
    final Cursor cursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION, null, null,
            null);
    boolean attachmentFoundInDb = false;
    try {
        while (cursor.moveToNext()) {
            final Attachment dbAttachment = new Attachment();
            dbAttachment.restore(cursor);
            // We test each of the fields here (instead of in SQL) because they may be
            // null, or may be strings.
            if (!TextUtils.equals(dbAttachment.mFileName, localAttachment.mFileName)
                    || !TextUtils.equals(dbAttachment.mMimeType, localAttachment.mMimeType)
                    || !TextUtils.equals(dbAttachment.mContentId, localAttachment.mContentId)
                    || !TextUtils.equals(dbAttachment.mLocation, localAttachment.mLocation)) {
                continue;
            }
            // We found a match, so use the existing attachment id, and stop looking/looping
            attachmentFoundInDb = true;
            localAttachment.mId = dbAttachment.mId;
            if (DEBUG_ATTACHMENTS) {
                LogUtils.d(Logging.LOG_TAG, "Skipped, found db attachment " + dbAttachment);
            }
            break;
        }
    } finally {
        cursor.close();
    }

    //TS: Gantao 2015-07-16 EMAIL BUGFIX_1045624 MOD_S
    // Save the attachment (so far) in order to obtain an id
    if (!attachmentFoundInDb) {
        localAttachment.save(context);
    }
    // If an attachment body was actually provided, we need to write the file now
    saveAttachmentBody(context, part, localAttachment, localMessage.mAccountKey);
    //TS: Gantao 2015-07-16 EMAIL BUGFIX_1045624 MOD_E
    if (localMessage.mAttachments == null) {
        localMessage.mAttachments = new ArrayList<Attachment>();
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_852100 MOD_S
    Body body = Body.restoreBodyWithMessageId(context, localAttachment.mMessageKey);
    ContentValues cv = new ContentValues();
    if (body != null && body.mHtmlContent != null && localAttachment.mContentId != null
            && localAttachment.getContentUri() != null) {
        cv.clear();
        String html = body.mHtmlContent;
        String contentIdRe = "\\s+(?i)src=\"cid(?-i):\\Q" + localAttachment.mContentId + "\\E\"";
        //TS: zhaotianyong 2015-03-23 EMAIL BUGFIX_899799 MOD_S
        //TS: zhaotianyong 2015-04-01 EMAIL BUGFIX_962560 MOD_S
        String srcContentUri = " src=\"" + localAttachment.getContentUri() + "\"";
        //TS: zhaotianyong 2015-04-01 EMAIL BUGFIX_962560 MOD_E
        //TS: zhaotianyong 2015-03-23 EMAIL BUGFIX_899799 MOD_E
        //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_S
        try {
            html = html.replaceAll(contentIdRe, srcContentUri);
        } catch (PatternSyntaxException e) {
            LogUtils.w(Logging.LOG_TAG, "Unrecognized backslash escape sequence in pattern");
        }
        //TS: zhaotianyong 2015-04-15 EMAIL BUGFIX_976967 MOD_E
        cv.put(BodyColumns.HTML_CONTENT, html);
        Body.updateBodyWithMessageId(context, localAttachment.mMessageKey, cv);
        Body.restoreBodyHtmlWithMessageId(context, localAttachment.mMessageKey);
    }
    //TS: wenggangjin 2014-12-10 EMAIL BUGFIX_852100 MOD_E
    localMessage.mAttachments.add(localAttachment);
    //TS: Gantao 2015-09-28 EMAIL FEATURE_526529 MOD_S
    //We do not think the inline images is an attachment from now.
    if (!isInline) {
        localMessage.mFlagAttachment = true;
    }
    //TS: Gantao 2015-09-28 EMAIL FEATURE_526529 MOD_E
}

From source file:org.mythtv.service.dvr.v27.RecordedHelperV27.java

private void processProgramGroups(final Context context, final LocationProfile locationProfile,
        Program[] programs) throws RemoteException, OperationApplicationException {
    Log.v(TAG, "processProgramGroups : enter");

    if (null == context)
        throw new RuntimeException("RecordedHelperV27 is not initialized");

    Map<String, ProgramGroup> programGroups = new TreeMap<String, ProgramGroup>();
    for (Program program : programs) {

        if (null != program.getRecording()) {

            if (null != program.getRecording().getRecGroup()
                    && !"livetv".equalsIgnoreCase(program.getRecording().getRecGroup())
                    && !"deleted".equalsIgnoreCase(program.getRecording().getRecGroup())) {
                String cleaned = ArticleCleaner.clean(program.getTitle());
                if (!programGroups.containsKey(cleaned)) {

                    ProgramGroup programGroup = new ProgramGroup();
                    programGroup.setTitle(program.getTitle());
                    programGroup.setCategory(program.getCategory());
                    programGroup.setInetref(program.getInetref());
                    programGroup.setSort(0);

                    programGroups.put(cleaned, programGroup);
                }/*from   w w  w.  j  ava 2 s  .  c o m*/

            }

        }

    }

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    Log.v(TAG, "processProgramGroups : adding 'All' program group in programGroups");
    ProgramGroup all = new ProgramGroup(null, "All", "All", "All", "", 1);
    programGroups.put(all.getProgramGroup(), all);

    String[] programGroupProjection = new String[] { ProgramGroupConstants._ID };
    String programGroupSelection = ProgramGroupConstants.FIELD_PROGRAM_GROUP + " = ?";

    programGroupSelection = appendLocationHostname(context, locationProfile, programGroupSelection, null);

    for (String key : programGroups.keySet()) {
        Log.v(TAG, "processProgramGroups : processing programGroup '" + key + "'");

        ProgramGroup programGroup = programGroups.get(key);

        ContentValues programValues = convertProgramGroupToContentValues(locationProfile, programGroup);
        Cursor programGroupCursor = context.getContentResolver().query(ProgramGroupConstants.CONTENT_URI,
                programGroupProjection, programGroupSelection, new String[] { key }, null);
        if (programGroupCursor.moveToFirst()) {

            Long id = programGroupCursor
                    .getLong(programGroupCursor.getColumnIndexOrThrow(ProgramGroupConstants._ID));
            ops.add(ContentProviderOperation
                    .newUpdate(ContentUris.withAppendedId(ProgramGroupConstants.CONTENT_URI, id))
                    .withValues(programValues).withYieldAllowed(true).build());

        } else {

            ops.add(ContentProviderOperation.newInsert(ProgramGroupConstants.CONTENT_URI)
                    .withValues(programValues).withYieldAllowed(true).build());
        }
        programGroupCursor.close();
        count++;

        if (count > 100) {
            Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

            processBatch(context, ops, processed, count);
        }

    }

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : remove deleted program groups");
    ops = new ArrayList<ContentProviderOperation>();

    DateTime lastModified = new DateTime();
    lastModified = lastModified.minusHours(1);

    String deleteProgramGroupSelection = ProgramGroupConstants.FIELD_LAST_MODIFIED_DATE + " < ?";
    String[] deleteProgramGroupArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deleteProgramGroupSelection = appendLocationHostname(context, locationProfile, deleteProgramGroupSelection,
            ProgramGroupConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(ProgramGroupConstants.CONTENT_URI)
            .withSelection(deleteProgramGroupSelection, deleteProgramGroupArgs).withYieldAllowed(true).build());

    if (!ops.isEmpty()) {
        Log.v(TAG, "processProgramGroups : applying batch for '" + count + "' transactions");

        processBatch(context, ops, processed, count);
    }

    Log.v(TAG, "processProgramGroups : exit");
}

From source file:org.deviceconnect.android.deviceplugin.chromecast.profile.ChromeCastMediaPlayerProfile.java

/**
 * mediaId?dummyUrl??/*ww  w  .j  av a 2  s . c  o m*/
 * 
 * @param   mediaId     ID
 * @return  dummyUrl    URL
 */
private String getDummyUrlFromMediaId(int mediaId) {
    Uri targetUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
    String path = getPathFromUri(ContentUris.withAppendedId(targetUri, Long.valueOf(mediaId)));

    if (path == null) {
        return null;
    }

    ChromeCastHttpServer server = ((ChromeCastService) getContext()).getChromeCastHttpServer();
    String dir = new File(path).getParent();
    String realName = new File(path).getName();
    String extension = MimeTypeMap.getFileExtensionFromUrl(realName);
    String dummyName = getMd5("" + System.currentTimeMillis()) + "." + extension;

    server.setFilePath(dir, realName, "/" + dummyName);
    return "http://" + getIpAddress() + ":" + server.getListeningPort() + "/" + dummyName;
}

From source file:com.mail163.email.LegacyConversions.java

/**
 * Save the body part of a single attachment, to a file in the attachments directory.
 *///from w w  w  .  j  a v  a  2s  . c  o  m
public static void saveAttachmentBody(Context context, Part part, Attachment localAttachment, long accountId)
        throws MessagingException, IOException {
    if (part.getBody() != null) {
        long attachmentId = localAttachment.mId;

        InputStream in = part.getBody().getInputStream();

        File saveIn = AttachmentProvider.getAttachmentDirectory(context, accountId);
        if (!saveIn.exists()) {
            saveIn.mkdirs();
        }
        File saveAs = AttachmentProvider.getAttachmentFilename(context, accountId, attachmentId);

        saveAs.createNewFile();
        FileOutputStream out = new FileOutputStream(saveAs);
        long copySize = IOUtils.copy(in, out);
        in.close();
        out.close();

        // update the attachment with the extra information we now know
        String contentUriString = AttachmentProvider.getAttachmentUri(accountId, attachmentId).toString();

        localAttachment.mSize = copySize;
        localAttachment.mContentUri = contentUriString;

        // update the attachment in the database as well
        ContentValues cv = new ContentValues();
        cv.put(AttachmentColumns.SIZE, copySize);
        cv.put(AttachmentColumns.CONTENT_URI, contentUriString);
        //            cv.put(AttachmentColumns.MIME_TYPE, "image/png");
        Uri uri = ContentUris.withAppendedId(Attachment.CONTENT_URI, attachmentId);

        context.getContentResolver().update(uri, cv, null, null);
    }
}

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

/**
 * Listener that checks for clicks on the main list view.
 * //  w w w .j  a va  2 s .c  om
 * @param adapterView
 * @param view
 * @param position
 * @param id
 */
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
    if (MyLog.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "onItemClick, id=" + id);
    }
    if (id <= 0) {
        return;
    }
    Uri uri = ContentUris.withAppendedId(Tweets.CONTENT_URI, id);
    String action = getIntent().getAction();
    if (Intent.ACTION_PICK.equals(action) || Intent.ACTION_GET_CONTENT.equals(action)) {
        if (MyLog.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "onItemClick, setData=" + uri);
        }
        setResult(RESULT_OK, new Intent().setData(uri));
    } else {
        if (MyLog.isLoggable(TAG, Log.DEBUG)) {
            Log.d(TAG, "onItemClick, startActivity=" + uri);
        }
        startActivity(new Intent(Intent.ACTION_VIEW, uri));
    }
}

From source file:com.just.agentweb.AgentWebUtils.java

@TargetApi(19)
static String getFileAbsolutePath(Activity context, Uri fileUri) {

    if (context == null || fileUri == null) {
        return null;
    }/*from   ww  w .j  a v a  2s .c o m*/

    LogUtils.i(TAG, "getAuthority:" + fileUri.getAuthority() + "  getHost:" + fileUri.getHost() + "   getPath:"
            + fileUri.getPath() + "  getScheme:" + fileUri.getScheme() + "  query:" + fileUri.getQuery());
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
            && DocumentsContract.isDocumentUri(context, fileUri)) {
        if (isExternalStorageDocument(fileUri)) {
            String docId = DocumentsContract.getDocumentId(fileUri);
            String[] split = docId.split(":");
            String type = split[0];
            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }
        } else if (isDownloadsDocument(fileUri)) {
            String id = DocumentsContract.getDocumentId(fileUri);
            Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                    Long.valueOf(id));
            return getDataColumn(context, contentUri, null, null);
        } else if (isMediaDocument(fileUri)) {
            String docId = DocumentsContract.getDocumentId(fileUri);
            String[] split = docId.split(":");
            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;
            }
            String selection = MediaStore.Images.Media._ID + "=?";
            String[] selectionArgs = new String[] { split[1] };
            return getDataColumn(context, contentUri, selection, selectionArgs);
        } else {

        }
    } // MediaStore (and general)
    else if (fileUri.getAuthority().equalsIgnoreCase(context.getPackageName() + ".AgentWebFileProvider")) {

        String path = fileUri.getPath();
        int index = path.lastIndexOf("/");
        return getAgentWebFilePath(context) + File.separator + path.substring(index + 1, path.length());
    } else if ("content".equalsIgnoreCase(fileUri.getScheme())) {
        // Return the remote address
        if (isGooglePhotosUri(fileUri)) {
            return fileUri.getLastPathSegment();
        }
        return getDataColumn(context, fileUri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(fileUri.getScheme())) {
        return fileUri.getPath();
    }
    return null;
}

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

@Override
public boolean onContextItemSelected(MenuItem item) {
    final SipProfile account = profileFromContextMenuInfo(item.getMenuInfo());
    if (account == null) {
        // For some reason the requested item isn't available, do nothing
        return super.onContextItemSelected(item);
    }/*from  www . j av a2 s . c  o m*/

    switch (item.getItemId()) {
    case MENU_ITEM_DELETE: {
        getActivity().getContentResolver()
                .delete(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), null, null);
        return true;
    }
    case MENU_ITEM_MODIFY: {
        showDetails(account.id, account.wizard);
        return true;
    }
    case MENU_ITEM_ACTIVATE: {
        ContentValues cv = new ContentValues();
        cv.put(SipProfile.FIELD_ACTIVE, !account.active);
        getActivity().getContentResolver()
                .update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), cv, null, null);
        return true;
    }
    case MENU_ITEM_WIZARD: {
        Intent it = new Intent(getActivity(), WizardChooser.class);
        it.putExtra(Intent.EXTRA_UID, account.id);
        startActivityForResult(it, CHANGE_WIZARD);
        return true;
    }
    }
    return super.onContextItemSelected(item);

}