getting contact id after saving android contact - android

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

Related

ContactsContract.RawContacts.VERSION is not changing

I am trying to listen to the changes of Contacts. So I tried with one contact first. I have registered a Contact with my app ACCOUNT_TYPE. And trying to listen changes of that particular contact only. whenever there is a change in the Contact ContactsContract.RawContacts.VERSION should get incremented and ContactsContract.RawContacts.DIRTY should become 1. but nothing is getting changed. I am modifying contact in default phone contacts app.
Here is how I am registering contact
ContactsManager.addContact(this,new MyContact("1000","961820018","sandwitch"));
addContact Code:
public static void addContact(Context context,MyContact contact){
ContentResolver resolver = context.getContentResolver();
boolean mHasAccount = isAlreadyRegistered(resolver, contact.Id);
if(mHasAccount){
Log.d("Contact already","there");
} else {
Log.d("new Contact","Adding");
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// insert account name and account type
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.RawContacts.CONTENT_URI, true))
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, Constants.ACCOUNT_NAME)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, Constants.ACCOUNT_TYPE)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE,
ContactsContract.RawContacts.AGGREGATION_MODE_DEFAULT)
.build());
// insert contact number
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, contact.number)
.build());
// insert contact name
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contact.name)
.build());
// insert mime-type data
ops.add(ContentProviderOperation
.newInsert(addCallerIsSyncAdapterParameter(ContactsContract.Data.CONTENT_URI, true))
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, MIMETYPE)
.withValue(ContactsContract.Data.DATA1, 12345)
.withValue(ContactsContract.Data.DATA2, "user")
.withValue(ContactsContract.Data.DATA3, "MyData")
.build());
try {
resolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
this is how I am reading the changes with check VERSION
private void readUpdate(){
Cursor cursor = mContentResolver.query(ContactsContract.RawContacts.CONTENT_URI,
new String[]{ContactsContract.RawContacts.VERSION, ContactsContract.RawContacts.CONTACT_ID,ContactsContract.RawContacts.ACCOUNT_TYPE},
ContactsContract.RawContacts.ACCOUNT_TYPE+"=? ",
new String[]{String.valueOf(Constants.ACCOUNT_TYPE)},
null);
if (cursor != null && cursor.getCount() >0)
{
cursor.moveToFirst();
while(!cursor.isAfterLast()){
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.CONTACT_ID));
String version = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.VERSION));
String type = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
if(id!=null && dirty!=null&& type!=null){
Log.d("Upadte version",version);
Log.d("Update ACCountid",id);
Log.d("Update type", type);
Cursor cur = mContentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?",
new String[]{String.valueOf(id)},
null);
if(cur!=null && cur.getCount()>0) {
cur.moveToFirst();
while(!cur.isAfterLast()){
String name = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number = cur.getString(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("Update Name", name);
Log.d("Update Number", number);
/* ContactsManager.updateContact(getContext(), id, name, number);
CV.clear();
CV.put(DBconstants.TableConstants.PHONE_NUMBER, number);
CV.put(DBconstants.TableConstants.C_CONTACT_NAME, name);
DB.updateInformation(DB, DBconstants.TableConstants.TABLE_CONTACTS, CV, DBconstants.TableConstants.C_ID, id);
CV.clear();
*/ cur.moveToNext();
}
cur.close();
}else{
Log.d("update", "nullinvalues");
}
}else{
Log.d("update", "nullvalues");
}
cursor.moveToNext();
}
cursor.close();
}else {
Log.d("update", "nullcursor");
}
}

Android insert contact not showing name

