Example usage for android.content ContentResolver query

List of usage examples for android.content ContentResolver query

Introduction

In this page you can find the example usage for android.content ContentResolver query.

Prototype

public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection,
        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) 

Source Link

Document

Query the given URI, returning a Cursor over the result set.

Usage

From source file:com.akop.bach.fragment.playstation.GamesFragment.java

@Override
protected Cursor getIconCursor() {
    if (getActivity() == null)
        return null;

    ContentResolver cr = getActivity().getContentResolver();
    return cr.query(Games.CONTENT_URI, new String[] { Games._ID, Games.ICON_URL },
            Games.ACCOUNT_ID + "=" + mAccount.getId(), null, Games.DEFAULT_SORT_ORDER);
}

From source file:com.pi.android.brainbeats.model.RemoteJSONSource.java

@Override
public Iterator<MediaMetadataCompat> iterator() {
    try {/*from   w w  w .  ja v a 2 s .co  m*/
        ContentResolver cr = applicationContext.getContentResolver();
        ArrayList<MediaMetadataCompat> tracks = new ArrayList<>();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        String selection = MediaStore.Audio.Media.IS_MUSIC + "!= 0";
        String sortOrder = MediaStore.Audio.Media.TITLE + " ASC";
        Cursor cur = cr.query(uri, null, selection, null, sortOrder);
        int count = 0;
        List<String> musicList = new ArrayList<>();
        if (cur != null) {
            count = cur.getCount();
            if (count > 0) {
                while (cur.moveToNext()) {
                    tracks.add(buildFromStorage(cur, cr));
                }

            }
        }
        cur.close();
        return tracks.iterator();
    } catch (JSONException e) {
        LogHelper.e(TAG, e, "Could not retrieve music list");
        throw new RuntimeException("Could not retrieve music list", e);
    }
}

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

