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.conferenceengineer.android.iosched.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 .j  a v a  2s  .co 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.conference_ic_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));
    }
    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.xboxlive.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.BOXART_URL },
            Games.ACCOUNT_ID + "=" + mAccount.getId(), null, Games.DEFAULT_SORT_ORDER);
}

From source file:com.group13.androidsdk.mycards.NotificationService.java

private List<NotificationRule> getCalendarAsNotificationRules() {
    Calendar beginTime = Calendar.getInstance();
    beginTime.set(Calendar.HOUR_OF_DAY, 0);
    beginTime.set(Calendar.MINUTE, 0);
    beginTime.set(Calendar.SECOND, 0);
    long startMillis = beginTime.getTimeInMillis();

    Calendar endTime = Calendar.getInstance();
    endTime.set(Calendar.HOUR_OF_DAY, 23);
    endTime.set(Calendar.MINUTE, 59);
    endTime.set(Calendar.SECOND, 59);
    long endMillis = endTime.getTimeInMillis();

    Cursor cur;/*from  w  w w  .j  a  v a 2  s  .c o m*/
    ContentResolver cr = getContentResolver();

    String selection = Instances.CALENDAR_ID + " = 1";
    String[] selectionArgs = new String[] {};

    Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
    ContentUris.appendId(builder, startMillis);
    ContentUris.appendId(builder, endMillis);

    cur = cr.query(builder.build(), INSTANCE_PROJECTION, selection, selectionArgs, null);

    List<NotificationRule> rules = new ArrayList<>();

    if (cur == null) {
        return rules;
    }

    while (cur.moveToNext()) {
        Calendar beginCalendar = Calendar.getInstance();
        beginCalendar.setTimeInMillis(cur.getLong(PROJECTION_BEGIN_INDEX));

        Calendar endCalendar = Calendar.getInstance();
        endCalendar.setTimeInMillis(cur.getLong(PROJECTION_END_INDEX));

        SimpleDatePattern datePattern = new SimpleDatePattern(beginCalendar.getTime(), endCalendar.getTime(), 0,
                0);
        rules.add(new NotificationRule(-1, datePattern, true));
    }
    cur.close();
    return rules;
}

From source file:com.tct.mail.NotificationActionIntentService.java

/**
 * Give the chance to restore the mail's status,here we restore to queue status
 * @param context/*www.  j  av a2  s . co m*/
 * @param boxId is the outbox's id
 */
private void cleanFaildMailStatus(Context context, long boxId) {
    Cursor cursor = null;
    ContentResolver resolver = context.getContentResolver();
    ArrayList<Long> pendingSendMails = new ArrayList<Long>();
    ContentValues value = new ContentValues();
    //query the failed mails
    try {
        cursor = resolver.query(EmailContent.Message.CONTENT_URI,
                EmailContent.Message.ID_COLUMN_WITH_STATUS_PROJECTION,
                MessageColumns.SENDING_STATUS + "=?" + " AND " + MessageColumns.MAILBOX_KEY + "=?",
                new String[] { Long.toString(EmailContent.Message.MAIL_IN_FAILED_STATUS),
                        Long.toString(boxId) },
                null);
        while (cursor.moveToNext()) {
            pendingSendMails.add(cursor.getLong(0));
        }
    } catch (Exception e) {
        LogUtils.e(LogUtils.TAG, e, "Exception happen during queue the failed mails in cleanFaildMailStatus ");
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    //update the mails status
    if (pendingSendMails.size() > 0) {
        for (long id : pendingSendMails) {
            value.clear();
            Uri uri = ContentUris.withAppendedId(EmailContent.Message.CONTENT_URI, id);
            value.put(MessageColumns.SENDING_STATUS, EmailContent.Message.MAIL_IN_QUEUE_STATUS);
            resolver.update(uri, value, null, null);
            LogUtils.d(LogUtils.TAG, "update the mail's status from FAIL to QUEUE,current message id is %d",
                    id);
        }
    }
    pendingSendMails.clear();
}

From source file:com.google.android.apps.iosched.calendar.SessionAlarmService.java

/**
 * Constructs and triggers system notification for when starred sessions are about to begin.
 *///from  www . j a va 2  s .  c  om
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notifySession(final long sessionStart, final long sessionEnd, final long alarmOffset) {
    long currentTime = System.currentTimeMillis();
    if (sessionStart < currentTime) {
        return;
    }

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

    final ContentResolver resolver = getContentResolver();
    final Uri starredBlockUri = ScheduleContract.Blocks
            .buildStarredSessionsUri(ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
    Cursor cursor = resolver.query(starredBlockUri, new String[] { ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
            ScheduleContract.Sessions.SESSION_TITLE }, null, null, null);
    int starredCount = 0;
    ArrayList<String> starredSessionTitles = new ArrayList<String>();
    while (cursor.moveToNext()) {
        starredSessionTitles.add(cursor.getString(1));
        starredCount = cursor.getInt(0);
    }

    if (starredCount < 1) {
        return;
    }

    // Generates the pending intent which gets fired when the user touches on the notification.
    Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri);
    sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent, 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);
    }

    // Construct a notification. Use Jelly Bean (API 16) rich notifications if possible.
    Notification notification;
    if (UIUtils.hasJellyBean()) {
        // Rich notifications
        Notification.Builder builder = new Notification.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 (minutesLeft > 5) {
            builder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, sessionEnd, 5));
        }
        Notification.InboxStyle richNotification = new Notification.InboxStyle(builder)
                .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));
        }
        notification = richNotification.build();

    } else {
        // Pre-Jelly Bean non-rich notifications
        notification = 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).getNotification();
    }
    NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(NOTIFICATION_ID, notification);
}

