Following code runs mostly successfully but on some devices it crashes and produces the appended error. Any ideas why or what I could do to solve this?
Code
byte[] photo = ...;
long rawId = ...;
Uri currentImageUri = ...; // retrieved via ContactsContract.Profile.PHOTO_URI
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, photo);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (currentImageUri != null) {
// this crashes sometimes, very rarely though
context.getContentResolver().update(
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
values,
ContactsContract.Data.RAW_CONTACT_ID + " = " + rawId + " and " + ContactsContract.Data.IS_SUPER_PRIMARY + " = 1",
null);
} else {
// we need an insert here, this always works without problems
}
Exception
android.database.sqlite.SQLiteException: unknown error (code 0): Unable to convert BLOB to string
#################################################################
Error Code : 0 (SQLITE_OK)
Caused By : unknown error (code 0): Unable to convert BLOB to string
#################################################################
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:179)
at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:135)
at android.content.ContentProviderProxy.update(ContentProviderNative.java:572)
at android.content.ContentResolver.update(ContentResolver.java:1678)
... <MY CODE ABOCE - ContentResolver.update line>
Your update selection says: "update all data rows in the user's profile uri that have RAW_CONTACT_ID
equals X and IS_SUPER_PRIMARY
is true".
That means you're basically overriding all phone, email, organization, address, etc. rows in Data
table of that profile, making them all Photo
rows with the specified photo bytes[].
You need to first figure out if the profile already contains a photo, if so, update that specific photo row. If it doesn't contain a photo, you need an insert operation (and not an update).
Check my related answer here: https://stackoverflow.com/a/47660583/819355 Just modify the code to update the profile uri instead of a contact uri.