如何在Android中检索联系人列表
作者:互联网
我检索联系人列表(姓名,电话号码)的目的记录在一个json对象中,以通过Web服务发送到服务器
然后我找到了访问联系人的代码,这很好,我测试了此代码
String id, name;
ContentResolver crs = getContentResolver();
Cursor people = crs.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
String phone = "";
people.moveToPosition(Contexts.getnbContacts());
while (people.moveToNext())
{
id = people.getString(people
.getColumnIndex(ContactsContract.Data._ID));
name = people.getString(people
.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
if (Integer
.parseInt(people.getString(people
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor phones = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + id, null, null);
while (phones.moveToNext()) {
// pdata =
// phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
phone = phone
+ phones.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA))
+ " and ";
;
}
phones.close();
}
我的问题是:如何将每个联系人(姓名,电话号码)保存在数组或arraylist中…
每个表行指定联系人
我认为数组类型与json格式兼容
那么如何将联系人复制到json对象中
解决方法:
这是我的代码
public static Map<String, String> getAddressBook(Context context)
{
Map<String, String> result = new HashMap<String, String>();
Cursor cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
while(cursor.moveToNext())
{
int phone_idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int name_idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
String phone = cursor.getString(phone_idx);
String name = cursor.getString(name_idx);
result.put(name, phone);
}
cursor.close();
return result;
}
和需要
<uses-permission android:name="android.permission.READ_CONTACTS"/>
标签:contacts,json,android 来源: https://codeday.me/bug/20191031/1972115.html