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.app.uafeed.activity.EditFeedActivity.java

public void onClickOk(View view) {
    // only in insert mode

    String url = mUrlEditText.getText().toString();
    ContentResolver cr = getContentResolver();

    if (!url.startsWith(Constants.HTTP_SCHEME) && !url.startsWith(Constants.HTTPS_SCHEME)) {
        url = Constants.HTTP_SCHEME + url;
    }/* w ww  .  j a va  2s .c  o m*/

    Cursor cursor = cr.query(FeedColumns.CONTENT_URI, null, FeedColumns.URL + Constants.DB_ARG,
            new String[] { url }, null);

    if (cursor.moveToFirst()) {
        cursor.close();
        Toast.makeText(EditFeedActivity.this, R.string.error_feed_url_exists, Toast.LENGTH_LONG).show();
    } else {
        cursor.close();
        ContentValues values = new ContentValues();

        values.put(FeedColumns.URL, url);
        values.putNull(FeedColumns.ERROR);

        String name = mNameEditText.getText().toString();

        if (name.trim().length() > 0) {
            values.put(FeedColumns.NAME, name);
        }
        values.put(FeedColumns.RETRIEVE_FULLTEXT, mRetrieveFulltextCb.isChecked() ? 1 : null);
        cr.insert(FeedColumns.CONTENT_URI, values);
    }

    setResult(RESULT_OK);
    finish();
}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Resolve sync provider information */
private void resolveSyncProvider(long providerId, ContentResolver cr) {
    Uri providerUri = ContentUris.withAppendedId(PasswdSafeContract.Providers.CONTENT_URI, providerId);
    Cursor providerCursor = cr.query(providerUri, PasswdSafeContract.Providers.PROJECTION, null, null, null);
    try {//from   ww w.  j a v a  2  s .  co m
        if ((providerCursor != null) && providerCursor.moveToFirst()) {
            String typeStr = providerCursor.getString(PasswdSafeContract.Providers.PROJECTION_IDX_TYPE);
            try {
                itsSyncType = ProviderType.valueOf(typeStr);
                itsTitle = providerCursor.getString(PasswdSafeContract.Providers.PROJECTION_IDX_ACCT);
            } catch (IllegalArgumentException e) {
                Log.e(TAG, "Unknown provider type: " + typeStr);
            }
        }
    } finally {
        if (providerCursor != null) {
            providerCursor.close();
        }
    }
}

From source file:com.google.samples.apps.iosched.service.SessionCalendarService.java

/**
 * Processes all sessions in the/*from w  ww .  ja va2  s. c o m*/
 * {@link com.google.samples.apps.iosched.provider.ScheduleProvider},
 * adding or removing calendar events to/from the specified Google Calendar depending on whether
 * a session is in the user's schedule or not.
 */
private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver,
        final long calendarId) {

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

    // Unable to find the Calendar associated with the user. Stop here.
    if (calendarId == INVALID_CALENDAR_ID) {
        return batch;
    }

    // Retrieves all sessions. For each session, add to Calendar if starred and attempt to
    // remove from Calendar if unstarred.
    Cursor cursor = resolver.query(ScheduleContract.Sessions.CONTENT_URI, SessionsQuery.PROJECTION, null, null,
            null);

    if (cursor != null) {
        while (cursor.moveToNext()) {
            Uri uri = ScheduleContract.Sessions.buildSessionUri(Long.valueOf(cursor.getLong(0)).toString());
            boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_IN_MY_SCHEDULE) == 1);
            if (isAddEvent) {
                batch.addAll(processSessionCalendar(resolver, calendarId, isAddEvent, uri,
                        cursor.getLong(SessionsQuery.SESSION_START), cursor.getLong(SessionsQuery.SESSION_END),
                        cursor.getString(SessionsQuery.SESSION_TITLE),
                        cursor.getString(SessionsQuery.ROOM_NAME)));
            }
        }
        cursor.close();
    }

    return batch;
}

From source file:com.jjcamera.apps.iosched.service.SessionAlarmService.java

