How to delete a contact? - android

I'm working at android 2.1 ContactContract, when I had not set account(for example: gmail account) to android emulator then, new a contact, but could not delete this contact at DB.
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String[] args = new String[] {id};
ops.add(ContentProviderOperation.newDelete(Data.CONTENT_URI)
.withSelection(Data.CONTACT_ID + "=?", args)
.build());
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI)
.withSelection(RawContacts.CONTACT_ID + "=?", args)
.build());
ops.add(ContentProviderOperation.newDelete(Contacts.CONTENT_URI)
.withSelection(Contacts._ID + "=?", args)
.build());

Deleting the contact from RawContacts will delete the data from Data, Contacts table.
ArrayList ops = new ArrayList(); String[] args = new String[] {id};
// if id is raw contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts._ID + "=?", args) .build());
OR
// if id is contact id
ops.add(ContentProviderOperation.newDelete(RawContacts.CONTENT_URI).withSelection(RawContacts.CONTACT_ID + "=?", args) .build());
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

public static boolean fullDeleteContactByRawId(String rawId)
{
Uri rawUri = RawContacts.CONTENT_URI.buildUpon().appendQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
String where = RawContacts._ID + " = ?";
String[] args = new String[]{rawId};
try
{
ContentManager.delete(rawUri, where, args);
}
catch(Exception e)
{
return false;
}
return true;
}
notice:
After full delete ,this contact can not sync

I use this to delete a phone number from an existing contact, but not the contact itself:
ArrayList ops = new ArrayList();
String[] args = new String[]{
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
number,
Integer.toString(ContactsContract.CommonDataKinds.Phone.TYPE_MAIN),
raw_contact_id
};
ops.add(
ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.MIMETYPE + "=? AND "
+ ContactsContract.CommonDataKinds.Phone.NUMBER + "=? AND "
+ ContactsContract.CommonDataKinds.Phone.TYPE + "=? AND "
+ ContactsContract.Data.RAW_CONTACT_ID + "=?"
, args)
.build());
c.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);

Related

Android - Update contacts without using Intent

Please help me, I am trying to update a contact by CONTACT_ID or by NAME. The only way i got it to work is with using Intent, but I want it to be updated in the background thread.
These are the code snippets I tried:
try {
String newName = "test";
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
new String[]{"Alexa Prg"})
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, newName)
.build());
ContentProviderResult[] result = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
// Do Any thing
}
and
Activity context = new Activity();
try {
ContentResolver contentResolver = context.getContentResolver();
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE + "'",
new String[]{"560"}) //ID
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, newName)
.build());
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
}
Both the snippets aren't working

How to edit existing Contacts in Android?

