Update information of an contact in android - android

I want to update new information of an contact. I need to update 3 fields: Name, phone number and company name of the contact. Here is my code. The problem of my is: the method does not update any new information!
Could you show me the reasons why I have the error. And show me how to fix it! Thanks guys!
public void editContact(String _id, String name, String phone, String company) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data._ID + " = ?" ;
String[] params = new String[] {_id};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.Data.DISPLAY_NAME, name)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone)
.withValue(ContactsContract.CommonDataKinds.Organization.DATA, company)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("ERROR UPDATE: ", e.getMessage());
}
this.finish();
Toast.makeText(getApplicationContext(), "Contact saved", Toast.LENGTH_SHORT).show();
this.callHomeActivity();
}

#Stacks28: This is me - Mr.Pakapun
I try to update only the name of the contact by using the code below. BUT, nothing happends! The name of the contact is not been updated. What wrong with the code ?
public void editContact(String _id, String name, String phone, String company) {
String where = ContactsContract.Data._ID + " = ? AND " +
ContactsContract.Data.MIMETYPE + "= ?";
String[] params = new String[] {_id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE };
ContentResolver cr = getContentResolver();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(where, params)
.withValue(StructuredName.DISPLAY_NAME, name)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.e("ERROR UPDATE: ", e.getMessage());
}
}

Related

Edit and update contact's data in android

i made an application that have read/write contacts permissions. i'm trying to make an updating function that gets new display name, an email address and phone number to add by using this:
public void updateContact(Context ctx, String name, String number, String email,String ContactId) {
try {
name = name.trim();
email = email.trim();
number = number.trim();
ContentResolver contentResolver = ctx.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(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.build());
}
if(!name.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.Contacts.DISPLAY_NAME, name)
.build());
}
if(!number.equals(""))
{
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);
} catch (Exception e) {
e.printStackTrace();
}
}
Sadly this code isn't making any changes to the contact and it's hard for me to find out why.
Thanks for any help :)
well, nobody helps me but i managed it by my own.
for anyone who gets the same issues i'm posting the answer for my own question.
the following code will update the phone, name and email's contact.
public static void updateContact(Context ctx, String name, String number, String email, Long id) {
try {
ContentValues contentValues;
long ret = id;
Log.i("contact id", ret + "");
if (!name.equals("")) {
contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, ret);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name);
ctx.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
}
if (!number.equals("")) {
contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, ret);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, number);
int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);
ctx.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
}
if (!email.equals("")) {
contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, ret);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.ADDRESS, email);
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_CUSTOM);
ctx.getContentResolver().insert(ContactsContract.Data.CONTENT_URI, contentValues);
}
} catch (Exception e) {
e.printStackTrace();
}
}

Performance of update existing contact in Android so slow

i have a problem in update existing contact in Android. My code execute about 400 contact but it take me about 20s to update it. Here is my code.
public class Contact {
private long contactId;
private String phoneNumber;
private int phoneType;
}
Then i try to update each contact filter by ID and Type:
ArrayList list = arrayLists[0];
for (int i = 0; i < list.size(); i++) {
Contact contact = list.get(i);
long contactID = contact.getContactId();
String newPhoneNumber = contact.getPhoneNumber();
int phoneType = contact.getPhoneType();
updateContact(contactID, newPhoneNumber, phoneType);
}
Here is my updateContact funtion:
private void updateContact(long contactID, String newPhoneNumber, int phoneType) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " + ContactsContract.CommonDataKinds.Phone.TYPE + " = ?";
String[] whereParams = new String[]{contactID + "", phoneType + ""};
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber);
Uri dataUri = ContactsContract.Data.CONTENT_URI;
cr.update(dataUri, contentValues, where, whereParams);
}
I tried other method to update contact but it also take same time ( about 20s for 400 contact)
private void updateContact(long contactID, String newPhoneNumber, int phoneType) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = ?";
String[] params = new String[]{contactID + "", phoneType + ""};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, newPhoneNumber)
.build());
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
What should i do, how can i improve the performance of update job. I expert it can update 400 contact in 3-5s

trying to update a contact with this code isn't working

I'm trying to use this code to allow a user edit a contact's name and number. I get no errors and when I print nameofcontact and numberofcontact in my log it shows me the latest changes I've made to the name and number of the contact.
But it's not saving to my contacts database. Any ideas what's wrong?
public void editButton(View view) {
// the text in the 'nameofcontact' edittext box, can be modified by the user
contactname = nameofcontact.getText().toString();
// the text in the 'numberofcontact' edittext box, can be modified by the user
contactnumber = numberofcontact.getText().toString();
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = new String[] {contactname,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
Cursor phoneCur = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, where, params, null);
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// if ( (null == phoneCur) ) {
// createContact(name, phone);
// } else
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.DATA, contactnumber)
.build());
}
phoneCur.close();
try {
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println (contactname);
System.out.println (contactnumber);
Toast.makeText(this, "Updated", Toast.LENGTH_SHORT).show();
}
Please check you add below permission in your manifeast or not
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
and you can use this method it works for me.
public boolean updateContact(String name, String number, String ContactId) {
boolean success = true;
String phnumexp = "^[0-9]*$";
try {
name = name.trim();
number = number.trim();
if (name.equals("") && number.equals("")) {
success = false;
} else if ((!number.equals("")) && (!match(number, phnumexp))) {
success = false;
} else {
ContentResolver contentResolver = SwipableHomeActivity.this
.getContentResolver();
String where = Data.CONTACT_ID + " = ? AND "
+ Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{
ContactId,
StructuredName.CONTENT_ITEM_TYPE};
String[] numberParams = new String[]{
ContactId,
Phone.CONTENT_ITEM_TYPE};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
if (!name.equals("")) {
ops.add(ContentProviderOperation
.newUpdate(
Data.CONTENT_URI)
.withSelection(where, nameParams)
.withValue(StructuredName.DISPLAY_NAME, name)
.build());
}
if (!number.equals("")) {
ops.add(ContentProviderOperation
.newUpdate(
Data.CONTENT_URI)
.withSelection(where, numberParams)
.withValue(Phone.NUMBER, number).build());
}
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
}
} catch (Exception e) {
e.printStackTrace();
success = false;
}
return success;
}

