2013-09-21 87 views
0

我想檢索所選聯繫人,但不會返回任何內容,因爲它會生成運行時異常。獲取所選聯繫人的手機號碼

String[] Phoneprojection = {Phone.NUMBER,Phone.TYPE}; 
       String[] projection ={Contacts.DISPLAY_NAME}; 
       String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER + "=1"; 
       Cursor cursor = null; 
       Cursor phone = null; 
       try 
       { 
        cursor = managedQuery(intent.getData(), projection, selection, null, null); 
        while (cursor.moveToNext()) 
        {   
         String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
         // String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

         phone = managedQuery(Phone.CONTENT_URI,Phoneprojection,Data.CONTACT_ID + "=?", 
           new String[]{String.valueOf(contactId)}, 
           null); 
         if(phone.moveToFirst()) { 
          final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER); 
          final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE); 

          while(!phone.isAfterLast()) { 
           final String number = phone.getString(contactNumberColumnIndex); 
           //final int type = phone.getInt(contactTypeColumnIndex); 
           //final int typeLabelResource = Phone.getTypeLabelResource(type); 
          // if(typeLabelResource==2) 
           phonenumber.setText(number); 
           Log.e("TAG1",phonenumber.toString()); 
           phone.moveToNext(); 
          } 

         }      
        } 
       } 
       catch (Exception npe) 
       { 
        Log.e("TAG2", "Error trying to get Contacts."+npe.getMessage()); 
       } 

日誌,其產生是: Error trying to get Contacts.Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.

誰能解釋我如何解決這個問題。

回答

0

您立即訪問外部遊標,但您甚至不確定它實際上是否返回數據。

while (cursor.moveToNext()) {   
    String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
    // String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 

變化While循環,進入一個做,而一個和呼叫

if (!cursor.moveToFirst()) 
    return; 

這確保這就是您的查詢實際上得到的結果。

0

您的代碼是錯誤的。投影中不包含Contacts._ID。

String[] projection ={Contacts.DISPLAY_NAME}; // add Contacts._ID if you wanna query it 
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
相關問題