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.android.unit_tests.CheckinProviderTest.java

@MediumTest
public void testEventReport() {
    long start = System.currentTimeMillis();
    ContentResolver r = getContext().getContentResolver();
    Checkin.logEvent(r, Checkin.Events.Tag.TEST, "Test Value");

    Cursor c = r.query(Checkin.Events.CONTENT_URI, null, Checkin.Events.TAG + "=?",
            new String[] { Checkin.Events.Tag.TEST.toString() }, null);

    long id = -1;
    while (c.moveToNext()) {
        String tag = c.getString(c.getColumnIndex(Checkin.Events.TAG));
        String value = c.getString(c.getColumnIndex(Checkin.Events.VALUE));
        long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE));
        assertEquals(Checkin.Events.Tag.TEST.toString(), tag);
        if ("Test Value".equals(value) && date >= start) {
            assertTrue(id < 0);//from  w w  w .j  a  v a 2  s  . c o m
            id = c.getInt(c.getColumnIndex(Checkin.Events._ID));
        }
    }
    assertTrue(id > 0);

    int rows = r.delete(ContentUris.withAppendedId(Checkin.Events.CONTENT_URI, id), null, null);
    assertEquals(1, rows);
    c.requery();
    while (c.moveToNext()) {
        long date = c.getLong(c.getColumnIndex(Checkin.Events.DATE));
        assertTrue(date < start); // Have deleted the only newer TEST.
    }

    c.close();
}

From source file:com.andrew.apollo.menu.CreateNewPlaylist.java

private String makePlaylistName() {
    final String template = getString(R.string.new_playlist_name_template);
    int num = 1;/*from  ww w.  j a  v  a 2  s .c o  m*/
    final String[] projection = new String[] { MediaStore.Audio.Playlists.NAME };
    final ContentResolver resolver = getActivity().getContentResolver();
    final String selection = MediaStore.Audio.Playlists.NAME + " != ''";
    Cursor cursor = resolver.query(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, projection, selection, null,
            MediaStore.Audio.Playlists.NAME);
    if (cursor == null) {
        return null;
    }

    String suggestedName;
    suggestedName = String.format(template, num++);
    boolean done = false;
    while (!done) {
        done = true;
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            final String playlistName = cursor.getString(0);
            if (playlistName.compareToIgnoreCase(suggestedName) == 0) {
                suggestedName = String.format(template, num++);
                done = false;
            }
            cursor.moveToNext();
        }
    }
    cursor.close();
    return suggestedName;
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static Uri getContactUriTypeFromPhoneNumber(ContentResolver resolver, String phoneNo, int index) {
    Uri result = null;/*from   www.  j  a  va  2  s. c om*/
    if (phoneNo == "" || "null".equals(phoneNo)) {
        phoneNo = "111111111";
    }
    String[] projection = { ContactsContract.Contacts._ID, ContactsContract.PhoneLookup.DISPLAY_NAME,
            ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.PHOTO_URI,
            ContactsContract.PhoneLookup.LOOKUP_KEY };
    Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNo));
    Cursor cursor = resolver.query(lookupUri, projection, null, null, null);
    if (cursor == null)
        return null;
    if (cursor.moveToFirst()) {
        if (cursor.getString(index) != null)
            result = Uri.parse(cursor.getString(index));
    }
    if (cursor != null) {
        cursor.close();
        cursor = null;
    }
    return result;
}

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

/**
 * get the cover and count//www .j av  a 2 s. c  om
 *
 * @param buckId album id
 */
private void buildAlbumCover(ContentResolver cr, String buckId, AlbumEntity album) {
    String[] photoColumn = new String[] { Media._ID, Media.DATA };
    Cursor coverCursor = cr.query(Media.EXTERNAL_CONTENT_URI, photoColumn, SELECTION_ID,
            new String[] { buckId, "image/jpeg", "image/png", "image/jpg", "image/gif" },
            Media.DATE_MODIFIED + " desc");
    try {
        if (coverCursor != null && coverCursor.moveToFirst()) {
            String picPath = coverCursor.getString(coverCursor.getColumnIndex(Media.DATA));
            String id = coverCursor.getString(coverCursor.getColumnIndex(Media._ID));
            album.mCount = coverCursor.getCount();
            album.mImageList.add(new ImageMedia(id, picPath));
            if (album.mImageList.size() > 0) {
                mBucketMap.put(buckId, album);
            }
        }
    } finally {
        if (coverCursor != null) {
            coverCursor.close();
        }
    }
}

