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:can.yrt.onebusaway.ArrivalsListFragment.java

private void setUserInfo() {
    ContentResolver cr = getActivity().getContentResolver();
    Cursor c = cr.query(mStopUri, USER_PROJECTION, null, null, null);
    if (c != null) {
        try {/*from  ww w  .jav  a 2s.  c  om*/
            if (c.moveToNext()) {
                mFavorite = (c.getInt(0) == 1);
                mStopUserName = c.getString(1);
            }
        } finally {
            c.close();
        }
    }
}

From source file:com.tweetlanes.android.view.HomeActivity.java

void onCreateHandleIntents() {

    boolean turnSoftKeyboardOff = true;

    Intent intent = getIntent();/*from w  ww.  j a v a 2  s. com*/
    if (intent.getAction() == Intent.ACTION_SEND) {

        Bundle extras = intent.getExtras();
        String type = intent.getType();
        if (type.equals("text/plain") == true) {

            String shareString = extras.getString(Intent.EXTRA_TEXT);
            if (extras.containsKey(Intent.EXTRA_TEXT)) {
                shareString = extras.getString(Intent.EXTRA_SUBJECT) + " " + shareString;
            }
            beginShareStatus(shareString);

            turnSoftKeyboardOff = false;
        } else if (type.contains("image/")) {
            // From http://stackoverflow.com/a/2641363/328679
            if (extras.containsKey(Intent.EXTRA_STREAM)) {
                Uri uri = (Uri) extras.getParcelable(Intent.EXTRA_STREAM);
                String scheme = uri.getScheme();
                if (scheme.equals("content")) {
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = contentResolver.query(uri, null, null, null, null);
                    cursor.moveToFirst();
                    try {
                        String imagePath = cursor.getString(cursor.getColumnIndexOrThrow(Images.Media.DATA));
                        beginShareImage(imagePath);
                    } catch (java.lang.IllegalArgumentException e) {
                        Toast.makeText(this, R.string.picture_attach_error, Toast.LENGTH_SHORT).show();
                    }

                    turnSoftKeyboardOff = false;
                }
            }
        }
    }

    if (turnSoftKeyboardOff == true) {
        // Turn the soft-keyboard off. For some reason it wants to appear on screen by default when coming back from multitasking...
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }
}

From source file:com.intel.xdk.contacts.Contacts.java

public String JSONValueForPerson(String idlk) {
    ContentResolver cr = activity.getContentResolver();
    //PROCESS NAME ELEMENTS FOR CURRENT CONTACT ID
    String firstName = "", lastName = "", compositeName = "", id = "";
    String nameWhere = ContactsContract.Data.LOOKUP_KEY + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    String[] params = new String[] { idlk, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
    Cursor nameCur = cr.query(ContactsContract.Data.CONTENT_URI, null, nameWhere, params, null);
    if (nameCur.getCount() > 0) {
        nameCur.moveToFirst();//from w w  w . j a  v  a 2s .c o  m
        id = nameCur.getString(nameCur.getColumnIndex(ContactsContract.Data.CONTACT_ID));

        firstName = nameCur
                .getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
        lastName = nameCur
                .getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
        compositeName = nameCur.getString(
                nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));

        firstName = (firstName == null) ? "" : escapeStuff(firstName);
        lastName = (lastName == null) ? "" : escapeStuff(lastName);
        compositeName = (compositeName == null) ? "" : escapeStuff(compositeName);
    }

    //PROCESS EMAIL ADDRESES FOR CURRENT CONTACT ID
    Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[] { id }, null);
    String emailAddresses = "[]";
    if (emailCur.getCount() > 0) {
        emailAddresses = "[";
        while (emailCur.moveToNext()) {
            String email = emailCur
                    .getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            email = escapeStuff(email);
            //String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE)); 

            emailAddresses += "'" + email + "', ";

        }
        emailAddresses += "]";
    }
    emailCur.close();

    //PROCESS PHONE NUMBERS FOR CURRENT CONTACT ID
    Cursor phoneCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);

    String phoneNumbers = "[]";
    if (phoneCur.getCount() > 0) {
        phoneNumbers = "[";
        while (phoneCur.moveToNext()) {
            String phoneNum = phoneCur
                    .getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
            phoneNum = escapeStuff(phoneNum);
            phoneNumbers += "'" + phoneNum + "', ";
        }
        phoneNumbers += "]";
    }
    phoneCur.close();

    //PROCESS STREET ADDRESSES FOR CURRENT CONTACT ID
    String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
    String[] addrWhereParams = new String[] { id,
            ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
    Cursor addressCur = cr.query(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI, null, addrWhere,
            addrWhereParams, null);

    String streetAddresses = "[]";
    if (addressCur.getCount() > 0) {
        streetAddresses = "[";
        while (addressCur.moveToNext()) {

            String street = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
            String city = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
            String state = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
            String zip = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
            String country = addressCur.getString(
                    addressCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));

            street = escapeStuff(street);
            city = escapeStuff(city);
            state = escapeStuff(state);
            zip = escapeStuff(zip);
            country = escapeStuff(country);

            String addressstr = String.format(
                    "{ street:'%s', city:'%s', state:'%s', zip:'%s', country:'%s' }, ", street, city, state,
                    zip, country);
            streetAddresses += addressstr;

        }
        streetAddresses += "]";
    }
    addressCur.close();

    String jsPerson = String.format(
            "{ id:'%s', name:'%s', first:'%s', last:'%s', phones:%s, emails:%s, addresses:%s }, ", idlk,
            compositeName, firstName, lastName, phoneNumbers, emailAddresses, streetAddresses);
    return jsPerson.replaceAll("\\r\\n|\\r|\\n", "\\\\n");

}

