I am using below code to add custom Mimetype in Android Contacts . This code is throwing an error on the below line
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.lang.Long.longValue()' on a null object reference
public static final String MIMETYPE_FORMALITY = "vnd.android.cursor.item/ABCAPPLICATION";
public MainActivity saveFormality() {
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.DATA1, this.getFormality() ? "1" : "0");
int mod = getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data.CONTACT_ID + "=" + "2231" + " AND "
+ ContactsContract.Data.MIMETYPE + "= '"
+ MIMETYPE_FORMALITY + "'", null);
if (mod == 0) {
values.put(ContactsContract.Data.CONTACT_ID, Long.valueOf("2231"));
values.put(ContactsContract.Data.MIMETYPE, MIMETYPE_FORMALITY);
**getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);** // This line was throwing null pointer exception.
Log.v("mimeType", "Inserted");
}
return this;
}
I have copied this code from Stackoverflow post But it is not working. Can someone explain me the reason why it is throwing this error.
Don't have guarantee that this will solve your issue because you haven't posted your full stack trace, but in general, you can't insert rows into Data.CONTENT_URI
by CONTACT_ID
, the ContactsContract
DB works like this:
Contacts
- each entry represents one contact, and groups together one or more RawContacts
RawContacts
- each entry represents data about a contact that was synced in by some SyncAdapter
(e.g. Whatsapp, Google, Facebook, Viber), this groups multiple Data entriesData
- The actual data about a contact, emails, phones, etc. each line is a single piece of data that belongs to a single RawContact
So when adding a Data row, you must specify the exact RawContact._ID it'll go into, via Data.RAW_CONTACT_ID = ...
, no need to specify the CONTACT_ID
since the RawContact
already belongs to some Contact
This is the same way to do updates to existing data as well.
As a side note: