2013-04-28 69 views
0

我正在工作的一個android項目,我正在嘗試使用AutoCompleteEditText並綁定聯繫人的ArrayAdapter。但我有一個問題,返回一組聯繫人。獲取所有聯繫人添加到ArrayAdapter綁定到AutoCompleteEditText

下面是我用來檢索聯繫人和顯示名稱的代碼。

public ArrayList<String> getPhoneNumbersAndContactNames() 
    { 
     ArrayList<String> contacts = new ArrayList<String>(); 
     try 
     { 
      ContentResolver contentResolver = context.getContentResolver(); 

      Uri uri = Data.CONTENT_URI; 
      String[] projection = new String[] {PhoneLookup._ID, PhoneLookup.DISPLAY_NAME, PhoneLookup.NUMBER}; 
      String selection = "*"; 
      Cursor cursor = contentResolver.query(uri, projection, selection, null, null); 
      if (cursor.moveToFirst()) 
      { 
       contacts.add(cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup.DISPLAY_NAME))); 
      } 
     } 
     catch (SQLiteException ex) 
     { 
      Log.d("Database All Contacts Exception", ex.toString()); 
     } 
     catch (Exception ex) 
     { 
      Log.d("Get All Contacts Exception", ex.toString()); 
     } 
     return contacts; 
    } 

在上面的代碼我得到異常:

IllegalArgumentException: Invalid column number 

下面是我如何我試圖綁定數組列表來自動完成編輯文本。

txtPhoneNumberOrContact = (AutoCompleteTextView)findViewById(R.id.call_blacklist_txtPhoneNumberContactName); 

ArrayList<String> contacts = common.getPhoneNumbersAndContactNames(); 

ArrayAdapter<String> contactAdapter = 
     new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, 
       contacts); 

txtPhoneNumberOrContact.setAdapter(contactAdapter); 

我想不出試圖檢索聯繫人列表添加到ArrayList時,爲什麼我收到異常。

感謝您提供的任何幫助。

回答

0

使用其他selection"*"但:" = ?"

在我的項目我使用這個流程已經爲我工作:

Map<String, String> contactDataMap = new HashMap<String, String>(); 

    ContentResolver cr = context.getContentResolver(); 

    Uri contactData = data.getData();  
    Cursor cursor = cr.query(contactData, null, null, null, null); 
    cursor.moveToFirst(); 
    String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
    String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID)); 

    contactDataMap.put(NAME, (name != null)?name:""); 


    if (Integer.parseInt(cursor.getString(
      cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
     Cursor pCur = cr.query(
           ContactsContract.CommonDataKinds.Phone.CONTENT_URI, 
           null, 
           ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", 
           new String[]{id}, 
           null); 

     while (pCur.moveToNext()) { 
      String number = pCur.getString(pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER)); 

      contactDataMap.put(PHONE, (number != null)?number:""); 
      break; // ? we want only 1 value 
     } 
     pCur.close(); 
    } 

在這裏您填寫contactDataMap與名稱爲keyphone number