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.tgx.tina.android.plugin.downloader.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(GlobalDownload.COLUMN_STATUS, status);
    values.put(GlobalDownload._DATA, filename);
    if (uri != null) {
        values.put(GlobalDownload.COLUMN_URI, uri);
    }//from  w ww . j av a2s.  co m
    values.put(GlobalDownload.COLUMN_MIME_TYPE, mimeType);
    values.put(GlobalDownload.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(GlobalDownload.CONTENT_URI, mInfo.mId),
            values, null, null);
}

From source file:com.android.calendar.EventInfoFragment.java

public EventInfoFragment(Context context, long eventId, long startMillis, long endMillis, int attendeeResponse,
        boolean isDialog, int windowStyle, ArrayList<ReminderEntry> reminders) {
    this(context, ContentUris.withAppendedId(Events.CONTENT_URI, eventId), startMillis, endMillis,
            attendeeResponse, isDialog, windowStyle, reminders);
    mEventId = eventId;//from  w w w  .j a  va 2  s  . c om
}

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 v  a 2  s  . co  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:com.android.providers.contacts.ContactsSyncAdapter.java

private static void addGroupMembershipToContactEntry(String account, ContentResolver cr, long personId,
        ContactEntry entry) throws ParseException {
    Cursor c = cr.query(GroupMembership.RAW_CONTENT_URI, null, "person=" + personId, null, null);
    try {//  w ww. ja  v  a  2  s  .c o  m
        int serverIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_SYNC_ID);
        int localIdIndex = c.getColumnIndexOrThrow(GroupMembership.GROUP_ID);
        while (c.moveToNext()) {
            String serverId = c.getString(serverIdIndex);
            if (serverId == null) {
                final Uri groupUri = ContentUris.withAppendedId(Groups.CONTENT_URI, c.getLong(localIdIndex));
                Cursor groupCursor = cr.query(groupUri, new String[] { Groups._SYNC_ID }, null, null, null);
                try {
                    if (groupCursor.moveToNext()) {
                        serverId = groupCursor.getString(0);
                    }
                } finally {
                    groupCursor.close();
                }
            }
            if (serverId == null) {
                // the group hasn't been synced yet, we can't complete this operation since
                // we don't know what server id to use for the group
                throw new ParseException("unable to construct GroupMembershipInfo since the "
                        + "group _sync_id isn't known yet, will retry later");
            }
            GroupMembershipInfo groupMembershipInfo = new GroupMembershipInfo();
            String groupId = getCanonicalGroupsFeedForAccount(account) + "/" + serverId;
            groupMembershipInfo.setGroup(groupId);
            groupMembershipInfo.setDeleted(false);
            entry.addGroup(groupMembershipInfo);
        }
    } finally {
        if (c != null)
            c.close();
    }
}

From source file:br.com.viniciuscr.notification2android.mediaPlayer.MusicUtils.java

/**
 * Get album art for specified album. You should not pass in the album id
 * for the "unknown" album here (use -1 instead)
 *//*from   ww w  .  j  a v a 2s .  c  o m*/
public static Bitmap getArtwork(Context context, long song_id, long album_id, boolean allowdefault) {

    if (album_id < 0) {
        // This is something that is not in the database, so get the album art directly
        // from the file.
        if (song_id >= 0) {
            Bitmap bm = getArtworkFromFile(context, song_id, -1);
            if (bm != null) {
                return bm;
            }
        }
        if (allowdefault) {
            return getDefaultArtwork(context);
        }
        return null;
    }

    ContentResolver res = context.getContentResolver();
    Uri uri = ContentUris.withAppendedId(sArtworkUri, album_id);
    if (uri != null) {
        InputStream in = null;
        try {
            in = res.openInputStream(uri);
            return BitmapFactory.decodeStream(in, null, sBitmapOptions);
        } catch (FileNotFoundException ex) {
            // The album art thumbnail does not actually exist. Maybe the user deleted it, or
            // maybe it never existed to begin with.
            Bitmap bm = getArtworkFromFile(context, song_id, album_id);
            if (bm != null) {
                if (bm.getConfig() == null) {
                    bm = bm.copy(Bitmap.Config.RGB_565, false);
                    if (bm == null && allowdefault) {
                        return getDefaultArtwork(context);
                    }
                }
            } else if (allowdefault) {
                bm = getDefaultArtwork(context);
            }
            return bm;
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
            }
        }
    }

    return null;
}