private static void refreshNotificationsForAccountInternal(final Context context, final long accountId) {
    final Uri accountUri = EmailProvider.uiUri("uiaccount", accountId);

    final ContentResolver contentResolver = context.getContentResolver();

    final Cursor mailboxCursor = contentResolver.query(
            ContentUris.withAppendedId(EmailContent.MAILBOX_NOTIFICATION_URI, accountId), null, null, null,
            null);//  w  w  w.j a v a  2s.  c  o m
    try {
        while (mailboxCursor.moveToNext()) {
            final long mailboxId = mailboxCursor.getLong(EmailContent.NOTIFICATION_MAILBOX_ID_COLUMN);
            if (mailboxId == 0)
                continue;

            final int unseenCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNSEEN_COUNT_COLUMN);

            final int unreadCount;
            // If nothing is unseen, clear the notification
            if (unseenCount == 0) {
                unreadCount = 0;
            } else {
                unreadCount = mailboxCursor.getInt(EmailContent.NOTIFICATION_MAILBOX_UNREAD_COUNT_COLUMN);
            }
            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_S
            Mailbox mailbox = Mailbox.restoreMailboxWithId(context, mailboxId);
            //TS:kaifeng.lu 2015-12-18 EMAIL BUGFIX_1190892  MOD_S
            if (mailbox != null && mailbox.mType == Mailbox.TYPE_INBOX) {
                //TS:kaifeng.lu 2015-12-18 EMAIL BUGFIX_1190892  MOD_E
                final Cursor unreadCursor = contentResolver.query(ContentUris
                        .withAppendedId(EmailContent.MAILBOX_MOST_RECENT_UNREAD_MESSAGE_URI, mailboxId), null,
                        null, null, null);
                long mostRecentUnreadMsgId = 0;
                if (unreadCursor != null && unreadCursor.moveToFirst()) {
                    try {
                        mostRecentUnreadMsgId = unreadCursor
                                .getLong(EmailContent.MAILBOX_MOST_RECENT_UNREAD_ID_COULUM);
                    } finally {
                        unreadCursor.close();
                    }
                }
                final int key = getUnreadKey(accountId, mailboxId);
                long lastMostRecentUnreadMsgId = sLastUnreadIds.get(key);
                LogUtils.i(LOG_TAG,
                        "key=" + key + " unseenCount=" + unseenCount + " unreadCount=" + unreadCount
                                + " lastMostRecentUnreadMsgId = " + lastMostRecentUnreadMsgId
                                + " mostRecentUnreadMsgId=" + mostRecentUnreadMsgId);
                //no need to send notification if latest Unread id not change
                if (lastMostRecentUnreadMsgId != 0 && unseenCount != 0
                        && lastMostRecentUnreadMsgId == mostRecentUnreadMsgId) {
                    LogUtils.i(LOG_TAG, "no need to send notification broadcast, continue");
                    continue;
                }
                sLastUnreadIds.put(key, mostRecentUnreadMsgId);
            }
            //TS:zheng.zou 2015-12-17 EMAIL BUGFIX_861247  ADD_E

            final Uri folderUri = EmailProvider.uiUri("uifolder", mailboxId);

            LogUtils.d(LOG_TAG, "Changes to account " + accountId + ", folder: " + mailboxId + ", unreadCount: "
                    + unreadCount + ", unseenCount: " + unseenCount);

            final Intent intent = new Intent(UIProvider.ACTION_UPDATE_NOTIFICATION);
            intent.setPackage(context.getPackageName());
            intent.setType(EmailProvider.EMAIL_APP_MIME_TYPE);

            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_ACCOUNT, accountUri);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_FOLDER, folderUri);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNREAD_COUNT, unreadCount);
            intent.putExtra(UIProvider.UpdateNotificationExtras.EXTRA_UPDATED_UNSEEN_COUNT, unseenCount);

            context.sendOrderedBroadcast(intent, null);
        }
    } finally {
        mailboxCursor.close();
    }
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private void readSmsDatabase() {
    //Fetches the complete call log in descending order. i.e recent calls appears first.
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.READ_SMS) == PackageManager.PERMISSION_GRANTED) {
        Uri message = Uri.parse("content://sms/");
        ContentResolver cr = getContentResolver();

        Cursor c = cr.query(message, null, null, null, null);
        int totalSMS = c.getCount();

        if (c.moveToFirst()) {
            for (int i = 0; i < totalSMS; i++) {
                mBuilder.setProgress(totalSMS, i, false);
                mNotifyManager.notify(notification_id, mBuilder.build());
                EventBus.getDefault()/*  w  w w . j  a va  2  s . c o m*/
                        .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
                String systemId = c.getString(c.getColumnIndexOrThrow("_id"));
                String address = c.getString(c.getColumnIndexOrThrow("address"));
                String body = c.getString(c.getColumnIndexOrThrow("body"));
                String readState = c.getString(c.getColumnIndex("read"));
                String dateAndTime = c.getString(c.getColumnIndexOrThrow("date"));
                String type = c.getString(c.getColumnIndexOrThrow("type"));

                Sms sms = Sms.getBySystemId(systemId);

                if (sms == null) {
                    sms = new Sms();
                    sms.setRemoteId("");
                }

                sms.setBody(body);
                sms.setAddress(address.replace(" ", "").replace("-", ""));
                sms.setDateAndTime(DateUtils.formatDate(dateAndTime));
                sms.setSystemId(systemId);
                sms.setType(Integer.valueOf(type));
                sms.setReadState(Boolean.parseBoolean(readState));
                sms.setDeviceId(
                        sms.getRemoteId() != "" ? sms.getDeviceId() : Device.registeredDevice().getLogin());
                sms.save();

                allSms.add(sms);

                c.moveToNext();
            }
        }
        // else {
        // throw new RuntimeException("You have no SMS");
        // }
        c.close();
    } else {
        EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, getString(R.string.permission_denied_sms)));
        stopSelf();
    }
}

From source file:com.bilibili.boxing.model.task.impl.ImageTask.java

private int getTotalCount(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum,
        boolean isNeedGif) {
    Cursor allCursor = null;//from  w w  w .j  a  v a2 s  . co  m
    int result = 0;
    try {
        if (isDefaultAlbum) {
            allCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, SELECTION_IMAGE_MIME_TYPE,
                    SELECTION_ARGS_IMAGE_MIME_TYPE, Images.Media.DATE_MODIFIED + " desc");
        } else {
            if (isNeedGif) {
                allCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, SELECTION_ID,
                        new String[] { bucketId, "image/jpeg", "image/png", "image/jpg", "image/gif" },
                        Images.Media.DATE_MODIFIED + " desc");
            } else {
                allCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, SELECTION_ID_WITHOUT_GIF,
                        new String[] { bucketId, "image/jpeg", "image/png", "image/jpg" },
                        Images.Media.DATE_MODIFIED + " desc");
            }
        }
        if (allCursor != null) {
            result = allCursor.getCount();
        }
    } finally {
        if (allCursor != null) {
            allCursor.close();
        }
    }
    return result;
}

From source file:com.akop.bach.fragment.xboxlive.SentMessagesFragment.java

@Override
public void onCreate(Bundle state) {
    super.onCreate(state);

    if (mAccount == null) {
        Bundle args = getArguments();/*from  ww  w.j  ava  2s. c  o  m*/
        ContentResolver cr = getActivity().getContentResolver();

        mAccount = (XboxLiveAccount) args.getParcelable("account");
        mTitleId = getFirstTitleId(cr.query(SentMessages.CONTENT_URI, new String[] { SentMessages._ID, },
                SentMessages.ACCOUNT_ID + "=" + mAccount.getId(), null, SentMessages.DEFAULT_SORT_ORDER));
    }

    if (state != null && state.containsKey("account")) {
        mAccount = (XboxLiveAccount) state.getParcelable("account");
        mTitleId = state.getLong("titleId");
    }

    setHasOptionsMenu(true);
}

