Sqlite Android Extract Phone Number Contacts

I ran into this sqlite problem in which I am trying to retrieve contacts that have phone numbers with the following query:

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" ); 

The problem is that if the contact has more than one phone number, the result will be in this form:

 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 

which is undesirable due to data duplication.

I want to make only 1 query in db, which I hope can be written to return the result as follows:

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

Is it possible?

Thanks.

+5
source share
1 answer

I don’t think it’s possible what you want to do. This is a workaround using HashMap. It can handle thousands of records, so don't worry.

  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()); } 
0
source

All Articles