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.google.samples.apps.sergio.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;//from  www .jav a 2 s .c o  m
    }

    if (!PrefUtils.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 = 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_NEW_TASK | 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 && PrefUtils.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());
}

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

/**
 * Move all the cards from their old decks to the first deck that was added in setup()
 *//* w  ww .j ava  2s  . c  om*/
public void testMoveCardsToOtherDeck() {
    final ContentResolver cr = getContext().getContentResolver();
    // Query all available notes
    final Cursor allNotesCursor = cr.query(FlashCardsContract.Note.CONTENT_URI, null, "tag:" + TEST_TAG, null,
            null);
    assertNotNull(allNotesCursor);
    try {
        assertEquals("Check number of results", mCreatedNotes.size(), allNotesCursor.getCount());
        while (allNotesCursor.moveToNext()) {
            // Now iterate over all cursors
            Uri cardsUri = Uri.withAppendedPath(
                    Uri.withAppendedPath(FlashCardsContract.Note.CONTENT_URI,
                            allNotesCursor
                                    .getString(allNotesCursor.getColumnIndex(FlashCardsContract.Note._ID))),
                    "cards");
            final Cursor cardsCursor = cr.query(cardsUri, null, null, null, null);
            assertNotNull("Check that there is a valid cursor after query for cards", cardsCursor);
            try {
                assertTrue("Check that there is at least one result for cards", cardsCursor.getCount() > 0);
                while (cardsCursor.moveToNext()) {
                    long targetDid = mTestDeckIds[0];
                    // Move to test deck
                    ContentValues values = new ContentValues();
                    values.put(FlashCardsContract.Card.DECK_ID, targetDid);
                    Uri cardUri = Uri.withAppendedPath(cardsUri, cardsCursor
                            .getString(cardsCursor.getColumnIndex(FlashCardsContract.Card.CARD_ORD)));
                    cr.update(cardUri, values, null, null);
                    Cursor movedCardCur = cr.query(cardUri, null, null, null, null);
                    assertNotNull("Check that there is a valid cursor after moving card", movedCardCur);
                    assertTrue("Move to beginning of cursor after moving card", movedCardCur.moveToFirst());
                    long did = movedCardCur
                            .getLong(movedCardCur.getColumnIndex(FlashCardsContract.Card.DECK_ID));
                    assertEquals("Make sure that card is in new deck", targetDid, did);
                }
            } finally {
                cardsCursor.close();
            }
        }
    } finally {
        allNotesCursor.close();
    }
}

From source file:com.vyasware.vaani.MainActivity.java

private void doMsg(String noun) {
    System.out.println("msg");

    Cursor cur = null;//from   w  w  w  . j a  v a2 s. c om
    ContentResolver cr = null;

    try {
        cr = getContentResolver();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        boolean called = false;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                // Log.i("Names", name);
                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // Query phone here. Covered next
                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                    while (phones.moveToNext()) {
                        String phoneNumberX = phones.getString(
                                phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // Log.i("Number", phoneNumber);
                        boolean a = (name.equalsIgnoreCase(noun));
                        System.out.println(name + "  " + a + "  " + phoneNumberX);

                        if (a)
                            System.out.println(phoneNumberX);

                        if (a) {
                            String b = "sms:";
                            String smsUri = b + phoneNumberX;
                            Intent smsIntent = new Intent(Intent.ACTION_VIEW);
                            smsIntent.setData(Uri.parse(smsUri));
                            called = true;
                            startActivity(smsIntent);
                            tts.speak(noun + "  ? !",
                                    TextToSpeech.QUEUE_FLUSH, null);

                        }

                    }
                    phones.close();

                }

            }

            if (!called)
                tts.speak(noun + "  ?    !",
                        TextToSpeech.QUEUE_FLUSH, null);

        }

    } catch (Exception ex) {
        ex.printStackTrace();

    }
}

From source file:com.vyasware.vaani.MainActivity.java

