5

所有聯繫人姓名和電話號碼作爲字符串列表,我發現了一個聯繫人列表這個好看的佈局:https://github.com/thehung111/ContactListView獲取Android上

然而,接觸是硬編碼。所以我需要取電話聯繫人並填寫聯繫人列表。

這是我曾嘗試:

public class ExampleDataSource { 

public static List<ContactItemInterface> getSampleContactList(){ 
    List<ContactItemInterface> list = new ArrayList<ContactItemInterface>(); 


    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
    String[] projection = new String[] {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, 
         ContactsContract.CommonDataKinds.Phone.NUMBER}; 
    Cursor people = getContentResolver().query(uri, projection, null, null, null); 

    int indexName = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME); 
    int indexNumber = people.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

    people.moveToFirst(); 
    do { 
     String name = people.getString(indexName); 
     String number = people.getString(indexNumber); 
     list.add(new ExampleContactItem(name , number)); 

    } while (people.moveToNext()); 

    /* Example inputs for contact list 

    list.add(new ExampleContactItem("Lizbeth" , "Lizbeth Crockett")); 
    list.add(new ExampleContactItem("Lizbeth" , "Lizbeth Crockett")); 
    list.add(new ExampleContactItem("Zachery" , "Zachery Loranger")); 
    list.add(new ExampleContactItem("Vada" , "Vada Winegar")); 
    list.add(new ExampleContactItem("Essie" , "Essie Pass")); 

    */ 
    return list; 
} 

}

我對getContentResolver()有錯誤,並試圖類擴展到應用程序等等。沒有運氣這麼遠。

所以最主要的問題是如何獲取包含姓名和電話號碼的列表作爲Android上的字符串列表。

回答

0

您是否在清單中聲明瞭以下權限?如果不是,請申報。

<uses-permission android:name="android.permission.READ_CONTACTS" /> 
+0

謝謝,但在這裏,那不是問題。 – user2882572

0

它會顯示所有聯繫人的名字和他們的電話號碼在每一個新行:

String names=""; 

Cursor people = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, 
             null,null,null, 
              null); 

            while (people.moveToNext()) { 


             int i=people.getColumnIndex(PhoneLookup.DISPLAY_NAME); 
             int i2=people.getColumnIndex(PhoneLookup._ID); 
             String name=people.getString(i); 
             String id1=people.getString(i2); 
             names+=name+":"; 
             Uri uri2 = ContactsContract. 
               CommonDataKinds.Phone.CONTENT_URI; 
               String[] projectio = new String[] { 
               ContactsContract.CommonDataKinds. 
               Phone.NUMBER }; 
               String selectio= ContactsContract. 
               CommonDataKinds.Phone.CONTACT_ID + 
               "=?"; 
               String[] selectionArg = new String[] 
               {id1 }; 
               Cursor peopl=getContentResolver().query(uri2,null,selectio,selectionArg,null); 
               while(peopl.moveToNext()) 
               { 
                int i3=peopl.getColumnIndex(CommonDataKinds.Phone.NUMBER); 

                String phonenum=peopl.getString(i3); 
                names+=phonenum+"\n"; 


               } 

              } 
Log.d("names":names);