2011-09-27 56 views
0

我尝试使用下面的代码获取从接触一个随机的手机号码:获取Android中随机联系号码

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.getColumnIndex(Phone.TYPE)); 
     switch (type) { 
      case Phone.TYPE_MOBILE: 
       numbers.add(number); 
       break; 
     } 
    } 

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

然而,运行此代码产生第4行的一声,用消息说“CursorIndexOutOfBoundsException:索引0请求,大小为0”。崩溃似乎是由cursor.getString()方法引起的。有谁知道我要去哪里错了?这是使用Android 2.1中的ContactsContract。 Eclipse没有提供任何错误。

谢谢!

回答

0

moveToFirst()方法返回一个boolean。它返回true如果它能够移动到第一行和false否则,表明该查询返回一个空集。

在使用光标,你应该遵循这样的:

if (cursor.moveToFirst()) { 
    do { 
     // do some stuff 
    } while (cursor.moveToNext()); 
} 
cursor.close(); 
相关问题