How to import contacts from VCF file by using code - android

I have create a vcf file that contains contacts by using this code
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
System.out.println("The value is " + cr.getType(uri));
AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
how can I import this file into the device by code?

After searching the Web the best way to import contacts is as follows
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE,null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.withValue(RawContacts.STARRED, Starred)
.withValue(RawContacts.CUSTOM_RINGTONE, CustRingTone)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, displayName)
.withValue(StructuredName.PHONETIC_GIVEN_NAME, PhoneticName_First)
.withValue(StructuredName.PHONETIC_MIDDLE_NAME, PhoneticName_Middle)
.withValue(StructuredName.PHONETIC_FAMILY_NAME, PhoneticName_Last)
.build());
for (RowData phone : phones) {
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, phone.data)
.withValue(Phone.TYPE, phone.type)
.withValue(Phone.LABEL, phone.customLabel)
.build());
}

Related

How to update 'profile' contact programmatically in Android?

I want to edit the device main user's profile from within my application. So I used the ContentProviderOperation with newUpdate method to collect the changes and then commit them using the ContentResolver method's : applyBatch. Here is the code i wrote so far:
public ContentProviderResult[] updateProfile(Contact userProfile) {
try {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(userProfile.id))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edtName.getText().toString().trim())
.build());
return getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
I am getting any run-time Exception but no change is commited!
Am I missing something?
I have figured it out, the problem was that I didn't know how to retrieve the User Profile RAW_CONTACT_ID to project on it on the ContactsContract.Data table.
My quick fix was by deleting the User Profile record and then create a new one. This is the code I used so far :
public ContentProviderResult[] createOrUpdateUserProfile() {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();
try {
ops.add(ContentProviderOperation.
newDelete(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
ops.clear();
//Create User Profile
ops.add(ContentProviderOperation.newInsert(ContactsContract.Profile.CONTENT_RAW_CONTACTS_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
//Create User Name
if (!(edtName.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edtName.getText().toString())
.build());
}
if (!(edtHomePhone.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtHomePhone.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1)
.build());
}
if (!(edtMobilePhone.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtMobilePhone.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 2)
.build());
}
if (!(edtWorkPhone.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, edtWorkPhone.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 3)
.build());
}
if (!(edtHomeEmail.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edtHomeEmail.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 1) // contact.numbers.get(0).type
.build());
}
if (!(edtWorkEmail.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, edtWorkEmail.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, 2) // contact.numbers.get(0).type
.build());
}
/*String completeAddress = edtStreet.getText().toString() + edtCity.getText().toString() + edtState.getText().toString()
+ edtCountry.getText().toString();*/
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, edtStreet.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, edtCity.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, edtState.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, edtCountry.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, edtZip.getText().toString())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, 1)
.build());
if (!(edtSkype.getText().toString().matches(""))) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Im.DATA, edtSkype.getText().toString())
.withValue(ContactsContract.CommonDataKinds.Im.PROTOCOL, 3)
.build());
}
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return res;
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
your code has a a bit error.
public ContentProviderResult[] updateProfile(Contact userProfile) {
try {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(userProfile.id)) // Error is here
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, edtName.getText().toString().trim())
.build());
return getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
use for this line:
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(userProfile.id))
this
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, getRawContactId(id))
public static String getRawContactId(String contactId)
{
String res = "";
Uri uri = ContactsContract.RawContacts.CONTENT_URI;
String[] projection = new String[]{ContactsContract.RawContacts._ID};
String selection = ContactsContract.RawContacts.CONTACT_ID + " = ?";
String[] selectionArgs = new String[]{ contactId };
Cursor c = ContentManager.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if(c != null && c.moveToFirst())
{
res = c.getString(c.getColumnIndex(ContactsContract.RawContacts._ID));
c.close();
}
return res;
}

Android - contacts address field updating to other fields

