Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

Android Contact Operations Insert/Search/Delete

4.67/5 (3 votes)
17 Apr 2013CPOL 58.4K   4.4K  
This article helps you to insert, search, and delete an item from your Android device contacts.

Introduction

This article helps you to insert, search, and delete an item from your Android device contacts.

Using the code

Using the Contact Operation class given in this article, you can easily do operations with your contact list such as insert, search, and delete. In the demo project, the main activity shows how to use the Contact Operation class with parameters.

The code snippets shows insert, search, and delete functions.

Insert an item to contacts:

Java
public static void Insert2Contacts(Context ctx, String nameSurname,
               String telephone) {
   if (!isTheNumberExistsinContacts(ctx, telephone)) {
       ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
       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(ContactsContract.Data.CONTENT_URI)
                      .withValueBackReference(
                                     ContactsContract.Data.RAW_CONTACT_ID,
                                     rawContactInsertIndex)
                      .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
                      .withValue(Phone.NUMBER, telephone).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, nameSurname)
                      .build());
       try {
               ContentProviderResult[] res = ctx.getContentResolver()
                              .applyBatch(ContactsContract.AUTHORITY, ops);
       } catch (Exception e) {
 
               Log.d(TAG, e.getMessage());
       }
   }
}

Search an item inside contacts:

Java
public static boolean isTheNumberExistsinContacts(Context ctx,
                       String phoneNumber) {
   Cursor cur = null;
   ContentResolver cr = null;
 
   try {
    cr = ctx.getContentResolver();
 
   } catch (Exception ex) {
    Log.d(TAG, ex.getMessage());
   }
 
   try {
     cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
                  null, null);
   } catch (Exception ex) {
     Log.i(TAG, ex.getMessage());
   }
 
   try {
       if (cur.getCount() > 0) {
           while (cur.moveToNext()) {
              String id = cur.getString(cur
                              .getColumnIndex(ContactsContract.Contacts._ID));
              String name = cur
                             .getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
              // Log.i("Names", name);
              if (Integer
                         .parseInt(cur.getString(cur
                                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                  // Query phone here. Covered next
                  Cursor phones = ctx
                                 .getContentResolver()
                                 .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                                null,
                                                 ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                                                + " = " + id, null, null);
                  while (phones.moveToNext()) {
                     String phoneNumberX = phones
                             .getString(phones
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                     // Log.i("Number", phoneNumber);
 
                     phoneNumberX = phoneNumberX.replace(" ", "");
                     phoneNumberX = phoneNumberX.replace("(", "");
                     phoneNumberX = phoneNumberX.replace(")", "");
                     if (phoneNumberX.contains(phoneNumber)) {
                             phones.close();
                             return true;
 
                     }
 
                  }
                  phones.close();
              }
 
           }
       }
   } catch (Exception ex) {
        Log.i(TAG, ex.getMessage());
 
   }
 
   return false;
}

Delete an item from contacts:

Java
public static boolean deleteContact(Context ctx,String phoneNumber) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
                               Uri.encode(phoneNumber));
           Cursor cur = ctx.getContentResolver().query(contactUri, null, null,
                           null, null);
           try {
               if (cur.moveToFirst()) {
                   do {
                      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);
                   } while (cur.moveToNext());
               }
 
           } catch (Exception e) {
                   System.out.println(e.getStackTrace());
           }
           return false;
    }
 
}

Using the functions in the Contact Operation Class

Java
ContactOperations.Insert2Contacts(getApplicationContext(),"Yildirim Kocdag", "05321000000");
if (ContactOperations.isTheNumberExistsinContacts(getApplicationContext(), "05321000000")) {
       Log.i(ContactOperations.TAG, "Exists");
} else {
       Log.i(ContactOperations.TAG, "Not Exists");
}

ContactOperations.deleteContact(getApplicationContext(), "05321000000");
if (ContactOperations.isTheNumberExistsinContacts(getApplicationContext(), "05321000000")) {
       Log.i(ContactOperations.TAG, "Exists");
} else {
       Log.i(ContactOperations.TAG, "Not Exists");
}

Do not forget to use appropriate permissions in the AndroidManifest

The Read from Contact and Write to Contact permissions should be inside AndroidManifest.xml.

XML
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)