From source file:com.murrayc.galaxyzoo.app.syncadapter.SyncAdapter.java

private int getNotDoneCount() {
    final ContentResolver resolver = getContentResolver();

    final Cursor c = resolver.query(Item.ITEMS_URI, PROJECTION_COUNT_AS_COUNT, WHERE_CLAUSE_NOT_DONE, null,
            null);/* ww w . j  a  va2s. c o m*/
    c.moveToFirst();
    final int result = c.getInt(0);
    c.close();
    return result;
}

From source file:net.naonedbus.manager.impl.FavoriManager.java

/**
 * @param contentResolver//from  www. j a  v a2 s  .c o m
 * @return les favoris avec les donnes sur la ligne et le sens
 */
public List<Favori> getFull(final ContentResolver contentResolver) {
    final Uri.Builder builder = FavoriProvider.CONTENT_URI.buildUpon();
    builder.path(FavoriProvider.FAVORIS_FULL_URI_PATH_QUERY);

    return getFromCursorFull(contentResolver.query(builder.build(), null, null, null, null));
}

From source file:com.murrayc.galaxyzoo.app.syncadapter.SyncAdapter.java

private int getUploadedCount() {
    final ContentResolver resolver = getContentResolver();

    final Cursor c = resolver.query(Item.ITEMS_URI, PROJECTION_COUNT_AS_COUNT, WHERE_CLAUSE_UPLOADED,
            new String[] {}, null);

    c.moveToFirst();/*from   ww w. j a  va 2 s. co m*/
    final int result = c.getInt(0);
    c.close();
    return result;
}

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

public static void addToPlaylist(Context context, long[] ids, long playlistid) {
    if (ids == null) {
        // this shouldn't happen (the menuitems shouldn't be visible
        // unless the selected item represents something playable
        Log.e("MusicBase", "ListSelection null");
    } else {//from w w  w  .j  a v a2  s  .c  o  m
        int size = ids.length;
        ContentResolver resolver = context.getContentResolver();
        // need to determine the number of items currently in the playlist,
        // so the play_order field can be maintained.
        String[] cols = new String[] { "count(*)" };
        Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
        Cursor cur = resolver.query(uri, cols, null, null, null);
        cur.moveToFirst();
        int base = cur.getInt(0);
        cur.close();
        int numinserted = 0;
        for (int i = 0; i < size; i += 1000) {
            makeInsertItems(ids, i, 1000, base);
            numinserted += resolver.bulkInsert(uri, sContentValuesCache);
        }
        String message = context.getResources().getQuantityString(R.plurals.NNNtrackstoplaylist, numinserted,
                numinserted);
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
        //mLastPlaylistSelected = playlistid;
    }
}

From source file:com.example.android.directoryselection.DirectorySelectionFragment.java

/**
 * Updates the current directory of the uri passed as an argument and its children directories.
 * And updates the {@link #mRecyclerView} depending on the contents of the children.
 *
 * @param uri The uri of the current directory.
 *///ww  w.  jav a 2s.c o m
//VisibileForTesting
void updateDirectoryEntries(Uri uri) {
    ContentResolver contentResolver = getActivity().getContentResolver();
    Uri docUri = DocumentsContract.buildDocumentUriUsingTree(uri, DocumentsContract.getTreeDocumentId(uri));
    Uri childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree(uri,
            DocumentsContract.getTreeDocumentId(uri));

    Cursor docCursor = contentResolver.query(docUri,
            new String[] { Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE }, null, null, null);
    try {
        while (docCursor.moveToNext()) {
            Log.d(TAG, "found doc =" + docCursor.getString(0) + ", mime=" + docCursor.getString(1));
            mCurrentDirectoryUri = uri;
            mCurrentDirectoryTextView.setText(docCursor.getString(0));
            mCreateDirectoryButton.setEnabled(true);
        }
    } finally {
        closeQuietly(docCursor);
    }

    Cursor childCursor = contentResolver.query(childrenUri,
            new String[] { Document.COLUMN_DISPLAY_NAME, Document.COLUMN_MIME_TYPE }, null, null, null);
    try {
        List<DirectoryEntry> directoryEntries = new ArrayList<>();
        while (childCursor.moveToNext()) {
            Log.d(TAG, "found child=" + childCursor.getString(0) + ", mime=" + childCursor.getString(1));
            DirectoryEntry entry = new DirectoryEntry();
            entry.fileName = childCursor.getString(0);
            entry.mimeType = childCursor.getString(1);
            directoryEntries.add(entry);
        }
        mAdapter.setDirectoryEntries(directoryEntries);
        mAdapter.notifyDataSetChanged();
    } finally {
        closeQuietly(childCursor);
    }
}