From source file:cd.education.data.collector.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this uri.
 *
 * @param mUri either an instance URI (if previously saved) or a form URI
 * @param instanceMetadata/*from w  w w.ja v a 2  s .  c  om*/
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(Uri mUri,
        FormController.InstanceMetadata instanceMetadata) {

    ContentResolver cr = Collect.getInstance().getContentResolver();

    // fetch the form information
    String formId;
    String formVersion;
    PublicKey pk;
    Base64Wrapper wrapper;

    Cursor formCursor = null;
    try {
        if (cr.getType(mUri) == InstanceColumns.CONTENT_ITEM_TYPE) {
            // chain back to the Form record...
            String[] selectionArgs = null;
            String selection = null;
            Cursor instanceCursor = null;
            try {
                instanceCursor = cr.query(mUri, null, null, null, null);
                if (instanceCursor.getCount() != 1) {
                    Log.e(t, "Not exactly one record for this instance!");
                    return null; // save unencrypted.
                }
                instanceCursor.moveToFirst();
                String jrFormId = instanceCursor
                        .getString(instanceCursor.getColumnIndex(InstanceColumns.JR_FORM_ID));
                int idxJrVersion = instanceCursor.getColumnIndex(InstanceColumns.JR_VERSION);
                if (!instanceCursor.isNull(idxJrVersion)) {
                    selectionArgs = new String[] { jrFormId, instanceCursor.getString(idxJrVersion) };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + "=?";
                } else {
                    selectionArgs = new String[] { jrFormId };
                    selection = FormsColumns.JR_FORM_ID + " =? AND " + FormsColumns.JR_VERSION + " IS NULL";
                }
            } finally {
                if (instanceCursor != null) {
                    instanceCursor.close();
                }
            }

            formCursor = cr.query(FormsColumns.CONTENT_URI, null, selection, selectionArgs, null);

            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form matches this jr_form_id");
                return null; // save unencrypted
            }
            formCursor.moveToFirst();
        } else if (cr.getType(mUri) == FormsColumns.CONTENT_ITEM_TYPE) {
            formCursor = cr.query(mUri, null, null, null, null);
            if (formCursor.getCount() != 1) {
                Log.e(t, "Not exactly one blank form!");
                return null; // save unencrypted.
            }
            formCursor.moveToFirst();
        }

        formId = formCursor.getString(formCursor.getColumnIndex(FormsColumns.JR_FORM_ID));
        if (formId == null || formId.length() == 0) {
            Log.e(t, "No FormId specified???");
            return null;
        }
        int idxVersion = formCursor.getColumnIndex(FormsColumns.JR_VERSION);
        int idxBase64RsaPublicKey = formCursor.getColumnIndex(FormsColumns.BASE64_RSA_PUBLIC_KEY);
        formVersion = formCursor.isNull(idxVersion) ? null : formCursor.getString(idxVersion);
        String base64RsaPublicKey = formCursor.isNull(idxBase64RsaPublicKey) ? null
                : formCursor.getString(idxBase64RsaPublicKey);

        if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
            return null; // this is legitimately not an encrypted form
        }

        int version = android.os.Build.VERSION.SDK_INT;
        if (version < 8) {
            Log.e(t, "Phone does not support encryption.");
            return null; // save unencrypted
        }

        // this constructor will throw an exception if we are not
        // running on version 8 or above (if Base64 is not found).
        try {
            wrapper = new Base64Wrapper();
        } catch (ClassNotFoundException e) {
            Log.e(t, "Phone does not have Base64 class but API level is " + version);
            e.printStackTrace();
            return null; // save unencrypted
        }

        // OK -- Base64 decode (requires API Version 8 or higher)
        byte[] publicKey = wrapper.decode(base64RsaPublicKey);
        X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf;
        try {
            kf = KeyFactory.getInstance(RSA_ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            Log.e(t, "Phone does not support RSA encryption.");
            e.printStackTrace();
            return null;
        }
        try {
            pk = kf.generatePublic(publicKeySpec);
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
            Log.e(t, "Invalid RSA public key.");
            return null;
        }
    } finally {
        if (formCursor != null) {
            formCursor.close();
        }
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceMetadata.instanceId == null) {
        Log.e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    // For now, prevent encryption if the BouncyCastle implementation is not present.
    // https://code.google.com/p/opendatakit/issues/detail?id=918
    try {
        Cipher.getInstance(EncryptionUtils.SYMMETRIC_ALGORITHM, ENCRYPTION_PROVIDER);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchProviderException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for implementation of symmetric algorithm!");
        return null;
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
        Log.e(t, "No BouncyCastle provider for padding implementation of symmetric algorithm!");
        return null;
    }

    return new EncryptedFormInformation(formId, formVersion, instanceMetadata, pk, wrapper);
}

From source file:com.grokkingandroid.sampleapp.samples.data.contentprovider.lentitems.LentItemDisplayFragment.java

/**
 * The dummyQuery method is only used to show a sample query. 
 * It's not used within this sample app.
 *//* w w  w  .  j  a  v a2 s  .  com*/
