I want to add my contacts from listview to contact page in android.. I am able to add contacts. But how do I avoid duplicates?
For example: I have an entry with name Jony and number 123. If I press that same contact again it shouldn't be added to contact page. I dont want to add the contact if it is already in the contact page. How can I do this?
Here is my code:
import_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> newArrayList=null;
//ArrayList<HashMap<String, String>> selectedContact=null;
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
newArrayList=ContactImportAdapter.contactsArrayList;
for(int i=0;i<newArrayList.size();i++)
{
String name;
String number;
String mail;
name=newArrayList.get(i).get("import_viewContactName");
number=newArrayList.get(i).get("import_viewContactNumber");
mail=newArrayList.get(i).get("import_viewContactMail");
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(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, name) // Name of the person
.build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, number) // Number of the person
.withValue(Phone.TYPE, Phone.TYPE_MOBILE).build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.DATA, mail)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
.build());
//Toast.makeText(getApplicationContext(), "Contact Added Successfully", Toast.LENGTH_SHORT).show();
}
newArrayList.clear();
try
{
ContentProviderResult[] res = getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
}
catch (RemoteException e)
{
// error
}
catch (OperationApplicationException e)
{
// error
}
}
});
Firstly To avoid duplicacy you will have to first call the database and check for the number if number exists then you can handle that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With