5 sqlite android android-contacts android-sqlite
我正面临这个sqlite问题,我试图通过以下查询提取具有电话号码的联系人:
Cursor cursor = context.getContentResolver().
query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{
ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI
},
ContactsContract.Contacts.HAS_PHONE_NUMBER + ">?",
new String [] {"0"},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
);
Run Code Online (Sandbox Code Playgroud)
问题是,如果联系人有超过1个电话号码,结果将采用以下形式:
id: 451, name: Maria, photoUri: null, has_phone_number: 1, phone_number: 0700 000 000
id: 451, name: Maria, photoUri: null, has_phone_number: 1, phone_number: 0800 000 000
id: 451, name: Maria, photoUri: null, has_phone_number: 1, phone_number: 0900 000 000
Run Code Online (Sandbox Code Playgroud)
由于重复数据,这是不合需要的.
我想只对数据库进行一次查询,希望可以写入以返回结果,如下所示:
id: 451, name: Maria, photoUri: null, has_phone_number: 1, phone_number: 0700 000 000, 0800 000 000, 0900 000 000
Run Code Online (Sandbox Code Playgroud)
可能吗?
谢谢.
我不认为你想要做的事情是可能的,这是使用 HashMap 的解决方法。它可以处理数千个条目,所以不用担心。
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI },
ContactsContract.Contacts.HAS_PHONE_NUMBER + ">?",
new String [] {"0"},
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
Map<String, List<String>> phonesPerContact = new HashMap<>();
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(2);
String phone = cursor.getString(1);
if (!phonesPerContact.containsKey(name)){
phonesPerContact.put(name, new ArrayList<String>());
}
phonesPerContact.get(name).add(phone);
} while (cursor.moveToNext());
}
for (String name: phonesPerContact.keySet()){
//Do whatever you want with the contact and its list of phones
List<String> phones = phonesPerContact.get(name);
Log.i("test", "Name: " + name + ", Numbers: " + phones.toString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
898 次 |
| 最近记录: |