我正面临这个sqlite问题,我试图通过以下查询提取具有电话号码的联系人:
strerror(errno)
问题是,如果联系人的电话号码超过1个,结果将采用以下格式:
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"
);
由于数据重复而不合需要。
我想对数据库进行只有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
有可能吗?
谢谢。
答案 0 :(得分:0)
我认为你不想做什么,这是一个使用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());
}