From source file:babybear.akbquiz.ConfigActivity.java

/**
 * ??//  ww  w . j a va2  s.  c  o m
 * 
 * @return ?
 */
private ArrayList<Music> queryMusics() {
    ArrayList<Music> musiclistResult = new ArrayList<Music>();
    ContentResolver cr = this.getContentResolver();
    Cursor musics = cr.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            new String[] { MediaStore.Audio.Media._ID, // int
                    MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.ALBUM,
                    MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.DATA, // String
                    MediaStore.Audio.Media.DISPLAY_NAME, // String
                    MediaStore.Audio.Media.MIME_TYPE // String
            }, MediaStore.Audio.Media.IS_MUSIC + " = 1 AND " + MediaStore.Audio.Media.DURATION + " > 10000",
            null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
    Log.d("", "musics : " + musics.getCount());

    musics.moveToFirst();
    while (!musics.isAfterLast()) {
        Music temp = new Music();
        temp._ID = musics.getInt(musics.getColumnIndex(MediaStore.Audio.Media._ID));
        temp.ALBUM = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.ALBUM));
        temp.ARTIST = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.ARTIST));
        temp.DATA = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.DATA));
        temp.DURATION = musics.getLong(musics.getColumnIndex(MediaStore.Audio.Media.DURATION));
        temp.TITLE = musics.getString(musics.getColumnIndex(MediaStore.Audio.Media.TITLE));
        temp.isExist = true;

        musiclistResult.add(temp);
        musics.moveToNext();
    }
    musics.close();
    return musiclistResult;
}

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

/**
 * Remove old classified subjects if we have too many.
 *
 * @return Return true if we know for sure that no further removal is currently necessary.
 *///from  w w  w.  j  a  v  a  2s  .  com
private boolean removeOldSubjects() {
    final int count = getUploadedCount();
    final int max = getKeepCount();
    if (count > max) {
        Log.info("removeOldSubjects(): start");
        //Get the oldest done (and uploaded) items:
        final ContentResolver resolver = getContentResolver();

        final String[] projection = { Item.Columns._ID };
        //ISO-8601 dates can be alphabetically sorted to get date-time order:
        final String orderBy = Item.Columns.DATETIME_DONE + " ASC";
        final int countToRemove = count - max;
        //TODO: Use this: final String limit = Integer.toString(countToRemove); //TODO: Is this locale-independent?
        final Cursor c = resolver.query(Item.ITEMS_URI, projection, WHERE_CLAUSE_UPLOADED, new String[] {},
                orderBy);

        //Remove them one by one:
        int removed = 0;
        while (c.moveToNext()) {
            final String itemId = c.getString(0);
            if (!TextUtils.isEmpty(itemId)) {
                removeItem(itemId);

                //Only remove enough:
                removed++;
                if (removed == countToRemove) {
                    break;
                }
            }
        }

        c.close();

        Log.info("removeOldSubjects(): end");

        return false;
    } else {
        return true; //Tell the caller that no action was necessary.
    }
}

From source file:com.android.calendar.alerts.AlertService.java

/**
 * Searches the CalendarAlerts table for alarms that should have fired but
 * have not and then reschedules them. This method can be called at boot
 * time to restore alarms that may have been lost due to a phone reboot.
 *
 * @param cr the ContentResolver//from  w ww.jav a  2s .  c o  m
 * @param context the Context
 * @param manager the AlarmManager
 */
private static final void rescheduleMissedAlarms(ContentResolver cr, Context context,
        AlarmManagerInterface manager) {
    // Get all the alerts that have been scheduled but have not fired
    // and should have fired by now and are not too old.
    long now = System.currentTimeMillis();
    long ancient = now - DateUtils.DAY_IN_MILLIS;
    String[] projection = new String[] { CalendarContract.CalendarAlerts.ALARM_TIME, };

    if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context,
            Manifest.permission.READ_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
        //If permission is not granted then just return.
        Log.d(TAG, "Manifest.permission.READ_CALENDAR is not granted");
        return;
    }

    // TODO: construct an explicit SQL query so that we can add
    // "GROUPBY" instead of doing a sort and de-dup
    Cursor cursor = cr.query(CalendarAlerts.CONTENT_URI, projection, WHERE_RESCHEDULE_MISSED_ALARMS,
            (new String[] { Long.toString(now), Long.toString(ancient), Long.toString(now) }),
            SORT_ORDER_ALARMTIME_ASC);
    if (cursor == null) {
        return;
    }

    if (DEBUG) {
        Log.d(TAG, "missed alarms found: " + cursor.getCount());
    }

    try {
        long alarmTime = -1;

        while (cursor.moveToNext()) {
            long newAlarmTime = cursor.getLong(0);
            if (alarmTime != newAlarmTime) {
                if (DEBUG) {
                    Log.w(TAG, "rescheduling missed alarm. alarmTime: " + newAlarmTime);
                }
                AlertUtils.scheduleAlarm(context, manager, newAlarmTime);
                alarmTime = newAlarmTime;
            }
        }
    } finally {
        cursor.close();
    }
}