private void doCall(String noun) {
    System.out.println("call");
    System.out.println(noun);/*w  w w .  ja  va  2  s.  c o m*/

    Cursor cur = null;
    ContentResolver cr = null;

    try {
        cr = getContentResolver();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        boolean called = false;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                // Log.i("Names", name);
                if (Integer.parseInt(
                        cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                    // Query phone here. Covered next
                    Cursor phones = getContentResolver().query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
                    while (phones.moveToNext()) {
                        String phoneNumberX = phones.getString(
                                phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        // Log.i("Number", phoneNumber);
                        boolean a = (name.equalsIgnoreCase(noun));
                        System.out.println(name + "  " + a + "  " + phoneNumberX);

                        if (a)
                            System.out.println(phoneNumberX);

                        if (a) {
                            String b = "tel:";
                            String phoneCallUri = b + phoneNumberX;
                            Intent phoneCallIntent = new Intent(Intent.ACTION_CALL);
                            phoneCallIntent.setData(Uri.parse(phoneCallUri));
                            called = true;
                            startActivity(phoneCallIntent);

                        }

                    }
                    phones.close();

                }

            }

            if (!called)
                tts.speak(noun + "  ?    !",
                        TextToSpeech.QUEUE_FLUSH, null);

        }

    } catch (Exception ex) {
        ex.printStackTrace();

    }
    // tts.speak(noun + "  ?    !",TextToSpeech.QUEUE_FLUSH, null);
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * @param context The {@link Context} to use.
 * @param ids The id of the song(s) to add.
 * @param playlistid The id of the playlist being added to.
 *//*ww  w  .j a v  a 2  s .c o  m*/
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    if (ids == null) {
        LOG.warn("song ids given null, not adding anything to playlist.");
        return;
    }

    if (ids == sEmptyList) {
        LOG.warn("song ids was empty, not adding anything to playlist.");
        return;
    }

    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[] { "count(*)" };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    try {
        cursor = resolver.query(uri, projection, null, null, null);
    } catch (Throwable ignored) {
    }

    if (cursor != null) {
        cursor.moveToFirst();
        final int base = cursor.getInt(0);
        cursor.close();
        int numinserted = 0;
        for (int offSet = 0; offSet < size; offSet += 1000) {
            makeInsertItems(ids, offSet, 1000, base);
            numinserted += resolver.bulkInsert(uri, mContentValuesCache);
        }
        final String message = context.getResources().getQuantityString(R.plurals.NNNtrackstoplaylist,
                numinserted, numinserted);
        AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show();
        refresh();
    } else {
        LOG.warn("Unable to complete addToPlaylist, review the logic");
    }
}

From source file:com.looseboxes.idisc.common.util.ContactEmailsExtractor.java

public JSONObject getNameEmailDetails(Context context) {

    JSONObject emailsMap = new JSONObject();

    Set<String> emailsSet = new HashSet<String>();

    ContentResolver contentResolver = context.getContentResolver();

    String[] PROJECTION = new String[] { ContactsContract.RawContacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.PHOTO_ID,
            ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Photo.CONTACT_ID };

    String order = "CASE WHEN " + ContactsContract.Contacts.DISPLAY_NAME + " NOT LIKE '%@%' THEN 1 ELSE 2 END, "
            + ContactsContract.Contacts.DISPLAY_NAME + ", " + ContactsContract.CommonDataKinds.Email.DATA
            + " COLLATE NOCASE";

    String filter = ContactsContract.CommonDataKinds.Email.DATA + " NOT LIKE ''";

    Cursor cur = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter,
            null, order);/*from  w ww .j ava  2s . c o m*/

    if (cur.moveToFirst()) {

        do {

            // names comes in hand sometimes
            String name = cur.getString(1);
            String email = cur.getString(3);

            // keep unique only
            if (emailsSet.add(email.toLowerCase())) {
                emailsMap.put(email, name);
            }
        } while (cur.moveToNext());
    }

    cur.close();

    return emailsMap;
}