I am trying to update the native contact data through my app.
The problem is when I am updating with address, the address is updating to First name and notes and phone fields. below code is I used in my app, please correct me if any mistake.
public ArrayList<ContentProviderOperation> updateContact(Context context, ContactData contactData){
String selectPhone = ContactsContract.Data.CONTACT_ID + "=?";
String[] phoneArgs = new String[]{contactData.getContactLocalId()};
ArrayList <ContentProviderOperation> ops = new ArrayList <> ();
ops.add(ContentProviderOperation.newUpdate(
ContactsContract.RawContacts.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
//------------------------------------------------------ Names
ops.add(ContentProviderOperation.newUpdate(
ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
contactData.getFirstName())
.withValue(
ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME,
contactData.getLastName())
.build());
//------------------------------------------------------ Mobile Number
ops.add(ContentProviderOperation.
newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactData.getContactPhoneBook().get(0).getNumber())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
//------------------------------------------------------ Email
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, contactData.getEmailbook().get(0).getEmail())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
//------------------------------------------------------ Notes
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, contactData.getNotes())
.build());
//------------------------------------------------------ Address
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, contactData.getAddressbook().get(0).getStreet_line_1())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.STREET)
.build());
// Asking the Contact provider to updating a contact
try {
ContentProviderResult[] result = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return ops;
}
Finally I found answer for my problem.
String selectPhone = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "= ?";
String[] nameArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] mobileArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
String[] emailArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] notesArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
String[] addressArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
we should pass separate arguments for updating.
public ContactData updateContact(Context context, ContactData contactData){
String selectPhone = ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "= ?";
String[] nameArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
String[] mobileArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE};
String[] emailArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE};
String[] notesArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
String[] addressArgs = new String[]{contactData.getContactLocalId(), ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
ArrayList <ContentProviderOperation> ops = new ArrayList <> ();
//------------------------------------------------------ Names
ops.add(ContentProviderOperation.newUpdate(
ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, nameArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, contactData.getFirstName())
.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, contactData.getLastName())
.build());
//------------------------------------------------------ Mobile Number
ops.add(ContentProviderOperation.
newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, mobileArgs)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contactData.getContactPhoneBook().get(0).getNumber())
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
//------------------------------------------------------ Email
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, emailArgs)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, contactData.getEmailbook().get(0).getEmail())
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
//------------------------------------------------------ Notes
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, notesArgs)
.withValue(ContactsContract.CommonDataKinds.Note.NOTE, contactData.getNotes())
.build());
//------------------------------------------------------ Address
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(selectPhone, addressArgs)
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, contactData.getAddressbook().get(0).getStreet_line_1())
.withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, ContactsContract.CommonDataKinds.StructuredPostal.STREET)
.build());
// Asking the Contact provider to updating a contact
try {
ContentProviderResult[] result = context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
String serverId = markAsUpdated(contactData);
contactData.setContactId(serverId);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return contactData;
}

adding contact automatically in phone book in android app