private void notifySession(final long sessionStart, final long alarmOffset) {
    long currentTime = UIUtils.getCurrentTime(this);
    final long intervalEnd = sessionStart + MILLI_TEN_MINUTES;
    LOGD(TAG, "Considering notifying for time interval.");
    LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;/* ww  w . j av a 2s .  c om*/
    }

    if (!SettingsUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LOGD(TAG, "Skipping session notification for sessions. Disabled in settings.");
        return;
    }

    // Avoid repeated notifications.
    if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(this,
            ScheduleContract.Blocks.generateBlockId(sessionStart, intervalEnd))) {
        LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor c = null;
    try {
        c = cr.query(ScheduleContract.Sessions.CONTENT_MY_SCHEDULE_URI, SessionDetailQuery.PROJECTION,
                ScheduleContract.Sessions.STARTING_AT_TIME_INTERVAL_SELECTION,
                ScheduleContract.Sessions.buildAtTimeIntervalArgs(sessionStart, intervalEnd), null);
        int starredCount = c.getCount();
        LOGD(TAG, "# starred sessions in that interval: " + c.getCount());
        String singleSessionId = null;
        String singleSessionRoomId = null;
        ArrayList<String> starredSessionTitles = new ArrayList<String>();
        while (c.moveToNext()) {
            singleSessionId = c.getString(SessionDetailQuery.SESSION_ID);
            singleSessionRoomId = c.getString(SessionDetailQuery.ROOM_ID);
            starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
            LOGD(TAG, "-> Title: " + c.getString(SessionDetailQuery.SESSION_TITLE));
        }
        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.
        Intent baseIntent = new Intent(this, MyScheduleActivity.class);
        baseIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
        TaskStackBuilder taskBuilder = TaskStackBuilder.create(this).addNextIntent(baseIntent);

        // For a single session, tapping the notification should open the session details (b/15350787)
        if (starredCount == 1) {
            taskBuilder.addNextIntent(
                    new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions.buildSessionUri(singleSessionId)));
        }

        PendingIntent pi = taskBuilder.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)
                .setColor(getResources().getColor(R.color.theme_primary))
                .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) {
            notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
                    String.format(res.getString(R.string.snooze_x_min), 5),
                    createSnoozeIntent(sessionStart, intervalEnd, 5));
        }
        /*if (starredCount == 1 && SettingsUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(R.drawable.ic_map_holo_dark,
                res.getString(R.string.title_map),
                createRoomMapIntent(singleSessionRoomId));
        }*/
        String bigContentTitle;
        if (starredCount == 1 && starredSessionTitles.size() > 0) {
            bigContentTitle = starredSessionTitles.get(0);
        } else {
            bigContentTitle = res.getQuantityString(R.plurals.session_notification_title, starredCount,
                    minutesLeft, starredCount);
        }
        NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(notifBuilder)
                .setBigContentTitle(bigContentTitle);

        // 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);
        LOGD(TAG, "Now showing notification.");
        nm.notify(NOTIFICATION_ID, richNotification.build());
    } finally {
        if (c != null) {
            try {
                c.close();
            } catch (Exception ignored) {
            }
        }
    }
}

From source file:me.myatminsoe.myansms.Message.java

/**
 * Fetch MMS parts./*from ww  w  . j  av  a  2 s.c  om*/
 *
 * @param context {@link Context}
 */
private void fetchMmsParts(final Context context) {
    final ContentResolver cr = context.getContentResolver();
    Cursor cursor = cr.query(URI_PARTS, null, PROJECTION_PARTS[INDEX_MID] + " = ?",
            new String[] { String.valueOf(id) }, null);
    if (cursor == null || !cursor.moveToFirst()) {
        return;
    }
    final int iID = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_ID]);
    final int iCT = cursor.getColumnIndex(PROJECTION_PARTS[INDEX_CT]);
    final int iText = cursor.getColumnIndex("text");
    do {
        final int pid = cursor.getInt(iID);
        final String ct = cursor.getString(iCT);

        // get part
        InputStream is = null;

        final Uri uri = ContentUris.withAppendedId(URI_PARTS, pid);
        if (uri == null) {

            continue;
        }
        try {
            is = cr.openInputStream(uri);
        } catch (IOException | NullPointerException e) {

        }
        if (is == null) {

            if (iText >= 0 && ct != null && ct.startsWith("text/")) {
                body = cursor.getString(iText);
            }
            continue;
        }
        if (ct == null) {
            continue;
        }
        if (ct.startsWith("image/")) {
            picture = BitmapFactory.decodeStream(is);
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("video/") || ct.startsWith("audio/")) {
            picture = BITMAP_PLAY;
            final Intent i = new Intent(Intent.ACTION_VIEW);
            i.setDataAndType(uri, ct);
            i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            contentIntent = i;
            continue; // skip the rest
        } else if (ct.startsWith("text/")) {
            body = fetchPart(is);
        }

        try {
            is.close();
        } catch (IOException e) {
        } // Ignore
    } while (cursor.moveToNext());
}

