Click here to Skip to main content
Click here to Skip to main content

Android Contact Operations Insert/Search/Delete

By , 17 Apr 2013
 

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:

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:

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:

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

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.

<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)

About the Author

Yildirim Kocdag
Software Developer (Senior)
Turkey Turkey
Member
Dr. Yildirim Kocdag is a Computer Engineer from Istanbul. Currently using Android, Objective-c, c#, vb.net, asp.net, javascript, SQL and Oracle. His favourite areas in Computer Science are Compilers, Expert Systems, Digital Image Processing, AI and Extreme Programming.
ykocdag@yahoo.com

Comments and Discussions

Comment 1 message has been posted for this article Visit http://www.codeproject.com/Articles/578823/Android-Contact-Operations-Insert-Search-Delete to post and view comments on this article, or click here to get a print view with messages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130513.1 | Last Updated 17 Apr 2013
Article Copyright 2013 by Yildirim Kocdag
Everything else Copyright © CodeProject, 1999-2013
Terms of Use