Why Update contacts methods does nothing in android

I write an Update method to update contacts but after i run this on my phone nothing happen
and no contact get update why?
this is my method :
public Boolean UpdateContacts(ArrayList<ContactInfo> encryptedContactsInfoList) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentResolver cr = null;
for (ContactInfo contactInfo : encryptedContactsInfoList) {
try {
String contactId = contactInfo.getContactID();
String contactName = contactInfo.getContactName();
String contactNumber = contactInfo.getContactNumber();
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(
ContactsContract.CommonDataKinds.Phone._ID
+ " = ?", new String[] { contactId })
.withValue(ContactsContract.Data.DISPLAY_NAME,
"asdffgh").build());
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.d("exception", e.getMessage());
}
}
return true;
}
this is ops after executing the code:
[{"mSelection":"_id \u003d ?","mSelectionArgs":["2302"],"mUri":{"authority":
{"decoded":"com.android.contacts","encoded":"com.android.contacts"},"fragment":{},"path":
{"decoded":"NOT CACHED","encoded":"/data"},"query":{},"scheme":"content","uriString":"NOT
CACHED","host":"NOT CACHED","port":-2},"mValues":{"mValues":
{"display_name":"asdffgh"}},"mType":2,"mYieldAllowed":false}]
any help really appreciate,
best regards.
You get nothing because your ContentResolver is null, so you get an exception in every iteration.
Your app does not crash because you have catch (Exception e) that catches every exception.
try with:
ContentResolver cr = getContentResolver();
also, the applyBatch call should be after the for loop, otherwise you are procesing many times every item, and change ContactsContract.CommonDataKinds.Phone._ID to ContactsContract.Data._ID
try {
for (ContactInfo contactInfo : encryptedContactsInfoList) {
String contactId = contactInfo.getContactID();
String contactName = contactInfo.getContactName();
String contactNumber = contactInfo.getContactNumber();
ops.add(ContentProviderOperation
.newUpdate(Data.CONTENT_URI)
.withSelection(
ContactsContract.Data._ID
+ " = ?", new String[] { contactId })
.withValue(ContactsContract.Data.DISPLAY_NAME,
"asdffgh").build());
}
cr.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
Log.d("exception", e.getMessage());
}

Delete a single phone type number from a contact

When a one of the contact have multiple numbers, for example:
Display name: GuessWho TYPE = home Number = homeNumber
TYPE = mobile Number = mobileNumber TYPE = other
Number = otherNumber ...
in conclusion ... one from those.
How I can remove a TYPE with number from this contact ( let's say "mobile" )? I have to update it using the userID acquired from the previous query, or how?
I just need to delete a single TYPE with number, other field of the contact must remain intact.
I am using this piece of code for obtaining contact :
int indexName = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int indexNumber = c
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int indexType = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
int indexID = c.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
String name = c.getString(indexName);
String number = c.getString(indexNumber);
String type = c.getString(indexType);
String typeStored = (String) Phone.getTypeLabel(mContext.getResources(), Integer.parseInt(type), "");
Log.i("TYPE READED : ", typeStored);
String id = c.getString(indexID);
where c is the cursor of the query.
Each number from same contact has it's own ID. You should use it for deleting. But you also need contact ID. You can get it using this line of code:
contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
Then you delete the number using following code:
Cursor cur = contentResolver.query(RawContacts.CONTENT_URI,
new String[]{RawContacts._ID},
RawContacts.CONTACT_ID + "=?",
new String[] {contactID.toString()}, null);
int rowId=0;;
if(cur.moveToFirst()){
rowId = cur.getInt(cur.getColumnIndex(RawContacts._ID));
}
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = Data.RAW_CONTACT_ID + " = ? AND " +
Data.MIMETYPE + " = ? AND " +
Phone._ID + " = ?";
String[] phoneArgs = new String[] { Integer.toString(rowId),
Phone.CONTENT_ITEM_TYPE,
ID.toString()};
ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs).build());
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
The code to delete is a little long, the below does what it should with less lines of code
public static void deleteContact(ContentResolver contactHelper, String number) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] { String.valueOf(getContactID(contactHelper, number)) };
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts.CONTACT_ID + "=?", args).build());
try {
contactHelper.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}

Categories

Resources