I need to add a contact automatically in phone book by my app....I found this link..
How to add new contacts in android
using this, I am able to add phone no.,name,email etc. But don't know how to add photo.
Firstly convert your image to bitmap and then use below code for adding photo to your contact.
OnClickListener addClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Getting reference to Name EditText
EditText etName = (EditText) findViewById(R.id.et_name);
// Getting reference to Mobile EditText
EditText etMobile = (EditText) findViewById(R.id.et_mobile);
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
int rawContactID = ops.size();
// Adding insert operation to operations list
// to insert a new raw contact in the table ContactsContract.RawContacts
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null)
.build());
// Adding insert operation to operations list
// to insert display name in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, etName.getText().toString())
.build());
// Adding insert operation to operations list
// to insert Mobile Number in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, etMobile.getText().toString())
.withValue(Phone.TYPE, CommonDataKinds.Phone.TYPE_MOBILE)
.build());
ByteArrayOutputStream stream = new ByteArrayOutputStream();
if(mBitmap!=null){ // If an image is selected successfully
mBitmap.compress(Bitmap.CompressFormat.PNG , 75, stream);
// Adding insert operation to operations list
// to insert Photo in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1)
.withValue(ContactsContract.Data.MIMETYPE,Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO,stream.toByteArray())
.build());
try {
stream.flush();
}catch (IOException e) {
e.printStackTrace();
}
}
try{
// Executing all the insert operations as a single database transaction
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Toast.makeText(getBaseContext(), "Contact is successfully added", Toast.LENGTH_SHORT).show();
}catch (RemoteException e) {
e.printStackTrace();
}catch (OperationApplicationException e) {
e.printStackTrace();
}
}
};
For more details please refer below link
http://wptrafficanalyzer.in/blog/programatically-adding-contacts-with-photo-using-contacts-provider-in-android-example/
Use following code this takes picture as photoByteArray for the method
private void addContact2() {
final String displayName = "XYZA";
final String mobileNumber = "666666";
final byte[] photoByteArray; // initalized elsewhere
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "")
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, "")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName)
//.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, photoByteArray)
.build());
Uri newContactUri = null;
ContentProviderResult[] res = null;
try {
final ContentResolver contentResolver = getContentResolver();
res = contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
if (res != null && res.length > 0 && res[0] != null) {
newContactUri = res[0].uri;
Log.d(CallActivity.class.getName(), "URI added contact:"+ newContactUri);
Toast.makeText(this, "Successfully added " + displayName, Toast.LENGTH_LONG).show();
}
else Log.e(CallActivity.class.getName(), "Contact not added.");
} catch (NullPointerException | RemoteException | OperationApplicationException e) {
Log.e(CallActivity.class.getName(), e.getMessage(), e);
}
}

getting contact id after saving android contact

I am saving a contact by this code
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
...
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, accountType)
.withValue(RawContacts.ACCOUNT_NAME, accountName)
.build());
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.GIVEN_NAME, linkname1)
.withValue(StructuredName.FAMILY_NAME, linkname2)
.build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
After saving the contact, I need to get the _ID field so that I can fetch that contact from the contact book for editing. How can I get the id after saving?
Thanks in advance
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Uri myContactUri = res[0].uri;
int contactID = Integer.parseInt(myContactUri.getLastPathSegment());
Here you go. Get the contact id for the number( ´phnumber` ) from the contacts
String[] projection = new String[]{Contacts._ID};
Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,Uri.encode(phnumber));
Cursor c = getContentResolver().query(contactUri, projection,
null, null, null);
if (c.moveToFirst()) {
long contactId=c.getColumnIndex(Contacts._ID);
c.close();
}

Add contact inside a group with group id

I need to insert a contact inside a group. I have the id of the group. But I can't. Don't know why.
Can anyone help me?
Here is my code.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
Account[] accounts = AccountManager.get(getActivity()).getAccounts();
String accountName = null;
String accountType = null;
String account = "mail#gmail.com";
for(Account account2 : accounts)
if(account2.name.equals(account)){
accountName = account2.name;
accountType = account2.type;
}
ops.add(ContentProviderOperation
.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName)
.build());
ops.add(ContentProviderOperation
.newAssertQuery(ContactsContract.Groups.CONTENT_URI)
.withSelection(ContactsContract.Groups._ID + "=?", new String[]{Long.toString(idGroup)})
.withExpectedCount(1)
.build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.CommonDataKinds.StructuredName.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "RICARDO")
.build());
try{
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}catch(Exception e){
Log.e("ERROR", e.toString());
}
This inserts a contact to a group by referring its id:
Builder builder = ContentProviderOperation.newInsert(Data.CONTENT_URI);
builder.withValueBackReference(Data.RAW_CONTACT_ID, 0);
builder.withValue(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
builder.withValue(GroupMembership.GROUP_ROW_ID, groupId);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("ContactsManager", "Failed to apply batch: "+e);
}

Categories

Resources