0

I'm working on an Android application that manages contacts (Add, Update, Delete)

This is the code that lists the contacts in listview

list_ct.clear();
Cursor cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor != null)
{
    while (cursor.moveToNext())
    {
        String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
        String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
        Cursor cursor2 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
        ArrayList<String> phones = new ArrayList<String>();
        while (cursor2.moveToNext())
        {
            String phoneNumber = cursor2.getString(cursor2.getColumnIndex(CommonDataKinds.Phone.NUMBER));
            phones.add(phoneNumber);
        }
        Contact ct = new Contact(id,name,phones);
        adapter.notifyDataSetChanged();
    }
}

This is the listview event listener

lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        Contact current = (Contact)list_ct.get(position);
        Intent in=new Intent(Intent.ACTION_EDIT,Uri.parse("content://contacts/people/"+current.getId()));
        startActivityForResult(in,2);
    }
});

When I click on a contact in the listview, for some of them the intent opens and closes immediatly, as if the id doesn't exist in the contact's database, and for others it opens the contact edit for another contact.

The contact display name and its phone numbers are correctly shown, but the id is wrong. What I don't understand is why the id in the first cursor works for showing the contact's phone numbers, but not to update.

Amine Messaoudi
  • 2,141
  • 2
  • 20
  • 37

1 Answers1

0

You're using a very old and deprecated Android API called "People" for your Contact URI, never use People's API, always ContactsContract.

You should build your contact uri like this:

Uri contactUri = ContentUris.withAppendedId(Contacts.CONTENT_URI, contactId);

Other then that, your query is super-slow, you can replace those hundreds of queries with a single fast query to make your app faster and life easier, see an example code in this answer: https://stackoverflow.com/a/47788324/819355

marmor
  • 27,641
  • 11
  • 107
  • 150