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);
}
Related
im trying to add new contacts to the phone but he does only the first 12 items.
i want to try all current 36 items and maybe more add to the phone contacts.
while ((line = bufferedReader.readLine()) != null) {
System.out.println("[[DEBUG]] [DW-UPDATE] LINE: " + line);
String[] split = line.split(";", -1);
split[2] = split[2].replace("/", "").replace("-", "");
if (!contactExists(mActivity, split[2])) {
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.withValue(ContactsContract.RawContacts.AGGREGATION_MODE, ContactsContract.RawContacts.AGGREGATION_MODE_DISABLED)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, split[1])
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, Integer.valueOf(split[0]))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, split[2])
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE,ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
}
function contactExists:
public boolean contactExists(Activity _activity, String number) {
Uri lookupUri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
String[] mPhoneNumberProjection = { ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.NUMBER, ContactsContract.PhoneLookup.DISPLAY_NAME };
Cursor cur = _activity.getContentResolver().query(lookupUri, mPhoneNumberProjection, null, null, null);
try {
if (cur.moveToFirst()) {
return true;
}
} finally {
if (cur != null)
cur.close();
}
return false;
}// contactExists
what i must do, to work this better?
Your problem is with your back references when adding the additional contact data. The back reference should refer to the position of your RawContacts.CONTENT_URI insert within your list of operations (ops), not the position of the contact within your raw data file. You can fix this by keeping track of the size of ops through each iteration:
if (!contactExists(mActivity, split[2])) {
int backRef = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(...)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build()
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, backRef)
.withValue(...)
.build());
try {
mActivity.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
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");
}
}
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);
}
}
I use this code to add a new contact:
ContentResolver mContentResolver = v.getContext().getContentResolver();
ArrayList<ContentProviderOperation> operationList = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder;
builder = ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, account.name);
builder.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type);
operationList.add(builder.build());
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.CommonDataKinds.StructuredName.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
operationList.add(builder.build());
mContentResolver.applyBatch(ContactsContract.AUTHORITY, operationList);
the point is, after add a contact, how can I add an email to that contact?
I know insert an email at the same time:
builder = ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI);
builder.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0);
builder.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.CommonDataKinds.Email.DATA, email);
builder.withValue(ContactsContract.CommonDataKinds.Email.TYPE,ContactsContract.CommonDataKinds.Email.TYPE_HOME);
operationList.add(builder.build());
After create a new contact and insert to database, save the RAW_CONTACT_ID, then insert a new email under this id.
Here is an example to do.
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI).withValue(
ContactsContract.RawContacts.ACCOUNT_NAME, "null"
).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, "null").build());
ops.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, "test").build());
try {
ContentProviderResult[] results = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
if (results != null && results.length >= 1) {
ops.clear();
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID, ContentUris.parseId(results[0].uri))
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, "test#abc.com").build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.d(TAG, results[0].uri.toString());
} else {
Log.d(TAG, "result is empty");
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
This is the solution. You need the raw_contact_id:
private void InsertEmail(long raw_contact_id, String email){
ContentValues values = new ContentValues();
values.put(ContactsContract.Data.RAW_CONTACT_ID, raw_contact_id);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Email.DATA, email);
values.put(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_HOME);
context.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
}
I am trying to add new contacts from within in my android application. However - when I do it and check my contact list the new contact isn't there? I have ensured the display name is unique and looked at a few threads like How to add new contacts in android but have still had no luck. Any suggestions? I call the contact class from another activity.
public class Contact {
public Contact(String displayName, String emailAddress, Context context) {
super();
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).build());
ops.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, emailAddress)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE,
ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, displayName)
.build());
try {
ContentProviderResult[] res = context.getApplicationContext()
.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}