I am trying to export contact from my application to the Android's default contact list. I am using an intent to insert the contact details by launching the contact activity. The contact activity pre-populate most of the intent data in the form, but It is not able to populate the name of the contact. Here is my code for populating the intent data.
ArrayList<ContentValues> data = new ArrayList<>();
if (!contactDetails.getName().isEmpty()) {
ContentValues rowName = new ContentValues();
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());
data.add(rowName);
}
if (!contactDetails.getCompany().isEmpty()) {
ContentValues rowCompany = new ContentValues();
rowCompany.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
rowCompany.put(ContactsContract.CommonDataKinds.Organization.COMPANY, contactDetails.getCompany());
data.add(rowCompany);
}
if (!contactDetails.getPhone().isEmpty()) {
ContentValues rowPhone = new ContentValues();
rowPhone.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
rowPhone.put(ContactsContract.CommonDataKinds.Phone.NUMBER, contactDetails.getPhone());
data.add(rowPhone);
}
ContentValues rowEmail = new ContentValues();
rowEmail.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
rowEmail.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_MOBILE);
rowEmail.put(ContactsContract.CommonDataKinds.Email.LABEL, "Work");
rowEmail.put(ContactsContract.CommonDataKinds.Email.ADDRESS, contactDetails.getEmail());
data.add(rowEmail);
Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putParcelableArrayListExtra(ContactsContract.Intents.Insert.DATA, data);
startActivity(intent);
Here is the screen shot. Notice that the name field is empty, even when intent has the data.
I feel that I am not providing the right value for the following lines.
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, contactDetails.getName());
I tried the NickName field and it does work. example code.
if (!contactDetails.getName().isEmpty()) {
ContentValues rowName = new ContentValues();
rowName.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
rowName.put(ContactsContract.CommonDataKinds.Nickname.NAME, contactDetails.getName());
data.add(rowName);
}
But not sure why it is not able to successfully display the name. Am i missing something here?
Try this its working for me ,and let me inform if you are facing still any issue .Here there are five fields for user to insert data , you can modify this as per ur need.
This is for adding new contact
// Creating a button click listener for the "Add Contact" button
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_phone);
// Getting reference to HomePhone EditText
EditText etHomePhone = (EditText) findViewById(R.id.et_home_phone);
// Getting reference to HomeEmail EditText
EditText etHomeEmail = (EditText) findViewById(R.id.et_home_email);
// Getting reference to WorkEmail EditText
EditText etWorkEmail = (EditText) findViewById(R.id.et_work_email);
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());
// Adding insert operation to operations list
// to insert Home Phone 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, etHomePhone.getText().toString())
.withValue(Phone.TYPE, Phone.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Home Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etHomeEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_HOME)
.build());
// Adding insert operation to operations list
// to insert Work Email in the table ContactsContract.Data
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactID)
.withValue(ContactsContract.Data.MIMETYPE, Email.CONTENT_ITEM_TYPE)
.withValue(Email.ADDRESS, etWorkEmail.getText().toString())
.withValue(Email.TYPE, Email.TYPE_WORK)
.build());
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();
}
}
This is for display contact list
OnClickListener contactsClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// Creating an intent to open Android's Contacts List
Intent contacts = new Intent(Intent.ACTION_VIEW,ContactsContract.Contacts.CONTENT_URI);
// Starting the activity
startActivity(contacts);
}
};
This are the permissions you need to set in side Manifest
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
I fixed this problem by just adding the following line just before startActivity() method call.
intent.putExtra(ContactsContract.Intents.Insert.NAME, contactDetails.getName());
You can use cursor to fetch contacts from device.
public void fetchContacts() {
String phoneNumber = null;
String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
String DATA = ContactsContract.CommonDataKinds.Email.DATA;
StringBuffer output = new StringBuffer();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
output.append("\n First Name:" + name);
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
output.append("\n Phone number:" + phoneNumber);
}
phoneCursor.close();
// Query and loop for every email of the contact
Cursor emailCursor = contentResolver.query(EmailCONTENT_URI, null, EmailCONTACT_ID+ " = ?", new String[] { contact_id }, null);
while (emailCursor.moveToNext()) {
email = emailCursor.getString(emailCursor.getColumnIndex(DATA));
output.append("\nEmail:" + email);
}
emailCursor.close();
}
output.append("\n");
}
System.out.println(output);
}
}

Android - How to get saved contact id

I want to get saved contact id and i used following way to retrieve it but the problem is it's returning the wrong id.
public static String addContact(FragmentActivity activity, String displayname, String mobilenumber, String homeemail) {
String DisplayName = displayname;
String MobileNumber = mobilenumber;
String homeemailID = homeemail;
int contactID = 0;
ArrayList<ContentProviderOperation> contentProviderOperation = new ArrayList<ContentProviderOperation>();
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());
// ------------------------------------------------------ Names
if (DisplayName != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, DisplayName).build());
}
// ------------------------------------------------------ Mobile Number
if (MobileNumber != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE).build());
}
// ------------------------------------------------------ homeEmail
if (homeemailID != null) {
contentProviderOperation.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, homeemailID)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME).build());
}
// Asking the Contact provider to create a new contact
try {
// activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY,
// contentProviderOperation);
ContentProviderResult[] res = activity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, contentProviderOperation);
Uri myContactUri = res[0].uri;
int lastSlash = myContactUri.toString().lastIndexOf("/");
int length = myContactUri.toString().length();
contactID = Integer.parseInt((String) myContactUri.toString().subSequence(lastSlash + 1, length));
} catch (Exception e) {
e.printStackTrace();
}
return contactID;
}
I think it passing the wrong contact data uri.Please help me to get correct contact id.
Try this way:
Uri contactUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
// query time
Cursor cursor = context.getContentResolver().query(contactUri, projection, null, null, null);
if (cursor.moveToFirst()) {
// Get values from contacts database:
contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup._ID));
name = cursor.getString(cursor.getColumnIndex(ContactsContract.PhoneLookup.DISPLAY_NAME));
}
You don't need to get the id in this way. There's a getLastPathSegment() method in Uri class. Use this instead
Uri myContactUri = res[0].uri;
contactID = Ineger.parseInt(myContactUri.getLastPathSegment());
Other than that, this is the right way to get saved contact id.

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

How to import contacts from VCF file by using code

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

Categories

Resources