Android adding contact to favorites programmatically - starred column does not exists

1k Views Asked by At

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);
    }
2

There are 2 best solutions below

1
marmor On BEST ANSWER

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);
};
0
Lucem On

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