iam adding a contact to the device using this code
long Contact_Id = 100;
ContentValues pCV =new ContentValues();
pCV.put(Contacts.People.NAME, "test");
pCV.put(ContactsContract.Contacts._ID, Contact_Id);
Uri newContactUri = insertContentValues(cResolver,
Contacts.People.CONTENT_URI, pCV);
i want to add this contact to a certain Account. iam using this code below
ContentResolver cResolver = context.getContentResolver();
cResolver.insert(uri, ContactsContract.RawContacts.CONTENT_URI,
getAccountType());
public ContentValues getAccountType() {
ContentValues cv = new ContentValues();
cv.put(ContactsContract.RawContacts.ACCOUNT_TYPE, "com.sonyericsson.localcontacts");
cv.put(ContactsContract.RawContacts.ACCOUNT_NAME, "Phone contacts");
return cv;
}
this code actually is adding a new contact to the "Phone contacts" Account. but i want to add the contact that i added above ("test") to be added to the "Phone contacts".
how can i do so?
You can try both the solution as per your choice/requirement.Both are working perfectly
To add contact open directly edit activity
try {
Intent addContactIntent = new Intent(Intent.ACTION_INSERT);
addContactIntent.setType(ContactsContract.Contacts.CONTENT_TYPE);
addContactIntent.putExtra(ContactsContract.Intents.Insert.PHONE, number);
addContactIntent.putExtra("finishActivityOnSaveCompleted", true);
context.startActivity(addContactIntent);
} catch (Exception e) {
e.printStackTrace();
}
option to create contact or add contact to existing contact
try {
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
// i.putExtra(ContactsContract.Intents.Insert.NAME, "TESTTEST");
i.putExtra(ContactsContract.Intents.Insert.PHONE, number);
context.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
After searching I have found that the best way to insert a Contact to the Local Phone contacts is to assign the ACCOUNT_TYPE, ACCOUNT_NAME to null take a look at this Link
Related
I have made an contact application. I am able to delete contact from samsung and moto but in MI(XIOMI) unable to delete contact. It display popup with message "Contact can't delete by third party apps. My code
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
String[] args = new String[]{id};
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(ContactsContract.RawContacts.CONTACT_ID + "=?", args).build());
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException | OperationApplicationException e) {
}
Was the RawContact created on your app's Account using your SyncAdapter?
Anyway, try this:
Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
rawContactUri = rawContactUri.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
ContentProviderOperation.newDelete(rawContactUri).build();
I am trying to delete a contact from phone contacts. The contact gets deleted from phone contacts but it's not getting deleted from the server-side (Google contacts) and when the Google contact sync triggers then that deleted contact re-appears. Below is my code.
public static void deleteContact(long rawid, ContentResolver contentResolver) {
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
Uri uri = ContactsContract.RawContacts.CONTENT_URI
.buildUpon()
.appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER,
"true")
.build();
ops.add(ContentProviderOperation
.newDelete(uri)
.withSelection(
ContactsContract.RawContacts._ID + " = ?",
new String[]{Long.toString(rawid)})
.build());
try {
contentResolver.applyBatch(
ContactsContract.AUTHORITY,
ops);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
}
You should try with ContactsContract.CALLER_IS_SYNCADAPTER as false in your code. While set to true, the contact is permanently deleted from the database. But when the next sync happens the contact is synched back. How Google sync checks for deleted contacts, is using a deleted flag which is set only if you set ContactsContract.CALLER_IS_SYNCADAPTER as false. Below is a snippet of code from the ContactsProvider class (contentprovider for contacts datastore)
if (callerIsSyncAdapter || rawContactIsLocal(rawContactId)) {
// When a raw contact is deleted, a SQLite trigger deletes the parent contact.
// TODO: all contact deletes was consolidated into ContactTableUtil but this one can't
// because it's in a trigger. Consider removing trigger and replacing with java code.
// This has to happen before the raw contact is deleted since it relies on the number
// of raw contacts.
db.delete(Tables.PRESENCE, PresenceColumns.RAW_CONTACT_ID + "=" + rawContactId, null);
count = db.delete(Tables.RAW_CONTACTS, RawContacts._ID + "=" + rawContactId, null);
mTransactionContext.get().markRawContactChangedOrDeletedOrInserted(rawContactId);
} else {
count = markRawContactAsDeleted(db, rawContactId, callerIsSyncAdapter);
}
I've worked hard on the following code, but unfortunately, the entry is assigned to the wrong contact. I don't know why. Tested for hours days but can't find the mistake. Can you help me?
I would like to use the code in order to select a person from the contact list (using the contact picker) and then adding an event entry (date of birth) for this person to the contacts table.
Step 1:
I've already set the permission in the manifest file:
<uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission>
Step 2:
The contact picker's ID is defined:
private static final int CONTACT_PICKER_ID = 123;
Step 3:
The contact picker is called:
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_ID);
Step 4:
Another method listens for the contact picker's result and tries to add an event for the selected user:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_ID:
Uri selectedPerson = data.getData();
String contactId = selectedPerson.getLastPathSegment();
// ADD A NEW EVENT FOR THE SELECTED CONTACT --- BEGIN
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
values.put(ContactsContract.Data.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.CommonDataKinds.Event.LABEL, "");
values.put(ContactsContract.CommonDataKinds.Event.START_DATE, "2010-01-28"); // hard-coded date of birth
Uri created = null;
try {
created = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
catch (Exception e) {
}
if (created == null) {
Toast.makeText(this.getApplicationContext(), "Failed inserting the event!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this.getApplicationContext(), "Successfully inserted the event!", Toast.LENGTH_SHORT).show();
}
// ADD A NEW EVENT FOR THE SELECTED CONTACT --- END
break;
}
}
}
The event is successfully inserted to the database and also shown in the Google contacts - but unfortunately it's assigned to the wrong contact. Why is this so? Is my contactId wrong that I get from the contact picker?
The activity result that you get back from the contact picker is the full path to the contact. Something like:
content://com.android.contacts/contacts/lookup/0r7-2C46324E483C324A3A484634/7
This is what's in your:
Uri selectedPerson = data.getData();
This contains both the Contact's LOOKUP_KEY AND the Contact's _ID. However, you need to be using the RawContacts _ID when inserting into the Data table. What you need to do is grab the RawContact's _ID:
long rawContactId = -1;
Cursor c = getContentResolver().query(RawContacts.CONTENT_URI,
new String[]{RawContacts._ID},
RawContacts.CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)}, null);
try {
if (c.moveToFirst()) {
rawContactId = c.getLong(0);
}
} finally {
c.close();
}
And then use the rawContactId:
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
However, it should be noted that there can be multiple RawContacts per one Contact. You may want to adjust your code so that it adds an event for each RawContact.
One entry is wrong in your content values. The Uri which you get in your onActivityResult data variable is not the raw_contact_id but the contact id. The difference between both is that one contact can contain multiple raw contacts. A raw contact is associated with a single account like Google or Facebook. But a contact can contain multiple raw_contacts.
Uri selectedPerson = data.getData();
String contactId = selectedPerson.getLastPathSegment();
// ADD A NEW EVENT FOR THE SELECTED CONTACT --- BEGIN
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE);
***values.put(ContactsContract.Data.CONTACT_ID, contactId);***
values.put(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY);
values.put(ContactsContract.CommonDataKinds.Event.RAW_CONTACT_ID, contactId);
values.put(ContactsContract.CommonDataKinds.Event.LABEL, "");
values.put(ContactsContract.CommonDataKinds.Event.START_DATE, "2010-01-28"); // hard-coded date of birth
try switching...
Uri created = null;
try {
created = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}catch (Exception e) {
}
if (created == null) {
Toast.makeText(this.getApplicationContext(), "Failed inserting the event!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this.getApplicationContext(), "Successfully inserted the event!", Toast.LENGTH_SHORT).show();
}
to...
try{
Uri created = getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
if (created == null) {
Toast.makeText(this.getApplicationContext(), "Failed inserting the event!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this.getApplicationContext(), "Successfully inserted the event!", Toast.LENGTH_SHORT).show();
}
}catch (Exception e) {}
I want to create a new contact group. I can query the group and display all the group names but I can't create a group in android I tried as creating contacts method but not created...
ContentResolver cr = this.getContentResolver();
groupValues = new ContentValues();
Log.e("Group","start");
groupValues.put(android.provider.Contacts.GroupMembership.GROUP_ID, 4);
groupValues.put(android.provider.Contacts.GroupMembership.NAME, "Sriseshaa");
groupValues.put(android.provider.Contacts.GroupMembership.PERSON_ID, 1);
cr.insert(android.provider.Contacts.GroupMembership.CONTENT_URI, groupValues);
i found the answer.i found in two ways but i dont know which is correct or best way to use.i am sharing those here..
its simple way like adding contact,
ContentValues groupValues;
create group()
{
ContentResolver cr = this.getContentResolver();
groupValues = new ContentValues();
groupValues.put(ContactsContract.Groups.TITLE, "MyContactGroup");
cr.insert(ContactsContract.Groups.CONTENT_URI, groupValues);
}
Another method using ContentProviderOperation
private void createGroup() {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Groups.CONTENT_URI)
.withValue(ContactsContract.Groups.TITLE, "SRI").build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
Thanks
adithi's answer is enough for Android 4.2.2, in which the name of Contacts manager application is "Contacts" , but the group created by that code will not show on Android 4.4,6 in which the name of Contacts manager application is "People".
The group would show up after adding the account type/name information while insertion happens.
private void createGroup() {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Groups.CONTENT_URI)
.withValue(
ContactsContract.Groups.TITLE,
Constants.CC_CONTACT_GROUP_TITLE)
.withValue(
ContactsContract.Groups.ACCOUNT_TYPE,
Constants.CC_CONTACT_GROUP_ACCOUNT_TYPE)
.withValue(
ContactsContract.Groups.ACCOUNT_NAME,
Constants.CC_CONTACT_GROUP_ACCOUNT_NAME)
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
Why are you specifying group ID with groupValues.put(android.provider.Contacts.GroupMembership.GROUP_ID, 4); Its androids job to determined the group ID, you cant specify it because you don't know whether this id is already taken or not.
I have added one contact to android by following code.
ContentValues values = new ContentValues();
Uri rawContactUri = getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);
values.put(StructuredName.DISPLAY_NAME, "Mike Sullivan");
getContentResolver().insert(Data.CONTENT_URI, values);
It shows up on emulator 2.1, but when i am going to delete it manually by "delete contact" option, its not deleteing from emulator.
If I edit some thing on it then only it deletes.
How can i directly delete it from menu ?
Thanks in advance...
Could you please use the below code to add the contact. This will not affect your emulator to delete contact from menu without editing the same.
import android.provider.Contacts.People;
public void addvaluestocontent()
{
ContentValues values = new ContentValues();
values.put(People.NAME, "Abraham Lincoln");
values.put(People._ID, "1");
values.put(People.NUMBER, "23333");
Uri uri = getContentResolver().insert(People.CONTENT_URI, values);
}
You have to save one more field, either "Given Name" or "Family Name". You can test it manually by saving contacts. First try to save manaully only number and then with saving contacts with both name and number.
Simple, Delete the .db file all contacts were deleted. and android will create new file automatically.
path for .db is:
data/data/com.android.providers.contacts/database/contacts.db
Use this method to Check your SDK version and Get the Contacts content Uri. After, that you can insert the contacts with this new Content Uri,
static
{
int sdk=new Integer(Build.VERSION.SDK).intValue();
if (sdk>=5) {
try {
Class<?> clazz=Class.forName("android.provider.ContactsContract$Contacts");
CONTENT_URI=(Uri)clazz.getField("CONTENT_URI").get(clazz);
}
catch (Throwable t) {
Log.e("PickDemo", "Exception when determining CONTENT_URI", t);
}
}
else {
CONTENT_URI=Contacts.People.CONTENT_URI;
}
}
Refer, CommonsWare Examples for Contacts Content Uri. This may be helps you.