androidandroid-contactscontactscontract

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


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

Solution

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