I am trying to edit existing phone contacts by using application. By using contact name am getting the corresponding contact id.Then am trying to update the existing contacts by using the contact id. But unfortunately it is not updating.
My code is as follows,
String select = "(" + ContactsContract.Contacts.DISPLAY_NAME + " == \"" + edt_nameDetail.getText() + "\" )";
Cursor c = getActivity().getApplicationContext().getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, CONTACTS_SUMMARY_PROJECTION, select, null, ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
getActivity().startManagingCursor(c);
if (c.moveToNext()) {
ContactId = c.getString(0);
Log.e("Tag contact id ","edit contact id "+ ContactId);
}
try
{
String name = edt_nameDetail.getText().toString().trim();
String email = edt_contactEmailDetail.getText().toString().trim();
String number = edt_mobileNumberDetail.getText().toString().trim();
ContentResolver contentResolver = getActivity().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("") &&!name.equals("")&& !number.equals(""))
{
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,emailParams)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, email)
.build());
ops.add(android.content.ContentProviderOperation.newUpdate(android.provider.ContactsContract.Data.CONTENT_URI)
.withSelection(where,nameParams)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, name)
.build());
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);
Toast.makeText(getActivity(), "Contact is successfully edited", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getActivity(), "Fail edit", Toast.LENGTH_SHORT).show();
}
If you are searching with email then update your .withSelection as
.withSelection(ContactsContract.CommonDataKinds.Email.ADDRESS + "=? AND " +
Data.MIMETYPE + "='" +
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE + "'",
new String[]{email})
update all your withselection code corresponding to your search type
Note: after this, contact ID will changed.
public static boolean updateContactName(String contactId, String pre, String first, String mid, String last, String suf)
{
try
{
if (pre == null && first == null && mid == null && last == null && suf == null)
return false;
String where = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] nameParams = new String[]{contactId, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE};
ArrayList<android.content.ContentProviderOperation> ops = new ArrayList<>();
android.content.ContentProviderOperation.Builder t ;
android.content.ContentProviderOperation b ;
t = android.content.ContentProviderOperation.newUpdate(Data.CONTENT_URI);
t = t.withSelection(where, nameParams);
if(pre != null)
t = t.withValue(StructuredName.PREFIX, pre.trim());
if(first != null)
t = t.withValue(StructuredName.GIVEN_NAME, first.trim());
if(mid != null)
t = t.withValue(StructuredName.MIDDLE_NAME, mid.trim());
if(last != null)
t = t.withValue(StructuredName.FAMILY_NAME, last.trim());
if(suf != null)
t = t.withValue(StructuredName.SUFFIX, suf.trim());
b = t.build();
ops.add(b);
ContentManager.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
return true;
}
catch (Exception e) {}
return false;
}

Why can not I set the email address if not set before the name to android?

I can not understand why I can not enter the email address unless you first insert the name , if the comment section what set the name the email works fine but I can not rightly then to enter the name , can anyone help ?
public String updateContact(String id, String name, String number,
String email, String surname, Context context,
ArrayList<EmailContactBean> listEmail) {
String resultId = null;
if (id == null) {
resultId = addContact(context, name, surname, number, email);
} else {
String raw_contact_id = getRawContactId(id, context);
ContentResolver contentResolver = context.getContentResolver();
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
// update name
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(ContactsContract.Data.CONTACT_ID + "=?",
new String[] { id })
.withValue(StructuredName.GIVEN_NAME, name).build());
// update surname
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(COLUMN_CONTACT_ID + "=? ",
new String[] { id })
.withValue(StructuredName.DATA3, surname).build());
// update number
Cursor numberCur = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[] { id }, null);
if ((null == numberCur) || (!numberCur.moveToFirst())) {
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID,
raw_contact_id)
.withValue(ContactsContract.Data.MIMETYPE,
Phone.CONTENT_ITEM_TYPE)
.withValue(
ContactsContract.CommonDataKinds.Phone.NUMBER,
number).build());
} else {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE
+ "=?",
new String[] { id, MIMETYPE_STRING_PHONE })
.withValue(COLUMN_NUMBER, number)
.build());
}
// update email
Cursor emailCur = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[] { id }, null);
if ((null == emailCur) || (!emailCur.moveToFirst())) {
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValue(ContactsContract.Data.RAW_CONTACT_ID,
raw_contact_id)
.withValue(ContactsContract.Data.MIMETYPE,
Email.CONTENT_ITEM_TYPE)
.withValue(Email.TYPE, listEmail.get(0).getType())
.withValue(ContactsContract.CommonDataKinds.Email.DATA,
listEmail.get(0).getName()).build());
} else {
for (int i = 0; i < listEmail.size(); i++) {
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data._ID + "=? AND "
+ COLUMN_MIMETYPE + "=?",
new String[] { listEmail.get(i).getId(),
MIMETYPE_STRING_EMAIL })
.withValue(COLUMN_EMAIL, listEmail.get(i).getName())
.withValue(COLUMN_EMAIL_TYPE,
listEmail.get(i).getType()).build());
}
}
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
}
}
return resultId;
}
I solved it , just do not set MIMETYPE 's name and surname :
// update name
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.CONTACT_ID + "=? AND "
+ COLUMN_MIMETYPE + "=?",
new String[] { id, MIMETYPE_STRING_NAME })
.withValue(StructuredName.DATA2, name).build());
// update surname
ops.add(ContentProviderOperation
.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(
COLUMN_CONTACT_ID + "=? AND " + COLUMN_MIMETYPE
+ "=?",
new String[] { id, MIMETYPE_STRING_NAME })
.withValue(StructuredName.DATA3, surname).build());

