0

I've been trying to add some contacts to favorites programmatically and this is done by update the STARRED value from 0 to 1 of that particular contact but whenever i execute the query it throws an SQLite exception letting my know that the STARRED column does not exist.

enter image description here

contactsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        contentValues = new ContentValues();
        contentValues.put(ContactsContract.CommonDataKinds.Phone.STARRED, 1);
        getActivity().getContentResolver()
        .update(ContactsContract.Data.CONTENT_URI, 
            contentValues, 
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+ " = 'Joe Luis'", null);
    }
marmor
  • 27,641
  • 11
  • 107
  • 150
Eri Otero
  • 3
  • 4

2 Answers2

1

The STARRED field is a part of the Contacts table, not the Data not Phone tables. You can access Phone.STARRED because all queries on the Data tables support implicit joins with some fields from the Contacts table, including STARRED.

This is the correct code:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    contentValues = new ContentValues();
    contentValues.put(Contacts.STARRED, 1);
    getActivity().getContentResolver().update(Contacts.CONTENT_URI, 
        contentValues, 
        Phone.DISPLAY_NAME+ " = 'Joe Luis'", null);
};

However please note that modifying contacts based on non-unique items like the display name is a really bad practice, as you might have more then one contact with the same name on the device, or you may empty DISPLAY_NAMEs that will really cause damage to many contacts.

Instead you should always use a unique field - Contacts._ID - to use as the selection of your updates, like so:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    long contactId = getContactIdFromPosition(position); // you need to implement this!

    contentValues = new ContentValues();
    contentValues.put(Contacts.STARRED, 1);
    getActivity().getContentResolver().update(Contacts.CONTENT_URI, 
        contentValues, Contacts._ID + "=" + contactId, null);
};
marmor
  • 27,641
  • 11
  • 107
  • 150
  • Thank you so much for your help, haha and good point on using a different field instead of a contact name, I was using it just for testing purpose:), I did what you recommended and it worked perfectly, thank you God bless you!! – Eri Otero Dec 27 '18 at 14:28
0

You are updating a different location of the contacts

ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME+" = 'Joe Luis'", null);

You should point to the Contacts data field. In this case ContactsContract.Contacts.Data not ContactsContract.CommonDataKinds

Please use this method Set Contact to favorite

Lucem
  • 2,912
  • 3
  • 20
  • 33