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.gdgdevfest.android.apps.devfestbcn.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime;
    if (sessionStart < (currentTime = UIUtils.getCurrentTime(this)))
        return;//  w  w  w  . ja  v a  2 s.c  o m

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
        return;
    }

    final ContentResolver cr = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor c = cr.query(starredBlockUri, SessionDetailQuery.PROJECTION, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
    String sessionId = null; // needed to get session track icon
    while (c.moveToNext()) {
        sessionId = c.getString(SessionDetailQuery.SESSION_ID);
        starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
        starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
        starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
    }
    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user taps on the notification.
    // NOTE: Use TaskStackBuilder to comply with Android's design guidelines
    // related to navigation from notifications.
    PendingIntent pi = TaskStackBuilder.create(this).addNextIntent(new Intent(this, HomeActivity.class))
            .addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
            .getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);

    final Resources res = getResources();
    String contentText;
    int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
    if (minutesLeft < 1) {
        minutesLeft = 1;
    }

    if (starredCount == 1) {
        contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
    } else {
        contentText = res.getQuantityString(R.plurals.session_notification_text, starredCount - 1, minutesLeft,
                starredCount - 1);
    }

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(starredSessionTitles.get(0)).setContentText(contentText)
            .setTicker(res.getQuantityString(R.plurals.session_notification_ticker, starredCount, starredCount))
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setLights(SessionAlarmService.NOTIFICATION_ARGB_COLOR, SessionAlarmService.NOTIFICATION_LED_ON_MS,
                    SessionAlarmService.NOTIFICATION_LED_OFF_MS)
            .setSmallIcon(R.drawable.ic_stat_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (starredCount == 1) {
        // get the track icon to show as the notification big picture
        Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
        Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION, null, null, null);
        if (tracksCursor.moveToFirst()) {
            String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
            int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
            Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(), trackName, trackColour);
            if (trackIcon != null) {
                notifBuilder.setLargeIcon(trackIcon);
            }
        }
    }
    if (minutesLeft > 5) {
        notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, sessionEnd, 5));
    }
    if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(R.drawable.ic_map_holo_dark, res.getString(R.string.title_map),
                createRoomMapIntent(starredSessionRoomIds.get(0)));
    }
    NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
            .setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount));

    // Adds starred sessions starting at this time block to the notification.
    for (int i = 0; i < starredCount; i++) {
        richNotification.addLine(starredSessionTitles.get(i));
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

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

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

    mCp = new CachePolicy();
    mCp.resizeHeight = 96;/*w ww.j  a  va  2 s .com*/

    if (mAccount == null) {
        Bundle args = getArguments();
        ContentResolver cr = getActivity().getContentResolver();

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

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

    setHasOptionsMenu(true);
}

From source file:com.android.exchange.adapter.EmailSyncAdapter.java

/**
 * Note that messages in the deleted database preserve the message's unique id; therefore, we
 * can utilize this id to find references to the message.  The only reference situation at this
 * point is in the Body table; it is when sending messages via SmartForward and SmartReply
 *//*from  w w  w  . j  a v a2  s  . co  m*/
private static boolean messageReferenced(ContentResolver cr, long id) {
    // See if this id is referenced in a body
    Cursor c = cr.query(Body.CONTENT_URI, Body.ID_PROJECTION, WHERE_BODY_SOURCE_MESSAGE_KEY,
            new String[] { Long.toString(id) }, null);
    try {
        return c.moveToFirst();
    } finally {
        c.close();
    }
}

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

@MediumTest
public void testPropertiesRestricted() throws Exception {
    ContentResolver r = getContext().getContentResolver();

    // The test app doesn't have the permission to access properties,
    // so any attempt to do so should fail.
    try {/*from  w  w w .  j ava 2  s .  c  o m*/
        r.insert(Checkin.Properties.CONTENT_URI, new ContentValues());
        fail("SecurityException expected");
    } catch (SecurityException e) {
        // expected
    }

    try {
        r.query(Checkin.Properties.CONTENT_URI, null, null, null, null);
        fail("SecurityException expected");
    } catch (SecurityException e) {
        // expected
    }
}

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

@MediumTest
public void testCrashReport() throws Exception {
    long start = System.currentTimeMillis();
    ContentResolver r = getContext().getContentResolver();

    // Log a test (fake) crash report.
    Checkin.reportCrash(r, new CrashData("Test", "Test Activity", new BuildData("Test Build", "123", start),
            new ThrowableData(new RuntimeException("Test Exception"))));

    // Crashes aren't indexed; go through them all to find the one we added.
    Cursor c = r.query(Checkin.Crashes.CONTENT_URI, null, null, null, null);

    Uri uri = null;/*w  w  w.  j  a  v a2  s  .com*/
    while (c.moveToNext()) {
        String coded = c.getString(c.getColumnIndex(Checkin.Crashes.DATA));
        byte[] bytes = Base64.decodeBase64(coded.getBytes());
        CrashData crash = new CrashData(new DataInputStream(new ByteArrayInputStream(bytes)));

        // Should be exactly one recently added "Test" crash.
        if (crash.getId().equals("Test") && crash.getTime() > start) {
            assertEquals("Test Activity", crash.getActivity());
            assertEquals("Test Build", crash.getBuildData().getFingerprint());
            assertEquals("Test Exception", crash.getThrowableData().getMessage());

            assertNull(uri);
            uri = ContentUris.withAppendedId(Checkin.Crashes.CONTENT_URI,
                    c.getInt(c.getColumnIndex(Checkin.Crashes._ID)));
        }
    }
    assertNotNull(uri);
    c.close();

    // Update the "logs" column.
    ContentValues values = new ContentValues();
    values.put(Checkin.Crashes.LOGS, "Test Logs");
    assertEquals(1, r.update(uri, values, null, null));

    c = r.query(uri, null, null, null, null);
    assertTrue(c.moveToNext());
    String logs = c.getString(c.getColumnIndex(Checkin.Crashes.LOGS));
    assertEquals("Test Logs", logs);
    c.deleteRow();
    c.close();

    c.requery();
    assertFalse(c.moveToNext());
    c.close();
}

From source file:com.example.android.scopeddirectoryaccess.ScopedDirectoryAccessFragment.java

private void updateDirectoryEntries(Uri uri) {
    mDirectoryEntries.clear();//w  ww . j a  va  2  s .  com
    ContentResolver contentResolver = getActivity().getContentResolver();
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri));
    Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri,
            DocumentsContract.getTreeDocumentId(uri));

    try (Cursor docCursor = contentResolver.query(docUri, DIRECTORY_SELECTION, null, null, null)) {
        while (docCursor != null && docCursor.moveToNext()) {
            mCurrentDirectoryTextView.setText(docCursor
                    .getString(docCursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME)));
        }
    }

    try (Cursor childCursor = contentResolver.query(childrenUri, DIRECTORY_SELECTION, null, null, null)) {
        while (childCursor != null && childCursor.moveToNext()) {
            DirectoryEntry entry = new DirectoryEntry();
            entry.fileName = childCursor
                    .getString(childCursor.getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME));
            entry.mimeType = childCursor
                    .getString(childCursor.getColumnIndex(DocumentsContract.Document.COLUMN_MIME_TYPE));
            mDirectoryEntries.add(entry);
        }

        if (mDirectoryEntries.isEmpty()) {
            mNothingInDirectoryTextView.setVisibility(View.VISIBLE);
        } else {
            mNothingInDirectoryTextView.setVisibility(View.GONE);
        }
        mAdapter.setDirectoryEntries(mDirectoryEntries);
        mAdapter.notifyDataSetChanged();
    }
}

