Insert a new android contact photo - android

I have a problem when I want to insert a photo for a contact.
I want to insert the "parent" contact image, which have no image.
I just want to change the photo of the contact, not the raw contact (contact_id)
It just works for Update, but not for insert, what is wrong ? The photo is not recorded in content providers.
//UPDATE
if (contact.getPhotoURL() != null){
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[] { String.valueOf(contact.getId()), ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE })
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
.build());
}else{
//INSERT
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValue(ContactsContract.Data.CONTACT_ID, contact.getId())
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray())
.build());
}
Thanks
EDIT :
this following code works
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
ContentResolver c = ctx.getContentResolver();
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " = " + personId + " AND " + ContactsContract.Data.MIMETYPE + "=='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = c.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID, personId);
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, baos.toByteArray());
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
if (photoRow >= 0) {
c.update(ContactsContract.Data.CONTENT_URI, values, ContactsContract.Data._ID + " = " + photoRow, null);
} else {
c.insert(ContactsContract.Data.CONTENT_URI, values);
}
The field IS_SUPER_PRIMARY fixes the problem, the photo is saved for the "global" contact, not just the specific raw_contact.
Regards.

Related

Store hidden sync identifier in android raw contact

I'd like to create an app which syncs contacts from a given server. To identify those contacts, I'd like to store a identifier in the android contact in a hidden field.
I've found the field SYNC1 which seems to appropriate for that, but I've no idea how to use this field correctly.
I tried setting it in the following way:
ArrayList<ContentProviderOperation> ops =
new ArrayList<>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, ACCOUNT_NAME)
.withValue(ContactsContract.RawContacts.SYNC1, "myInternalId")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Test User")
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
The issue is now, that the batch insert runs through, but the field isn't set in the contact, because it is empty when I try to read it afterwards:
ContentResolver cr = this.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
String id = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(
ContactsContract.Contacts.DISPLAY_NAME));
String sync1 = null;
int sync1Index = cur.getColumnIndex(ContactsContract.RawContacts.SYNC1);
if (sync1Index >= 0) {
sync1 = cur.getString(sync1Index);
}
System.out.println("Contact id=" + id + " name=" + name + " sync1=" + sync1);
}
}
cur.close();
If I want to set it in the raw contact, so in the second batch, I get an exception.
The way you insert the value seems correct, but the method that reads the value isn't.
You can't query Contacts.CONTENT_URI and get fields from the RawContacts table.
To read back your value, try this:
ContentResolver cr = this.getContentResolver();
String[] projection = new String[] { RawContacts._ID, RawContacts.CONTACT_ID, RawContacts.SYNC1 }
String selection = RawContacts.ACCOUNT_TYPE + " = '" + accountType + "' AND " + RawContacts.ACCOUNT_NAME + " = '" + accountName + "'";
Cursor cur = cr.query(ContactsContract.RawContacts.CONTENT_URI, projection, selection, null, null);
while (cur.moveToNext()) {
Long rawId = cur.getLong(0);
Long contactId = cur.getLong(1);
String sync1 = cur.getString(2);
System.out.println("Contact id=" + contactId + " raw-id=" + rawId + " sync1=" + sync1);
}
cur.close();

Android : Update exicting Contact List

