Why Update contacts methods does nothing in android - 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());
}

Related

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

How to delete all android contacts that start with a specific name?

I want to delete all contacts from my android phone that starts with a "AAA" or that contains "AAA" . Here's what I tried:
private void deleteContact(String name) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] {"AAAA"};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where, params)
.build());
Log.e(",,,,",String.valueOf(ops.get(0)));
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();
}
Toast.makeText(NativeContentProvider.this, "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();
}
but failed. Please give me some idea so I can proceed further in my project.
Maybe this will get you on the right track:
ContentResolver mContentResolver = getContentResolver();
private int deleteContactsLike(String name) {
return mContentResolver.delete(
ContactsContract.RawContacts.CONTENT_URI,
ContactsContract.Contacts.DISPLAY_NAME
+ " like ?",
new String[] { name + '%'});

Is that possible to delete the phone contact from my application

I fetched all contacts from phone and listed in list view.i am able to remove the local contact in my listview as well as database now i want to remove the phone contact is that possible. For removing purpose i am using the following code.
if (position == 1) {
db.deleteContact(item_position + 1);
from.remove(item_position);
note.notifyDataSetChanged();
}
get the selected item name and assign it to the name then try the following code.
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
String[] params = new String[] {name};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(where, params)
.build());
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();
}
Toast.makeText(getApplicationContext(), "Deleted the contact with name '" + name +"'", Toast.LENGTH_SHORT).show();
from.remove(item_position);
note.notifyDataSetChanged();
It may be same as deleting a particular log from the mobile, not sure of how far it can be done.
The code for deleting a particular call log is as follows:
public void DeleteNumFromCallLog(ContentResolver resolver, String strNum) {
try {
String strUriCalls = "content://call_log/calls";
Uri UriCalls = Uri.parse(strUriCalls);
if (null != resolver) {
resolver.delete(UriCalls, CallLog.Calls._ID + "=?",
new String[] { strNum });
}
} catch (Exception e) {
e.getMessage();
}
}
This is all we need. To delete Contact with phone number and name given
public static boolean deleteContact(Context ctx, String phone, String name)
{
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try
{
if (cur.moveToFirst())
{
do
{
if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name))
{
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return true;
}
} while (cur.moveToNext());
}
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}
And remind to add read/write contact permission
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
if you need to delete contact from Contact Uri
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
1.Get all contact from device and store into one container
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
}
phones.close();
2.Select the contact from container`
then pass selected value for performe delete operation
public static boolean deleteContact(Context ctx, String phone, String name) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
try {
if (cur.moveToFirst()) {
do {
if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
ctx.getContentResolver().delete(uri, null, null);
return true;
}
} while (cur.moveToNext());
}
} catch (Exception e) { System.out.println(e.getStackTrace()); }
return false;
}

Update information of an contact in 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());
}
}

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