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;
}
Related
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 + '%'});
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());
}
I have some issues when updating phone number for contacts of different phone type. I need to add prefix xxx with all the numbers. For example: "Paul" have Mobile: 42342397908, Home: 3453459534, Work: 4345436533, Other: 3253454354, Other: 3465465464, Mobile: 34564654654. The update is working but when it saves it is like this. Mobile: xxx42342397908, Home: xxx3453459534, Work: xxx4345436533, Other: xx3253454354, Other: xx3253454354, Mobile: xxx42342397908. It overrides the one which have same phone type with the same phone number. please see below my update function and help me.
private void updateContact(String name, String phone,String id, String type) {
ContentResolver cr = getContentResolver();
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = null;
/*
ContentProviderOperation.Builder builderPhone = ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=?"+" AND "+ContactsContract.Data.MIMETYPE + "=?" + " AND "+Phone.TYPE+"=?",
new String[]{String.valueOf(id), Phone.CONTENT_ITEM_TYPE, String.valueOf(phoneType)});
*/
if (Integer.valueOf(type) == Phone.TYPE_MOBILE)
{
params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)};
}
else if (Integer.valueOf(type) == Phone.TYPE_HOME)
{
params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
}
else if (Integer.valueOf(type) == Phone.TYPE_WORK)
{
params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_WORK)};
}
else if (Integer.valueOf(type) == Phone.TYPE_OTHER)
{
params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_OTHER)};
}
// ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE
Cursor phoneCur = managedQuery(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.NUMBER, phone)
.withValue(ContactsContract.CommonDataKinds.Phone.TYPE, type)
.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();
}
}
How to edit firstname,surname,mobilenumber,photo,email,address in native contact in android programmatically using contact id. Please help me. Thanks in advance.
on Button click do the following:
Intent in = new Intent(Intent.ACTION_INSERT_OR_EDIT);
in.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivityForResult(in,EDIT_CONTACT);
and in onActivityResult Function do this:
case EDIT_CONTACT:
if (resultCode == RESULT_OK) {
Uri contactData = data.getData();
Cursor cur = managedQuery(contactData, null, null, null, null);
ContentResolver contect_resolver = getContentResolver();
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String name = "";
String no = "";
String key = cur.getString(cur.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY));
String where = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + " = ? ";
String[] params = new String[] {name,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_HOME)};
Cursor phoneCur = contect_resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id }, null);
if (phoneCur.moveToFirst()) {
name = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
no = phoneCur.getString(phoneCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
key = phoneCur.getString(phoneCur.getColumnIndexOrThrow(ContactsContract.Contacts.LOOKUP_KEY));
System.out.println("EDITIDDDDDDDDDD"+name);
System.out.println("EDITIDDDDDDDDDD"+no);
System.out.println("EDITIDDDDDDDDDD"+key);
/*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, no)
.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();
}
*/
id = null;
name = null;
no = null;
phoneCur = null;
key = null;
contect_resolver = null;
cur = null;
}
}
}
break;
I been working on an app that helps sending sms to your contacts. Everything is great, except that I'm supposed to add a "custom field number" to a contact such as "Work" or "Private". I'd search the web for answers and the ones that are useful for evryone, aren't for me. This is my code:
private void AddCtxtAttribute(int contactID, String contactNumber) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(Data.CONTENT_URI);
builder.withValue(Data.RAW_CONTACT_ID, contactID);
builder.withValue(ContactsContract.Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
builder.withValue(ContactsContract.Data.DATA1, contactNumber);
builder.withValue(ContactsContract.Data.DATA2, Phone.TYPE_CUSTOM);
builder.withValue(ContactsContract.Data.DATA3, "My Custom Label");
ops.add(builder.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
Log.e("RESULT", "Success! " + contactID + " - "
+ contactNumber);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
} catch (OperationApplicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("ERROR", "error : " + e.toString());
}
}
And it's called:
AddCtxtAttribute(contacto_id, contacto_numero);
where contacto_id and contacto_numero are a int and a String respectively.
The problem is that when I pressed the button, I have the ID (contacto_id) of that contact but it updates other contact. (like the id's don't match) but i've debug it and the id doesn't change.
Can anyone help me with this?
I figured it out!
the problem was that i was using diferent column names and uris in reading the contacts and inserting a new contact number.
I did this:
to query all contacts:
private void llenar_contactos() {
ProgressDialog progress;
lista_contactos_cel_sobrantes = null;
sobrantes = false;
lista_contactos_cel = new ArrayList<HashMap<String, Object>>();
progress = ProgressDialog.show(contactsActivity.this, "",
"Cargando Contactos. Porfavor espere...");
String[] projection = new String[] { Data.RAW_CONTACT_ID,
Phone.DISPLAY_NAME, Phone.NUMBER, Phone.LABEL };
String selection = Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'";
// ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + "='1'";
String sort_order = "display_name ASC";
Uri mContacts = Data.CONTENT_URI;
// ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor contacts = getContentResolver().query(mContacts, // Contact URI
projection, // Which columns to return
selection, // Which rows to return
null, // Where clause parameters
sort_order // Order by clause
);
total_contactos = contacts.getCount();
if (total_contactos > 0) {
int i = 0;
int multiplo = 0;
int indice_total = 0;
int temp_registros = 0;
String contact_id = "";
String name = "";
String phoneNo = "";
String label = "";
sobrantes = false;
int nameFieldColumnIndex = 0;
while (contacts.moveToNext()) {
nameFieldColumnIndex = contacts.getColumnIndex(Data.RAW_CONTACT_ID);
if (nameFieldColumnIndex > -1) {
contact_id = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.DISPLAY_NAME);
if (nameFieldColumnIndex > -1) {
name = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.NUMBER);
if (nameFieldColumnIndex > -1) {
phoneNo = contacts.getString(nameFieldColumnIndex);
}
nameFieldColumnIndex = contacts.getColumnIndex(Phone.LABEL);
if (nameFieldColumnIndex > -1) {
label = contacts.getString(nameFieldColumnIndex);
}
if(label != null){
Log.i("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
} else {
Log.d("CONTACTO", "id: " + contact_id + " -> name: " + name
+ " ->number: " + phoneNo + " ->label: " + label);
}
}
contacts.close();
}
}
And to insert a new custom label:
private void AddCtxtAttribute(int contactID, String contactNumber) {
if (contactID != 0 && contactNumber != null) {
ArrayList<ContentProviderOperation> ops =
new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
.withValue(Data.RAW_CONTACT_ID, contactID)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, contactNumber)
.withValue(Phone.TYPE, Phone.TYPE_CUSTOM)
.withValue(Phone.LABEL, "My Custom Label")
.build());
try{
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();
}
}
}