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沒有提供任何錯誤。
謝謝!