我发现联系人列表的这个漂亮的布局:https://github.com/thehung111/ContactListView
然而,联系人是硬编码的。所以我需要提取手机联系人并填写联系人列表。
以下是我的尝试:
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()上遇到错误,并试图将类扩展到Application等。到目前为止没有运气。
所以主要问题是如何在Android上获取包含姓名和电话号码的列表作为字符串列表。
答案 0 :(得分:0)
您是否在清单中声明了以下权限?如果没有,请声明。
<uses-permission android:name="android.permission.READ_CONTACTS" />
答案 1 :(得分: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);