From source file:com.securecomcode.text.contacts.ContactAccessor.java

public Collection<ContactData> getContactsWithPush(Context context) {
    final ContentResolver resolver = context.getContentResolver();
    final String[] inProjection = new String[] { PhoneLookup._ID, PhoneLookup.DISPLAY_NAME };

    List<String> pushNumbers = Directory.getInstance(context).getActiveNumbers();
    final Collection<ContactData> lookupData = new ArrayList<ContactData>(pushNumbers.size());

    for (String pushNumber : pushNumbers) {
        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(pushNumber));
        Cursor lookupCursor = resolver.query(uri, inProjection, null, null, null);
        try {/*from w  w  w  . j a va2  s .  c  o m*/
            if (lookupCursor != null && lookupCursor.moveToFirst()) {
                final ContactData contactData = new ContactData(lookupCursor.getLong(0),
                        lookupCursor.getString(1));
                contactData.numbers.add(new NumberData("TextSecure", pushNumber));
                lookupData.add(contactData);
            }
        } finally {
            if (lookupCursor != null)
                lookupCursor.close();
        }
    }
    return lookupData;
}

From source file:com.ichi2.anki.tests.ContentProviderTest.java

/**
 * Check that a valid Cursor is returned when querying notes table with non-default projections
 *//*from w w w  .ja  va  2s  .c o m*/
public void testQueryNotesProjection() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available notes
    for (int i = 0; i < FlashCardsContract.Note.DEFAULT_PROJECTION.length; i++) {
        String[] projection = removeFromProjection(FlashCardsContract.Note.DEFAULT_PROJECTION, i);
        final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, projection,
                "tag:" + TEST_TAG, null, null);
        assertNotNull("Check that there is a valid cursor", allNotesCursor);
        try {
            assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount());
            // Check columns
            assertEquals("Check column count", projection.length, allNotesCursor.getColumnCount());
            for (int j = 0; j < projection.length; j++) {
                assertEquals("Check column name " + j, projection[j], allNotesCursor.getColumnName(j));
            }
        } finally {
            allNotesCursor.close();
        }
    }
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactField JSONArray/*from  w w w.j  a  v  a 2  s.co  m*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactFields
 */
private JSONArray imQuery(ContentResolver cr, String contactId) {
    String imWhere = ContactMethods.PERSON_ID + " = ? AND " + ContactMethods.KIND + " = ?";
    String[] imWhereParams = new String[] { contactId, ContactMethods.CONTENT_IM_ITEM_TYPE };
    Cursor cursor = cr.query(ContactMethods.CONTENT_URI, null, imWhere, imWhereParams, null);
    JSONArray ims = new JSONArray();
    JSONObject im;
    while (cursor.moveToNext()) {
        im = new JSONObject();
        try {
            im.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            im.put("perf", false);
            im.put("value", cursor.getString(cursor.getColumnIndex(ContactMethodsColumns.DATA)));
            im.put("type", getContactType(cursor.getInt(cursor.getColumnIndex(ContactMethodsColumns.TYPE))));
            ims.put(im);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    cursor.close();
    return null;
}

From source file:com.phonegap.ContactAccessorSdk3_4.java

/**
 * Create a ContactAddress JSONArray/*from  www .  j av a  2 s . co  m*/
 * @param cr database access object
 * @param contactId the ID to search the database for
 * @return a JSONArray representing a set of ContactAddress
 */
private JSONArray addressQuery(ContentResolver cr, String contactId) {
    String addrWhere = ContactMethods.PERSON_ID + " = ? AND " + ContactMethods.KIND + " = ?";
    String[] addrWhereParams = new String[] { contactId, ContactMethods.CONTENT_POSTAL_ITEM_TYPE };
    Cursor cursor = cr.query(ContactMethods.CONTENT_URI, null, addrWhere, addrWhereParams, null);
    JSONArray addresses = new JSONArray();
    JSONObject address;
    while (cursor.moveToNext()) {
        address = new JSONObject();
        try {
            address.put("id", cursor.getString(cursor.getColumnIndex(ContactMethods._ID)));
            address.put("formatted", cursor.getString(cursor.getColumnIndex(ContactMethodsColumns.DATA)));
            addresses.put(address);
        } catch (JSONException e) {
            Log.e(LOG_TAG, e.getMessage(), e);
        }
    }
    return addresses;
}