From source file:com.android.music.TrackBrowserFragment.java

private void removeItem() {
    int curcount = mTrackCursor.getCount();
    int curpos = mTrackList.getSelectedItemPosition();
    if (curcount == 0 || curpos < 0) {
        return;/*from   w  w w . j a v  a 2s  .c o m*/
    }

    if ("nowplaying".equals(mPlaylist)) {
        // remove track from queue

        // Work around bug 902971. To get quick visual feedback
        // of the deletion of the item, hide the selected view.
        try {
            if (curpos != MusicUtils.sService.getQueuePosition()) {
                mDeletedOneRow = true;
            }
        } catch (RemoteException ex) {
        }
        View v = mTrackList.getSelectedView();
        v.setVisibility(View.GONE);
        mTrackList.invalidateViews();
        ((NowPlayingCursor) mTrackCursor).removeItem(curpos);
        v.setVisibility(View.VISIBLE);
        mTrackList.invalidateViews();
    } else {
        // remove track from playlist
        int colidx = mTrackCursor.getColumnIndexOrThrow(MediaStore.Audio.Playlists.Members._ID);
        mTrackCursor.moveToPosition(curpos);
        long id = mTrackCursor.getLong(colidx);
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", Long.valueOf(mPlaylist));
        getActivity().getContentResolver().delete(ContentUris.withAppendedId(uri, id), null, null);
        curcount--;
        if (curcount == 0) {
            getActivity().finish();
        } else {
            mTrackList.setSelection(curpos < curcount ? curpos : curcount);
        }
    }
}

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

/**
 * @param context The {@link Context} to use
 * @param id The song ID.//from   w  w w .j a  v  a  2s  .  c  o m
 */
public static void setRingtone(final Context context, final long id) {
    final ContentResolver resolver = context.getContentResolver();
    final Uri uri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
    try {
        final ContentValues values = new ContentValues(2);
        values.put(AudioColumns.IS_RINGTONE, "1");
        values.put(AudioColumns.IS_ALARM, "1");
        resolver.update(uri, values, null, null);
    } catch (final UnsupportedOperationException ignored) {
        return;
    }

    final String[] projection = new String[] { BaseColumns._ID, MediaColumns.DATA, MediaColumns.TITLE };

    final String selection = BaseColumns._ID + "=" + id;
    Cursor cursor = resolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, selection, null,
            null);
    try {
        if (cursor != null && cursor.getCount() == 1) {
            cursor.moveToFirst();
            RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, uri);
            final String message = context.getString(R.string.set_as_ringtone, cursor.getString(2));
            AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show();
        }
    } catch (Throwable ignored) {
        UIUtils.showLongMessage(context, R.string.ringtone_not_set);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.akop.bach.parser.XboxLiveParser.java

private void parseGames(XboxLiveAccount account) throws ParserException, IOException {
    long started = System.currentTimeMillis();

    String url = String.format(URL_GAME_LIST, mLocale);
    String page = getResponse(url);

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Game page fetch", started);

    long accountId = account.getId();
    String[] queryParams = new String[1];
    int rowNo = 0;
    boolean changed = false;
    Cursor c;/*from  w w  w .  j  a va  2s.co m*/
    ContentValues cv;
    long updated = System.currentTimeMillis();
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);
    ContentResolver cr = mContext.getContentResolver();
    List<String> gameIds = new ArrayList<String>(50);

    Matcher m = PATTERN_GAME_ITEM.matcher(page);
    while (m.find()) {
        String content = m.group(1);
        App.logv(" *** found it: " + content);
        Matcher im = PATTERN_GAME_TITLE_ID.matcher(content);
        if (!im.find())
            continue;

        String uid = im.group(1);
        String title = htmlDecode(im.group(2));
        String boxArtUrl = null;
        int gpAcquired = 0;
        int achUnlocked = 0;

        gameIds.add(uid);

        im = PATTERN_GAME_BOX_ART.matcher(content);
        if (im.find())
            boxArtUrl = im.group(1);

        im = PATTERN_GAME_SCORE.matcher(content);
        if (im.find()) {
            try {
                gpAcquired = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        im = PATTERN_GAME_ACHIEVEMENTS.matcher(content);
        if (im.find()) {
            try {
                achUnlocked = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        // Check to see if we already have a record of this game
        queryParams[0] = uid;
        c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION,
                Games.ACCOUNT_ID + "=" + accountId + " AND " + Games.UID + "=?", queryParams, null);

        try {
            if (c == null || !c.moveToFirst()) // New game
            {
                cv = new ContentValues(15);
                cv.put(Games.ACCOUNT_ID, accountId);
                cv.put(Games.TITLE, title);
                cv.put(Games.UID, uid);
                cv.put(Games.BOXART_URL, boxArtUrl);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.LAST_UPDATED, updated);
                cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                cv.put(Games.POINTS_TOTAL, gpAcquired);
                cv.put(Games.GAME_URL, (String) null);
                cv.put(Games.INDEX, rowNo);

                // Games with no achievements do not need achievement refresh
                cv.put(Games.ACHIEVEMENTS_STATUS, 1);

                newCvs.add(cv);
            } else // Existing game
            {
                long gameId = c.getLong(COLUMN_GAME_ID);
                long lastPlayedTicksRec = c.getLong(COLUMN_GAME_LAST_PLAYED_DATE);

                cv = new ContentValues(15);

                boolean refreshAchievements = true;

                if (refreshAchievements) {
                    cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                    cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                    cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                    cv.put(Games.POINTS_TOTAL, gpAcquired);
                    cv.put(Games.ACHIEVEMENTS_STATUS, 1);
                }

                cv.put(Games.BEACON_SET, 0);
                cv.put(Games.BEACON_TEXT, (String) null);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.INDEX, rowNo);
                cv.put(Games.LAST_UPDATED, updated);
                cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);

                changed = true;
            }
        } finally {
            if (c != null)
                c.close();
        }

        rowNo++;
    }

    // Remove games that are no longer present
    c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION, Games.ACCOUNT_ID + "=" + accountId, null, null);

    if (c != null) {
        while (c.moveToNext()) {
            if (!gameIds.contains(c.getString(COLUMN_GAME_UID))) {
                // Game is no longer in list of played games; remove it
                cr.delete(ContentUris.withAppendedId(Games.CONTENT_URI, c.getLong(COLUMN_GAME_ID)), null, null);
                changed = true;
            }
        }

        c.close();
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Game page processing", started);

    if (newCvs.size() > 0) {
        changed = true;

        ContentValues[] cvs = new ContentValues[newCvs.size()];
        newCvs.toArray(cvs);

        cr.bulkInsert(Games.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Game page insertion", started);
    }

    account.refresh(Preferences.get(mContext));
    account.setLastGameUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));

    if (changed)
        cr.notifyChange(Games.CONTENT_URI, null);
}