From source file:com.saarang.samples.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;
    LogUtils.LOGD(TAG, "Considering notifying for time interval.");
    LogUtils.LOGD(TAG, "    Interval start: " + sessionStart + "=" + (new Date(sessionStart)).toString());
    LogUtils.LOGD(TAG, "    Interval end: " + intervalEnd + "=" + (new Date(intervalEnd)).toString());
    LogUtils.LOGD(TAG, "    Current time is: " + currentTime + "=" + (new Date(currentTime)).toString());
    if (sessionStart < currentTime) {
        LogUtils.LOGD(TAG, "Skipping session notification (too late -- time interval already started)");
        return;//w ww  .  j a  v a  2  s .c om
    }

    if (!PrefUtils.shouldShowSessionReminders(this)) {
        // skip if disabled in settings
        LogUtils.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))) {
        LogUtils.LOGD(TAG, "Skipping session notification (already notified)");
        return;
    }

    final ContentResolver cr = getContentResolver();

    LogUtils.LOGD(TAG, "Looking for sessions in interval " + sessionStart + " - " + intervalEnd);
    Cursor 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();
    LogUtils.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));
        LogUtils.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_NEW_TASK | 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(com.saarang.samples.apps.iosched.R.string.session_notification_text_1,
                minutesLeft);
    } else {
        contentText = res.getQuantityString(
                com.saarang.samples.apps.iosched.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(com.saarang.samples.apps.iosched.R.color.theme_primary))
            .setTicker(res
                    .getQuantityString(com.saarang.samples.apps.iosched.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(com.saarang.samples.apps.iosched.R.drawable.ic_stat_notification).setContentIntent(pi)
            .setPriority(Notification.PRIORITY_MAX).setAutoCancel(true);
    if (minutesLeft > 5) {
        notifBuilder.addAction(com.saarang.samples.apps.iosched.R.drawable.ic_alarm_holo_dark,
                String.format(res.getString(com.saarang.samples.apps.iosched.R.string.snooze_x_min), 5),
                createSnoozeIntent(sessionStart, intervalEnd, 5));
    }
    if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) {
        notifBuilder.addAction(com.saarang.samples.apps.iosched.R.drawable.ic_map_holo_dark,
                res.getString(com.saarang.samples.apps.iosched.R.string.title_map),
                createRoomMapIntent(singleSessionRoomId));
    }
    String bigContentTitle;
    if (starredCount == 1 && starredSessionTitles.size() > 0) {
        bigContentTitle = starredSessionTitles.get(0);
    } else {
        bigContentTitle = res.getQuantityString(
                com.saarang.samples.apps.iosched.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);
    LogUtils.LOGD(TAG, "Now showing notification.");
    nm.notify(NOTIFICATION_ID, richNotification.build());
}

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

private String queryForTrackName() {
    ContentResolver resolver = getContentResolver();
    Cursor trackCursor = null;/*from  w  w  w .j a v  a2  s  . c om*/
    String name = null;

    try {
        trackCursor = resolver.query(mTrackUri, new String[] { Tracks.NAME }, null, null, null);
        if (trackCursor.moveToFirst()) {
            name = trackCursor.getString(0);
        }
    } finally {
        if (trackCursor != null) {
            trackCursor.close();
        }
    }
    return name;
}

From source file:com.example.gaurav.sunshine.app.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*  ww w .jav  a2s . com*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    long rowId;
    final ContentResolver resolver = mContext.getContentResolver();
    Uri uri = Uri.parse(WeatherContract.BASE_CONTENT_URI + "/" + WeatherContract.PATH_LOCATION);
    String selectionArgs[] = { WeatherContract.LocationEntry.COLUMN_CITY_NAME };
    String selection = WeatherContract.LocationEntry.COLUMN_CITY_NAME + " =? ";

    //First, query database to check if this location already exists.
    Cursor cursor = resolver.query(uri, null, selection, new String[] { cityName }, null);

    if (cursor.moveToNext())
        return Long.parseLong(cursor.getString(cursor.getColumnIndex(WeatherContract.LocationEntry._ID)));
    else {
        ContentValues values = new ContentValues();
        values.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        values.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        values.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        //resolver.insert(uri, values);
        return Long.parseLong(resolver.insert(uri, values).getLastPathSegment());
    }
    // return -1;
}

From source file:com.cttapp.bby.mytlc.layer8apps.MyTlc.java

/************
 *  PURPOSE: Retrieves a list of all calendars on the device and
 *      returns the name of each calendar
 *  ARGUMENTS: null/*from w ww.ja  va 2 s.  c o m*/
 *  RETURNS: String[][]
 *  AUTHOR: Devin Collins <agent14709@gmail.com>
 *************/
private String[][] selectCalendar() {
    try {
        Cursor managedCursor = null;
        int nameColumn = 0;
        int idColumn = 0;
        String[] projection;

        /*****************
         * Figure out which version of Android we're on to know how
         * we should be calling the calendar
         *****************/
        ContentResolver cr = getContentResolver();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
            try {
                managedCursor = cr.query(Uri.parse("content://calendar/calendars/"),
                        new String[] { "_id", "displayName" }, "selected=1", null, null);
                nameColumn = 1;
            } catch (Exception e) {
                return null;
            }
        } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            try {
                managedCursor = cr.query(Uri.parse("content://com.android.calendar/calendars/"),
                        new String[] { "_id", "displayName" }, "selected=1", null, null);
                nameColumn = 1;
            } catch (Exception e) {
                return null;
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            Uri uri = CalendarContract.Calendars.CONTENT_URI;
            projection = new String[] { CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                    CalendarContract.Calendars._ID };
            try {
                // Make sure the calendar loaded properly
                managedCursor = cr.query(uri, projection, null, null, null);
                nameColumn = managedCursor.getColumnIndex(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME);
                idColumn = managedCursor.getColumnIndex(CalendarContract.Calendars._ID);
            } catch (Exception e) {
                return null;
            }
        }

        /************
         * Go to the first listing in our calendar
         *****************/
        if (managedCursor.moveToFirst()) {
            String calendars[][] = new String[managedCursor.getCount()][2];
            int count = 0;
            /************
             * The following 'do' statement checks for a valid calendar name.
             * If one doesn't exist, such as in the case of an Exchange
             * server, we give it a blank name.
             *****************/
            do {
                calendars[count][0] = managedCursor.getString(idColumn);
                if (managedCursor.getString(nameColumn) == null
                        || managedCursor.getString(nameColumn).equals("")) {
                    calendars[count][1] = "Unnamed calendar";
                } else {
                    calendars[count][1] = managedCursor.getString(nameColumn);
                }
                count++;
            } while (managedCursor.moveToNext());
            return calendars;
        }
    } catch (Exception e) {
        return null;
    }
    return null;
}