From source file:com.bangz.smartmute.services.LocationMuteService.java

private void handleAddGeofence(Uri uri) {

    LogUtils.LOGD(TAG, "Handling add one geofence id = " + ContentUris.parseId(uri));
    if (PrefUtils.isEnableSmartMute(this) == false) {
        LogUtils.LOGD(TAG, "Smart Mute is disabled by user. quit add one geofdence");
        return;// ww  w. j  a  v  a  2  s  . co m
    }

    ContentResolver cr = getContentResolver();

    Cursor cursor = cr.query(uri, PROJECTS, SELECT_STRING, DEF_SELECT_ARGUMENTS, RulesColumns._ID);
    if (cursor.getCount() == 0) {
        cursor.close();
        LogUtils.LOGD(TAG, "handleAddGeofence: no record selected,but id = " + ContentUris.parseId(uri));
        return;
    }

    List<Geofence> geofences = fillGeofences(cursor);
    cursor.close();

    boolean b = addGeofences(geofences);
    LogUtils.LOGD(TAG, (b ? "Successful" : "Failed") + " add one geofence id = " + ContentUris.parseId(uri));

}

From source file:com.chatwing.whitelabel.managers.CommunicationModeManager.java

public boolean processMessageNotInCurrentCommunicationBox(Message message) {
    Uri uri;/*ww  w.jav a2 s . c om*/
    String unreadColumn;
    if (message.isPrivate()) {
        uri = ChatWingContentProvider.getConversationWithIdUri(message.getConversationID());
        unreadColumn = ConversationTable.UNREAD_COUNT;
    } else {
        uri = ChatWingContentProvider.getChatBoxWithIdUri(message.getChatBoxId());
        unreadColumn = ChatBoxTable.UNREAD_COUNT;
    }

    AppCompatActivity activity = mActivityDelegate.getActivity();
    ContentResolver contentResolver = activity.getContentResolver();

    // Get unread count of the correct chat box.
    Cursor cursor = null;
    int unreadCount = -1;
    try {
        cursor = contentResolver.query(uri, new String[] { unreadColumn }, null, null, null);
        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            unreadCount = cursor.getInt(cursor.getColumnIndex(unreadColumn));
        }
        // else {
        // The chat box is not available in the DB.
        // TODO: may create the chat box or trigger a sync operation.
        // }
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }

    if (unreadCount == -1) {
        // 1. Something was wrong (the chat box id is invalid
        // or can't query the chat box from DB).
        // Let's stop.
        // 2. Conversation not found. There might be a case client received
        // a msg but there is not conversation created beforehand. We can
        // just ignore that and wait for "remote_unread"
        if (message.isPrivate()) {
            Intent intent = new Intent(activity, SyncCommunicationBoxesIntentService.class);
            intent.putExtra(SyncCommunicationBoxesIntentService.UPDATE_CATEGORIES_FLAG, false);
            intent.putExtra(SyncCommunicationBoxesIntentService.UPDATE_CONVERSATION_FLAG, true);
            activity.startService(intent);
        }
        return false;
    }

    // Increase unread count in DB
    if (message.isPrivate()) {
        return updateConversationUnreadCount(message.getConversationID(), ++unreadCount);
    } else {
        return updateChatBoxUnreadCountInDB(message.getChatBoxId(), ++unreadCount);
    }
}