From source file:mobisocial.musubi.service.AddressBookUpdateHandler.java

public static void importFullAddressBook(Context context) {
    Log.d(TAG, "doing full import");
    SQLiteOpenHelper db = App.getDatabaseSource(context);
    DatabaseManager dbm = new DatabaseManager(context);
    IdentitiesManager idm = dbm.getIdentitiesManager();
    FeedManager fm = dbm.getFeedManager();
    MyAccountManager am = dbm.getMyAccountManager();
    long startTime = System.currentTimeMillis();
    String musubiAccountType = context.getString(R.string.account_type);
    long maxDataId = -1;
    long maxContactId = -1;
    assert (SYNC_EMAIL);
    String account_type_selection = getAccountSelectionString();

    Cursor c = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI,
            new String[] { ContactsContract.Data.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.Data._ID, ContactsContract.Data.DATA_VERSION, ContactsContract.Data.DATA1,
                    ContactsContract.Data.MIMETYPE, ContactsContract.RawContacts.ACCOUNT_NAME,
                    ContactsContract.RawContacts.ACCOUNT_TYPE },
            "(" + ContactsContract.RawContacts.ACCOUNT_TYPE + "<>'" + musubiAccountType + "'" + ") AND ("
                    + NAME_OR_OTHER_SELECTION + account_type_selection + ")", // All known contacts.
            null, null);//from   w  w w  .j a v a  2  s. com

    if (c == null) {
        Log.e(TAG, "no valid cursor", new Throwable());
        return;
    }

    sAddressBookTotal = c.getCount();
    sAddressBookPosition = 0;
    Log.d(TAG, "Scanning contacts...");

    final Map<String, MMyAccount> myAccounts = new HashMap<String, MMyAccount>();
    final Pattern emailPattern = getEmailPattern();
    final Pattern numberPattern = getNumberPattern();
    while (c.moveToNext()) {
        sAddressBookPosition++;
        String identityType = c.getString(5);
        String identityPrincipal = c.getString(4);
        long contactId = c.getLong(0);
        long dataId = c.getLong(2);
        String displayName = c.getString(1);
        byte[] thumbnail = null;

        String accountName = c.getString(6);
        String accountType = c.getString(7);
        if (accountName == null) {
            accountName = "null-account-name";
        }
        if (accountType == null) {
            accountType = "null-account-type";
        }
        String accountKey = accountName + "-" + accountType;
        MMyAccount myAccount = myAccounts.get(accountKey);
        if (myAccount == null) {
            myAccount = lookupOrCreateAccount(dbm, accountName, accountType);
            prepareAccountWhitelistFeed(am, fm, myAccount);
            myAccounts.put(accountKey, myAccount);
        }

        if (displayName == null || emailPattern.matcher(displayName).matches()
                || numberPattern.matcher(displayName).matches()) {
            continue;
        }

        IBIdentity ibid = ibIdentityForData(identityType, identityPrincipal);
        if (ibid == null) {
            //TODO: better selection
            //Log.d(TAG, "skipping " + displayName + " // " + identityPrincipal);
            continue;
        }
        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId);
        InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(),
                uri);
        if (is != null) {
            //Log.d(TAG, "importing photo for " + displayName);
            try {
                thumbnail = IOUtils.toByteArray(is);
            } catch (IOException e) {
                thumbnail = null;
                //Log.e(TAG, "photo thumbnail failed to serialize", e);
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        } else {
            thumbnail = null;
        }
        MIdentity ident = addIdentity(context, idm, contactId, displayName, thumbnail, ibid);
        if (ident != null) {
            fm.ensureFeedMember(myAccount.feedId_, ident.id_);
            fm.acceptFeedsFromMember(context, ident.id_);
        }

        maxDataId = Math.max(maxDataId, dataId);
        maxContactId = Math.max(maxContactId, contactId);
    }
    c.close();
    long timeTaken = System.currentTimeMillis() - startTime;

    ContactDataVersionManager cdvm = new ContactDataVersionManager(db);
    cdvm.setMaxDataIdSeen(maxDataId);
    cdvm.setMaxContactIdSeen(maxContactId);
    Log.d(TAG, "full import took " + timeTaken / 1000 + " secs");
    context.getContentResolver().notifyChange(MusubiService.ADDRESS_BOOK_SCANNED, null);
}

