gpt4 book ai didi

android - sqlite android提取带有电话号码的联系人

转载 作者:IT王子 更新时间:2023-10-29 06:30:03 25 4
gpt4 key购买 nike

我正面临这个 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"
);

问题是如果联系人有超过 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

由于数据重复,这是不可取的。

我想对数据库进行仅 1 个查询,希望可以将其写入以返回如下结果:

id: 451, name: Maria, photoUri: null, has_phone_number: 1, phone_number: 0700 000 000, 0800 000 000, 0900 000 000

这可能吗?

谢谢。

最佳答案

我不认为你想做什么是可能的,这是使用 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());
}

关于android - sqlite android提取带有电话号码的联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30536930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com