@SuppressWarnings("unused")
private void dummyQuery() {

    String itemId = "10";
    String selection = LentItemsContract.SELECTION_ID_BASED; // BaseColumns._ID
                                                             // + " = ? "
    String[] selectionArgs = { itemId };
    ContentResolver resolver = getActivity().getContentResolver();
    Cursor c = resolver.query(Items.CONTENT_URI, // die URI
            Items.PROJECTION_ALL, // optionale Angabe der gewnschten Spalten
            selection, // optionale WHERE Klausel (ohne Keyword)
            selectionArgs, // optionale Wildcard Ersetzungen
            Items.SORT_ORDER_DEFAULT); // optionale ORDER BY Klausel (ohne Keyword)

    if (c != null && c.moveToFirst()) {
        // int idx = c.getColumnIndex(Items.NAME);
        String name = c.getString(1);
        String borrower = c.getString(2);
    }

}

From source file:com.todoroo.astrid.gcal.GCalControlSet.java

@Override
protected void readFromTaskOnInitialize() {
    String uri = gcal.getTaskEventUri(model);
    if (!TextUtils.isEmpty(uri)) {
        try {// ww w  .  j a v  a  2  s.  c  om
            calendarUri = Uri.parse(uri);

            // try to load calendar
            ContentResolver cr = activity.getContentResolver();
            Cursor cursor = cr.query(calendarUri, new String[] { "dtstart" }, null, null, null); //$NON-NLS-1$
            try {
                boolean deleted = cursor.getCount() == 0;

                if (deleted) {
                    calendarUri = null;
                    return;
                }
            } finally {
                cursor.close();
            }

            hasEvent = true;
        } catch (Exception e) {
            log.error("unable-to-parse-calendar: " + model.getCalendarURI(), e);
        }
    } else {
        hasEvent = false;
        calendarUri = null;
    }
    refreshDisplayView();
}

From source file:gov.wa.wsdot.android.wsdot.service.BorderWaitSyncService.java

/** 
 * Check the travel border wait table for any starred entries. If we find some, save them
 * to a list so we can re-star those after we flush the database.
 *///from   ww w.  j  a  va 2s  . c o  m
private List<Integer> getStarred() {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;
    List<Integer> starred = new ArrayList<Integer>();

    try {
        cursor = resolver.query(BorderWait.CONTENT_URI, new String[] { BorderWait.BORDER_WAIT_ID },
                BorderWait.BORDER_WAIT_IS_STARRED + "=?", new String[] { "1" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            while (!cursor.isAfterLast()) {
                starred.add(cursor.getInt(0));
                cursor.moveToNext();
            }
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    return starred;
}

From source file:com.almalence.googsharing.Thumbnail.java

public static Media getLastImageThumbnail(ContentResolver resolver) {
    Media internalMedia = null;// w  w  w .  j ava  2s . c  om
    Media externalMedia = null;

    String name = getName();

    try {
        Uri baseUri = Images.Media.INTERNAL_CONTENT_URI;

        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { ImageColumns._ID, ImageColumns.ORIENTATION,
                ImageColumns.DATE_TAKEN };

        String selection = ImageColumns.DATA + " like '%" + name + "%' AND " + ImageColumns.MIME_TYPE
                + "='image/jpeg'";
        String order = ImageColumns.DATE_TAKEN + " DESC," + ImageColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                internalMedia = new Media(id, cursor.getInt(1), cursor.getLong(2),
                        ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    try {
        Uri baseUri = Images.Media.EXTERNAL_CONTENT_URI;
        Uri query = baseUri.buildUpon().appendQueryParameter("limit", "1").build();
        String[] projection = new String[] { ImageColumns._ID, ImageColumns.ORIENTATION,
                ImageColumns.DATE_TAKEN };

        String selection = ImageColumns.DATA + " like '%" + name + "%' AND " + ImageColumns.MIME_TYPE
                + "='image/jpeg'";
        String order = ImageColumns.DATE_TAKEN + " DESC," + ImageColumns._ID + " DESC";

        Cursor cursor = null;

        try {
            cursor = resolver.query(query, projection, selection, null, order);
            if (cursor != null && cursor.moveToFirst()) {
                final long id = cursor.getLong(0);
                externalMedia = new Media(id, cursor.getInt(1), cursor.getLong(2),
                        ContentUris.withAppendedId(baseUri, id));
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    } catch (Exception e) {

    }

    if (internalMedia == null) {
        return externalMedia;
    } else if (externalMedia == null) {
        return internalMedia;
    } else {
        return internalMedia.dateTaken > externalMedia.dateTaken ? internalMedia : externalMedia;
    }
}

From source file:com.bt.download.android.gui.UniversalScanner.java

private boolean documentExists(String filePath, long size) {
    boolean result = false;

    Cursor c = null;/*from w ww.  ja v a  2  s .  c  o  m*/

    try {
        ContentResolver cr = context.getContentResolver();
        c = cr.query(UniversalStore.Documents.Media.CONTENT_URI, new String[] { DocumentsColumns._ID },
                DocumentsColumns.DATA + "=?" + " AND " + DocumentsColumns.SIZE + "=?",
                new String[] { filePath, String.valueOf(size) }, null);
        result = c != null && c.getCount() != 0;
    } catch (Throwable e) {
        LOG.warn("Error detecting if file exists: " + filePath, e);
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return result;
}