2011-09-27 87 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(); 
相關問題