From source file:com.technoxist.fragment.EntryFragment.java

private void refreshUI(Cursor entryCursor) {
    if (entryCursor != null) {
        String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos)
                : entryCursor.getString(mFeedNamePos);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.setTitle(feedTitle);// w w w .j  av a  2s  . c o  m

        byte[] iconBytes = entryCursor.getBlob(mFeedIconPos);
        Bitmap bitmap = UiUtils.getScaledBitmap(iconBytes, 24);
        if (bitmap != null) {
            activity.getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
        } else {
            activity.getActionBar().setIcon(R.drawable.icon);
        }

        mFavorite = entryCursor.getInt(mIsFavoritePos) == 1;
        activity.invalidateOptionsMenu();

        // Listen the mobilizing task
        if (FetcherService.hasMobilizationTask(mEntriesIds[mCurrentPagerPos])) {
            hideSwipeProgress();

            // Start services here if not already started to avoid an infinite loading
            if (!PrefUtils.getBoolean(PrefUtils.IS_REFRESHING, false)) {
                MainApplication.getContext()
                        .startService(new Intent(MainApplication.getContext(), FetcherService.class)
                                .setAction(FetcherService.ACTION_MOBILIZE_FEEDS));
            }
        } else {
            hideSwipeProgress();
        }

        // Mark the article as read
        if (entryCursor.getInt(mIsReadPos) != 1) {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getReadContentValues(), null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }).start();
        }
    }
}

From source file:com.app.uafeed.fragment.EntryFragment.java

private void refreshUI(Cursor entryCursor) {
    if (entryCursor != null) {
        String feedTitle = entryCursor.isNull(mFeedNamePos) ? entryCursor.getString(mFeedUrlPos)
                : entryCursor.getString(mFeedNamePos);
        BaseActivity activity = (BaseActivity) getActivity();
        activity.setTitle(feedTitle);/*from   w  ww .  ja va  2  s.c om*/

        byte[] iconBytes = entryCursor.getBlob(mFeedIconPos);
        Bitmap bitmap = UiUtils.getScaledBitmap(iconBytes, 24);
        if (bitmap != null) {
            activity.getActionBar().setIcon(new BitmapDrawable(getResources(), bitmap));
        } else {
            activity.getActionBar().setIcon(R.drawable.icon);
        }

        mFavorite = entryCursor.getInt(mIsFavoritePos) == 1;
        activity.invalidateOptionsMenu();

        // Listen the mobilizing task
        boolean isRefreshing = FetcherService.hasTasks(mEntriesIds[mCurrentPagerPos]);
        activity.getProgressBar().setVisibility(isRefreshing ? View.VISIBLE : View.GONE);

        // Mark the article as read
        if (entryCursor.getInt(mIsReadPos) != 1) {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getReadContentValues(), null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }).start();
        }
    }
}