I am trying to edit my contact list through my App. I can able to update Contact name , Phone number and Email. But, when I try to change existing photo it is not updating.
When I try to add new contact with image it is successfully added
Problem occur when I try to edit existing Contact with Image
Code that I using for Update Contact
ContentResolver contentResolver = getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{idValue, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{idValue, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{idValue, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
int photoRow = -1;
String wherePhoto = ContactsContract.Data.RAW_CONTACT_ID + " = " + idValue + " AND " + ContactsContract.Data.MIMETYPE + " =='" + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI, null, wherePhoto, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if (cursor.moveToFirst()) {
photoRow = cursor.getInt(idIdx);
}
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, edt_contactEmail.getText().toString().trim())
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edt_contact_name.getText().toString().trim())
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edt_contactNumber.getText().toString().trim())
.build());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(contact_bitmap!=null){ // If an image is selected successfully
contact_bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
byte[] b = stream.toByteArray();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data._ID + " = ?", new String[]{Integer.toString(photoRow)})
.withValue(ContactsContract.Data.RAW_CONTACT_ID, idValue)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.Data.DATA15, b)
.build());
try {
stream.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(EditContacts.this,"Contact Successfully updated",Toast.LENGTH_LONG).show();
Intent i = new Intent(EditContacts.this,MainActivity.class);
finish();
startActivity(i);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
Can any one please tell me how to edit existing contact with image.
Thanks in advance :)
I have used this example for updating contact.
ContactManager
Method to update Contact:
boolean updateContact(String contactID, String contactName, String contactNumber, String contactEmailAdd, Bitmap bitmap) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=?", new String[]{contactID, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactName)
.build());
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=? AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
, new String[]{contactID, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
, String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)})
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactNumber)
.build());
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE
+ "=? AND " + ContactsContract.CommonDataKinds.Organization.TYPE + "=?"
, new String[]{contactID, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
, String.valueOf(Email.TYPE_WORK)})
.withValue(Email.ADDRESS, contactEmailAdd)
.build());
try {
ByteArrayOutputStream image = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, image);
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " +
ContactsContract.Data.MIMETYPE + "=?", new String[]{contactID, Photo.CONTENT_ITEM_TYPE})
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(Photo.PHOTO, image.toByteArray())
.build());
/*Builder builder;
builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(ContactsContract.Data.CONTACT_ID + "=?" + " AND " + ContactsContract.Data.MIMETYPE + "=?",
new String[]{contactID, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE});
builder.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, image.toByteArray());
ops.add(builder.build());*/
} catch (Exception e) {
e.printStackTrace();
}
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

How to edit existing Contacts in Android?

I am trying to edit existing phone contacts by using application. By using contact name am getting the corresponding contact id.Then am trying to update the existing contacts by using the contact id. But unfortunately it is not updating.
My code is as follows,
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" + edt_nameDetail.getText() + "\" )";
Cursor c = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
getActivity().startManagingCursor(c);
if (c.moveToNext()) {
ContactId = c.getString(0);
Log.e("Tag contact id ","edit contact id "+ ContactId);
}
try
{
String name = edt_nameDetail.getText().toString().trim();
String email = edt_contactEmailDetail.getText().toString().trim();
String number = edt_mobileNumberDetail.getText().toString().trim();
ContentResolver contentResolver = getActivity().getContentResolver();
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] emailParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] nameParams = new String[]{ContactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{ContactId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<android.content.ContentProviderOperation>();
if(!email.equals("") &&!name.equals("")&& !number.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,numberParams)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, number)
.build());
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getActivity(), "Contact is successfully edited", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "Fail edit", Toast.LENGTH_SHORT).show();
}
If you are searching with email then update your .withSelection as
.withSelection(ContactsContract.CommonDataKinds.Email.ADDRESS + "=? AND " +
Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'",
new String[]{email})
update all your withselection code corresponding to your search type
Note: after this, contact ID will changed.
public static boolean updateContactName(String contactId, String pre, String first, String mid, String last, String suf)
{
try
{
if (pre == null && first == null && mid == null && last == null && suf == null)
return false;
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
android.content.ContentProviderOperation.Builder t ;
android.content.ContentProviderOperation b ;
t = android.content.ContentProviderOperation.newUpdate(Data.CONTENT_URI);
t = t.withSelection(where, nameParams);
if(pre != null)
t = t.withValue(StructuredName.PREFIX, pre.trim());
if(first != null)
t = t.withValue(StructuredName.GIVEN_NAME, first.trim());
if(mid != null)
t = t.withValue(StructuredName.MIDDLE_NAME, mid.trim());
if(last != null)
t = t.withValue(StructuredName.FAMILY_NAME, last.trim());
if(suf != null)
t = t.withValue(StructuredName.SUFFIX, suf.trim());
b = t.build();
ops.add(b);
ContentManager.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return true;
}
catch (Exception e) {}
return false;
}