remove contact from a specific group in android

I am making an android app, I want to remove a contact from a specific group not to delete contact just remove from the group, I have group id and contact id, can anyone please tell me the query to do this,
I want to implement something like Delete contact_id=1 from group_id=2
Contacts are linked to groups with ContactsContract.CommonDataKinds.GroupMembership records. You can use something like this to delete contact from group:
private void deleteContactFromGroup(long contactId, long groupId)
{
ContentResolver cr = getContentResolver();
String where = ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=" + groupId + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.RAW_CONTACT_ID + "=?" + " AND "
+ ContactsContract.CommonDataKinds.GroupMembership.MIMETYPE + "='"
+ ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE + "'";
for (Long id : getRawContactIdsForContact(contactId))
{
try
{
cr.delete(ContactsContract.Data.CONTENT_URI, where,
new String[] { String.valueOf(id) });
} catch (Exception e)
{
e.printStackTrace();
}
}
}
private HashSet<Long> getRawContactIdsForContact(long contactId)
{
HashSet<Long> ids = new HashSet<Long>();
Cursor cursor = getContentResolver().query(RawContacts.CONTENT_URI,
new String[]{RawContacts._ID},
RawContacts.CONTACT_ID + "=?",
new String[]{String.valueOf(contactId)}, null);
if (cursor != null && cursor.moveToFirst())
{
do
{
ids.add(cursor.getLong(0));
} while (cursor.moveToNext());
cursor.close();
}
return ids;
}
Note that when you perform delete, you should specify RAW_CONTACT_ID instead of CONTACT_ID. So you need to query all raw contact ids for specified contact.
Also you may need to consider account data. In that case change querying for contact ids to something like that:
Uri rawContactUri = RawContacts.CONTENT_URI.buildUpon()
.appendQueryParameter(RawContacts.ACCOUNT_NAME, accountName)
.appendQueryParameter(RawContacts.ACCOUNT_TYPE, accountType).build();
Cursor cursor = getContentResolver().query(rawContactUri,
new String[] { RawContacts._ID }, RawContacts.CONTACT_ID + "=?",
new String[] { String.valueOf(contactId) }, null);
public static Uri addContactToGroup(String rawContactId,String groupId)
{
try
{
ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(GroupMembership.GROUP_ROW_ID, groupId);
values.put(Data.MIMETYPE, GroupMembership.CONTENT_ITEM_TYPE);
return getContentResolver.insert(Data.CONTENT_URI, values);
}
catch (Exception e)
{}
return Uri.EMPTY;
}
//-----------------------------------
public static int removeContactFromGroup(String contactId,String groupId)
{
try
{
String where = Data.CONTACT_ID + " = ? AND " + Data.MIMETYPE + " = ? AND " + GroupMembership.GROUP_ROW_ID + " = ?";
String[] args = {contactId, GroupMembership.CONTENT_ITEM_TYPE, groupId};
return getContentResolver.delete(Data.CONTENT_URI, where, args);
}
catch (Exception e)
{}
return 0;
}

How to update contact number using Android