From source file:com.technoxist.fragment.EntryFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (mEntriesIds != null) {
        Activity activity = getActivity();

        switch (item.getItemId()) {
        case R.id.menu_star: {
            mFavorite = !mFavorite;/*w  w  w  .  j a  v  a  2s . c  o  m*/

            if (mFavorite) {
                item.setIcon(R.drawable.rating_important);
            } else {
                item.setTitle(R.string.menu_star).setIcon(R.drawable.rating_not_important);
            }

            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(EntryColumns.IS_FAVORITE, mFavorite ? 1 : 0);
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, values, null, null);

                    // Update the cursor
                    Cursor updatedCursor = cr.query(uri, null, null, null, null);
                    updatedCursor.moveToFirst();
                    mEntryPagerAdapter.setUpdatedCursor(mCurrentPagerPos, updatedCursor);
                }
            }.start();
            break;
        }
        case R.id.menu_share: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            if (link != null) {
                String title = cursor.getString(mTitlePos);
                startActivity(Intent.createChooser(
                        new Intent(Intent.ACTION_SEND).putExtra(Intent.EXTRA_SUBJECT, title)
                                .putExtra(Intent.EXTRA_TEXT, link).setType(Constants.MIMETYPE_TEXT_PLAIN),
                        getString(R.string.menu_share)));
            }
            break;
        }
        case R.id.menu_full_screen: {
            setImmersiveFullScreen(true);
            break;
        }
        case R.id.menu_copy_clipboard: {
            Cursor cursor = mEntryPagerAdapter.getCursor(mCurrentPagerPos);
            String link = cursor.getString(mLinkPos);
            ClipboardManager clipboard = (ClipboardManager) activity
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("Copied Text", link);
            clipboard.setPrimaryClip(clip);

            Toast.makeText(activity, R.string.copied_clipboard, Toast.LENGTH_SHORT).show();
            break;
        }
        case R.id.menu_mark_as_unread: {
            final Uri uri = ContentUris.withAppendedId(mBaseUri, mEntriesIds[mCurrentPagerPos]);
            new Thread() {
                @Override
                public void run() {
                    ContentResolver cr = MainApplication.getContext().getContentResolver();
                    cr.update(uri, FeedData.getUnreadContentValues(), null, null);
                }
            }.start();
            activity.finish();
            break;
        }
        }
    }

    return true;
}

From source file:com.jefftharris.passwdsafe.file.PasswdFileUri.java

/** Resolve fields for a generic provider URI */
private void resolveGenericProviderUri(Context context) {
    ContentResolver cr = context.getContentResolver();
    boolean writable = false;
    boolean deletable = false;
    itsTitle = "(unknown)";
    Cursor cursor = cr.query(itsUri, null, null, null, null);
    try {//from www  .  j a v a2  s .  c om
        if ((cursor != null) && cursor.moveToFirst()) {
            int colidx = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            if (colidx != -1) {
                itsTitle = cursor.getString(colidx);
            }

            int flags = 0;
            colidx = cursor.getColumnIndex(DocumentsContractCompat.COLUMN_FLAGS);
            if (colidx != -1) {
                flags = cursor.getInt(colidx);
            }

            PasswdSafeUtil.dbginfo(TAG, "file %s, %x", itsTitle, flags);
            writable = (flags & DocumentsContractCompat.FLAG_SUPPORTS_WRITE) != 0;
            deletable = (flags & DocumentsContractCompat.FLAG_SUPPORTS_DELETE) != 0;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    itsWritableInfo = new Pair<>(writable, null);
    itsIsDeletable = deletable;
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

private String queryForNotes() {
    StringBuilder tags = new StringBuilder();
    ContentResolver resolver = getContentResolver();
    Cursor mediaCursor = null;//from w w w. j ava  2  s . c o m
    Uri mediaUri = Uri.withAppendedPath(mTrackUri, "media");
    try {
        mediaCursor = resolver.query(mediaUri, new String[] { Media.URI }, null, null, null);
        if (mediaCursor.moveToFirst()) {
            do {
                Uri noteUri = Uri.parse(mediaCursor.getString(0));
                if (noteUri.getScheme().equals("content")
                        && noteUri.getAuthority().equals(GPStracking.AUTHORITY + ".string")) {
                    String tag = noteUri.getLastPathSegment().trim();
                    if (!tag.contains(" ")) {
                        if (tags.length() > 0) {
                            tags.append(" ");
                        }
                        tags.append(tag);
                    }
                }
            } while (mediaCursor.moveToNext());
        }
    } finally {
        if (mediaCursor != null) {
            mediaCursor.close();
        }
    }
    return tags.toString();
}