开发者

Getting random contact numbers in Android

I'm trying to use the following code to grab a random mobile phone number from the contacts:

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + "NAME" + "'", null, null);
    cursor.moveToFirst();
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
    Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
    List numbers = new ArrayList();

    while (phones.moveToNext()) {
        String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
        int type = phones.getInt(phones.getColu开发者_如何转开发mnIndex(Phone.TYPE));
        switch (type) {
            case Phone.TYPE_MOBILE:
                numbers.add(number);
                break;
        }
    }

    Random randGen = new Random();
    return (String) numbers.get(randGen.nextInt(numbers.size()));

However, running this code produces a crash on line 4, with a message saying "CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0". The crash seems to be caused by the cursor.getString() method. Does anyone know where I'm going wrong? This is using the ContactsContract in Android 2.1. Eclipse gives no errors.

Thanks!


The moveToFirst() method returns a boolean. It returns true if it was able to move to the first row and false otherwise, indicating that the query returned an empty set.

When using a cursor, you should follow something like:

if (cursor.moveToFirst()) {
    do {
        // do some stuff
    } while (cursor.moveToNext());
}
cursor.close();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