I am learning android. I am trying to upadate contact number programmatically. Could anyone help me please how can I do that.
My effort is:
String lNumber = pCur.getString( pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContentValues values = new ContentValues();
Uri lPhoneUri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, ContactsContract.CommonDataKinds.Phone.NUMBER);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, "45323333"));
getContentResover().update(lPhoneUri, values, ContactsContract.CommonDataKinds.Phone.NUMBER+"=?", new String[] { lNumber });
I think you are pretty much there. The following uses the new API to update the WORK phone number of a contact, assume that that contact already has a work phone number.
public void updateContact (String contactId, String newNumber, Activity act)
throws RemoteException, OperationApplicationException{
//ASSERT: #contactId alreay has a work phone number
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId, String.valueOf(Phone.TYPE_WORK)};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(Phone.NUMBER, newNumber)
.build());
act.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
Try this
String where = ContactsContract.Data.DISPLAY_NAME + "=? AND " +
ContactsContract.Data.MIMETYPE + "=? AND " +
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE) + "=?";
String[] params = new String[] {
Cname,
ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
String.valueOf(ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
};
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER,"9999999999")
// .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "Sample Name 21")
.build()
);
//email
String where3 = ContactsContract.Data.DISPLAY_NAME + " = ? AND " +
ContactsContract.Data.MIMETYPE + " = ?";
String[] params3 = new String[] {
Cname,
"vnd.android.cursor.item/email_v2"
};
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where3, params3)
.withValue(ContactsContract.CommonDataKinds.Email.DATA,"a#b.com")
.build()
);
By using this I am able to update the contact details.
Just small change, if you need to update some other phone than work phone, you can have method that has this as a parameter.
public void updateContact (String contactId, String newNumber, String phoneType)
throws RemoteException, OperationApplicationException{
//ASSERT: #contactId alreay has a work phone number
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
String selectPhone = Data.CONTACT_ID + "=? AND " + Data.MIMETYPE + "='" +
Phone.CONTENT_ITEM_TYPE + "'" + " AND " + Phone.TYPE + "=?";
String[] phoneArgs = new String[]{contactId, phoneType};
ops.add(ContentProviderOperation.newUpdate(Data.CONTENT_URI)
.withSelection(selectPhone, phoneArgs)
.withValue(Phone.NUMBER, newNumber)
.build());
this.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
This class may help to update the contact.
public class UpdateContact extends Activity {
private EditText txtName,txtPh;
private Button btnUpdate;
private TextView txt;
private static final String TAG_ID="id";
private static final String TAG_NAME = "name";
private static final String TAG_PHNO = "phNo";
private static int id;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_contact);
txtName=(EditText)findViewById(R.id.txtNname);
txtPh=(EditText)findViewById(R.id.txtNPhNo);
btnUpdate=(Button)findViewById(R.id.btnUpdate);
txt=(TextView)findViewById(R.id.txtId);
Intent i=getIntent();
id=i.getIntExtra(TAG_ID,0);
txtName.setText(i.getStringExtra(TAG_NAME));
txtPh.setText(i.getStringExtra(TAG_PHNO));
//to update contact on button click you can apply this
btnUpdate.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
DatabaseHandler handler=new DatabaseHandler(UpdateContact.this);
Contact contact=new Contact();
contact.setID(id);
contact.setName(txtName.getText().toString());
contact.setPhNo(txtPh.getText().toString());
handler.UpdateContact(contact);
finish();
}
});
}
}
Here's how you update your Phone.Home.
val rawContactId = "101"
val contentProviderOperation = ArrayList<ContentProviderOperation>()
val where = ContactsContract.Data.RAW_CONTACT_ID + "=? AND " +
ContactsContract.Contacts.Data.MIMETYPE + "=" +
"'${ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE}'" + " AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + "=?"
val params = arrayOf(rawContactId, "${ContactsContract.CommonDataKinds.Phone.TYPE_HOME}")
contentProviderOperation.add(
ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI)
.withSelection(where, params)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "+60123456789")
.build()
)
try {
contentResolver.applyBatch(ContactsContract.AUTHORITY, contentProviderOperation)
showToastyMessage("Contact Update Successfully")
} catch (exception: Exception) {
showToastyMessage(exception.message.toString())
}

Categories

Resources