Display name not updating Email.Content_URI

I am trying to update Display name and email id of an existing contact, I am able to update email address, but display name not updating, the code I am using is here. I have tried plenty of more code but nothing is working for me please help.
Cursor cursorEmail = getContentResolver()
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = "
+ model.getContactid(),
null, null);
if (cursorEmail
.moveToFirst()) {
ops.add(ContentProviderOperation
.newUpdate(
ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.CONTACT_ID
+ "=? AND "
+ ContactsContract.Data.MIMETYPE
+ "=?",
new String[] {
String.valueOf(model
.getContactid()),
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.withValue(
ContactsContract.CommonDataKinds.Email.ADDRESS,
txtEditedMailId
.getText()
.toString()
.trim()
.toLowerCase())
.withValue(
ContactsContract.CommonDataKinds.Email.DISPLAY_NAME,
txtEditedName
.getText()
.toString()
.trim()
.toLowerCase())
.build());
}
cursorEmail.close();
getContentResolver()
.applyBatch(
ContactsContract.AUTHORITY,
ops);
final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Cursor cursorEmail = getContentResolver()
.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = "
+ model.getContactid(),
null, null);
if (cursorEmail.moveToFirst()) {
//Update Email
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(
Email.CONTACT_ID
+ "=? AND "
+ ContactsContract.Data.MIMETYPE
+ "=?",
new String[] {
String.valueOf(model
.getContactid()),
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE })
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.withValue(
ContactsContract.CommonDataKinds.Email.DATA,
txtEditedMailId
.getText()
.toString()
.trim()
.toLowerCase())
.build());
//Update image
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory
.decodeFile(localPathEditedImage,
options);
Logger.debug("path--------"
+ imgAbsPath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(
Bitmap.CompressFormat.PNG, 100,
baos); // bm is the bitmap object
byte[] photoByteArray = baos
.toByteArray();
Builder builder = ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI);
builder = ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI);
builder.withSelection(
ContactsContract.Data.CONTACT_ID
+ "=?"
+ " AND "
+ ContactsContract.Data.MIMETYPE
+ "=?",
new String[] {
String.valueOf(model
.getContactid()),
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE });
builder.withValue(
ContactsContract.CommonDataKinds.Photo.PHOTO,
photoByteArray);
ops.add(builder.build());
//Update Display name
ops.add(ContentProviderOperation
.newUpdate(
RawContacts.CONTENT_URI)
.withSelection(
Email.CONTACT_ID
+ " = ?",
new String[] { String.valueOf(model
.getContactid()) })
.withValue(
RawContacts.DISPLAY_NAME_PRIMARY,
txtEditedName.getText()
.toString())
.build());
}
cursorEmail.close();
//Execute Batch
getContentResolver().applyBatch(
ContactsContract.AUTHORITY, ops);
//Contact updated

To set Contact Picture using Contact ID

I have a Bitmap and a Contact id. I want a function that takes these parameters and sets the Bitmap as the Contact picture of that id. Can you help me please?
try
Convert your bitmap into byteArray
Bitmap bit; // <-- put your bitmap here
ByteArrayOutputStream streamy = new ByteArrayOutputStream();
bit.compress(CompressFormat.PNG, 0, streamy);
byte[] photo = streamy.toByteArray();
and then
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(yourContectID) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = managedQuery(
ContactsContract.Data.CONTENT_URI,
null,
where,
null,
null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if(cursor.moveToFirst()){
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID,
ContentUris.parseId(yourContectID));
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(photoRow >= 0){
this.getContentResolver().update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
this.getContentResolver().insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}
don not forget to add permissions WRITE_CONTACTS and READ_CONTACTS in your manifest file

Categories

Resources