From source file:com.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testStatsUpdate() {
    ContentResolver r = getContext().getContentResolver();

    // First, delete any existing data associated with the TEST tag.
    Uri uri = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 0, 0);
    assertNotNull(uri);/*from   w  w w.  j  a  v  a2 s . co  m*/
    assertEquals(1, r.delete(uri, null, null));
    assertFalse(r.query(uri, null, null, null, null).moveToNext());

    // Now, add a known quantity to the TEST tag.
    Uri u2 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 1, 0.5);
    assertFalse(uri.equals(u2));

    Cursor c = r.query(u2, null, null, null, null);
    assertTrue(c.moveToNext());
    assertEquals(1, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT)));
    assertEquals(0.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM)));
    assertFalse(c.moveToNext()); // Only one.

    // Add another known quantity to TEST (should sum with the first).
    Uri u3 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, 2, 1.0);
    assertEquals(u2, u3);
    c.requery();
    assertTrue(c.moveToNext());
    assertEquals(3, c.getInt(c.getColumnIndex(Checkin.Stats.COUNT)));
    assertEquals(1.5, c.getDouble(c.getColumnIndex(Checkin.Stats.SUM)));
    assertFalse(c.moveToNext()); // Only one.

    // Now subtract the values; the whole row should disappear.
    Uri u4 = Checkin.updateStats(r, Checkin.Stats.Tag.TEST, -3, -1.5);
    assertNull(u4);
    c.requery();
    assertFalse(c.moveToNext()); // Row has been deleted.
    c.close();
}

From source file:com.marvin.rocklock.navigation.CursorGroupedSongPicker.java

@Override
public LinkedHashMap<Integer, String> getSearchResults(Context context, String search) {
    ContentResolver resolver = context.getContentResolver();
    search.replace("'", "''");
    String filter = mGroupProjection[GROUP_NAME] + " LIKE '" + search + "%'";
    Cursor query = resolver.query(mGroupUri, mGroupProjection, filter, null, null);
    LinkedHashMap<Integer, String> results = null;
    if (query != null && query.moveToFirst()) {
        results = new LinkedHashMap<Integer, String>();
        do {//w w  w.j av a  2 s.  c o m
            results.put(query.getInt(0), query.getString(1));
        } while (query.moveToNext());
    }
    if (query != null) {
        query.close();
    }
    return results;
}

From source file:com.trellmor.berrymotes.sync.EmoteDownloader.java

public void deleteSubreddit(String subreddit, ContentResolver contentResolver) throws IOException {

    Log.info(" Removing emotes of " + subreddit);
    Cursor c = contentResolver.query(EmotesContract.Emote.CONTENT_URI_DISTINCT,
            new String[] { EmotesContract.Emote.COLUMN_IMAGE }, EmotesContract.Emote.COLUMN_SUBREDDIT + "=?",
            new String[] { subreddit }, null);

    if (c.moveToFirst()) {
        final int POS_IMAGE = c.getColumnIndex(EmotesContract.Emote.COLUMN_IMAGE);

        do {/* w  ww .  j  a  v  a2s.c o m*/
            checkStorageAvailable();
            File file = new File(c.getString(POS_IMAGE));
            if (file.exists()) {
                file.delete();
            }
        } while (c.moveToNext());
    }

    c.close();

    int deletes = mContentResolver.delete(EmotesContract.Emote.CONTENT_URI,
            EmotesContract.Emote.COLUMN_SUBREDDIT + "=?", new String[] { subreddit });
    Log.info("Removed emotes: " + Integer.toString(deletes));
    synchronized (mSyncResult) {
        mSyncResult.stats.numDeletes += deletes;
    }
}

From source file:com.bilibili.boxing.model.task.impl.ImageTask.java

private Cursor query(ContentResolver cr, String bucketId, String[] columns, boolean isDefaultAlbum,
        boolean isNeedGif, String imageMimeType, String[] args, String order, String selectionId) {
    Cursor resultCursor;/*w w  w. ja v a 2s . c  o m*/
    if (isDefaultAlbum) {
        resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, imageMimeType, args, order);
    } else {
        if (isNeedGif) {
            resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                    new String[] { bucketId, args[0], args[1], args[2], args[3] }, order);
        } else {
            resultCursor = cr.query(Images.Media.EXTERNAL_CONTENT_URI, columns, selectionId,
                    new String[] { bucketId, args[0], args[1], args[2] }, order);
        }
    }
    return resultCursor;
}