From source file:com.akop.bach.parser.PsnUsParser.java

protected void parseFriendSummary(PsnAccount account, String friendOnlineId)
        throws ParserException, IOException {
    long updated = System.currentTimeMillis();
    long started = updated;

    GamerProfileInfo gpi = parseGamerProfile(account, friendOnlineId);

    ContentResolver cr = mContext.getContentResolver();
    Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
            Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
            new String[] { friendOnlineId }, null);

    long friendId = -1;

    try {//from  ww w.j a  va  2  s.  c  o  m
        if (c != null && c.moveToFirst())
            friendId = c.getLong(0);
    } finally {
        if (c != null)
            c.close();
    }

    ContentValues cv = new ContentValues(15);

    cv.put(Friends.ONLINE_ID, gpi.OnlineId);
    cv.put(Friends.ICON_URL, gpi.AvatarUrl);
    cv.put(Friends.LEVEL, gpi.Level);
    cv.put(Friends.PROGRESS, gpi.Progress);
    cv.put(Friends.ONLINE_STATUS, gpi.OnlineStatus);
    cv.put(Friends.TROPHIES_PLATINUM, gpi.PlatinumTrophies);
    cv.put(Friends.TROPHIES_GOLD, gpi.GoldTrophies);
    cv.put(Friends.TROPHIES_SILVER, gpi.SilverTrophies);
    cv.put(Friends.TROPHIES_BRONZE, gpi.BronzeTrophies);
    cv.put(Friends.PLAYING, gpi.Playing);
    cv.put(Friends.LAST_UPDATED, updated);

    if (friendId < 0) {
        // New
        cv.put(Friends.ACCOUNT_ID, account.getId());
        cr.insert(Friends.CONTENT_URI, cv);
    } else {
        cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Friend page processing", started);

    cr.notifyChange(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), null);
}