From source file:com.bitants.wally.fragments.SavedImagesFragment.java

@Override
public boolean handleMessage(Message msg) {
    switch (msg.what) {
    case GET_IMAGES_FROM_STORAGE:
        if (getActivity() != null) {
            String[] projection = { MediaStore.Images.Media._ID };
            ContentResolver contentResolver = getActivity().getContentResolver();
            Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

            cursor = contentResolver.query(mImageUri, projection, MediaStore.Images.Media.DATA + " like ? ",
                    new String[] { "%/Wally/%" }, MediaStore.Audio.Media.DATE_ADDED + " DESC");

            initObserver(cursor);//from   ww w.  ja va 2  s  .  co m

            int what;
            if (recyclerSavedImagesAdapter == null) {
                what = SET_IMAGES_TO_ADAPTER;
            } else {
                what = UPDATE_ADAPTER;
            }
            uiHandler.sendEmptyMessage(what);
        }
        break;

    case SET_IMAGES_TO_ADAPTER:
        hideLoader();
        recyclerSavedImagesAdapter = new RecyclerSavedImagesAdapter(getFileUrisFromCursor(cursor), itemSize,
                selectedItems);
        gridView.setAdapter(recyclerSavedImagesAdapter);
        setupAdapter(recyclerSavedImagesAdapter);
        gridView.scheduleLayoutAnimation();
        break;

    case UPDATE_ADAPTER:
        ArrayList<Uri> newFilePaths = getFileUrisFromCursor(cursor);
        ArrayList<Uri> oldFilePaths = recyclerSavedImagesAdapter.getData();
        recyclerSavedImagesAdapter.setData(newFilePaths);
        checkIfAddedOrRemovedItem(oldFilePaths, newFilePaths);
        break;

    default:
        break;
    }
    return false;
}

From source file:com.chatwingsdk.managers.CommunicationModeManager.java

public boolean processMessageNotInCurrentCommunicationBox(Message message) {
    Uri uri;/*from  w  w  w  . ja va  2s  . c  o m*/
    String unreadColumn;
    if (message.isPrivate()) {
        uri = ChatWingContentProvider.getConversationWithIdUri(message.getConversationID());
        unreadColumn = ConversationTable.UNREAD_COUNT;
    } else {
        uri = ChatWingContentProvider.getChatBoxWithIdUri(message.getChatBoxId());
        unreadColumn = ChatBoxTable.UNREAD_COUNT;
    }

    ActionBarActivity activity = mActivityDelegate.getActivity();
    ContentResolver contentResolver = activity.getContentResolver();

    // Get unread count of the correct chat box.
    Cursor cursor = null;
    int unreadCount = -1;
    try {
        cursor = contentResolver.query(uri, new String[] { unreadColumn }, null, null, null);
        if (cursor.getCount() > 0 && cursor.moveToFirst()) {
            unreadCount = cursor.getInt(cursor.getColumnIndex(unreadColumn));
        }
        // else {
        // The chat box is not available in the DB.
        // TODO: may create the chat box or trigger a sync operation.
        // }
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }

    if (unreadCount == -1) {
        // 1. Something was wrong (the chat box id is invalid
        // or can't query the chat box from DB).
        // Let's stop.
        // 2. Conversation not found. There might be a case client received
        // a msg but there is not conversation created beforehand. We can
        // just ignore that and wait for "remote_unread"
        if (message.isPrivate()) {
            Intent intent = new Intent(activity, SyncCommunicationBoxesIntentService.class);
            intent.putExtra(SyncCommunicationBoxesIntentService.UPDATE_CATEGORIES_FLAG, false);
            intent.putExtra(SyncCommunicationBoxesIntentService.UPDATE_CONVERSATION_FLAG, true);
            activity.startService(intent);
        }
        return false;
    }

    // Increase unread count in DB
    if (message.isPrivate()) {
        return updateConversationUnreadCount(message.getConversationID(), ++unreadCount);
    } else {
        return updateChatBoxUnreadCountInDB(message.getChatBoxId(), ++unreadCount);
    }
}