Click here to Skip to main content
15,884,838 members
Articles / Programming Languages / Java

Android Contact Operations Insert/Search/Delete

Rate me:
Please Sign up or sign in to vote.
4.67/5 (3 votes)
17 Apr 2013CPOL 57.5K   4.4K   11   9
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)


Written By
Architect
Turkey Turkey
Phd. Yildirim Kocdag is a Computer Engineer.

Programming Languages
Android, Objective-c, c#, vb.net, asp.net, javascript, TSQL.

Computer Science
DataMining, Compilers, Expert Systems, Digital Image Processing, AI and Extreme Programming.

ykocdag@yahoo.com

http://www.linkedin.com/profile/view?id=223886830

Comments and Discussions

 
QuestionHow to compile / generate runnable command? Pin
Member 1328714730-Jun-17 7:26
Member 1328714730-Jun-17 7:26 
AnswerRe: How to compile / generate runnable command? Pin
Yildirim Kocdag15-Jan-19 19:45
Yildirim Kocdag15-Jan-19 19:45 
QuestionNO GUI Pin
evans cr77-Apr-14 18:51
evans cr77-Apr-14 18:51 
AnswerRe: NO GUI Pin
Yildirim Kocdag8-Apr-14 4:35
Yildirim Kocdag8-Apr-14 4:35 
GeneralRe: NO GUI Pin
evans cr79-Apr-14 20:31
evans cr79-Apr-14 20:31 
Questionwhy is not i can't insert ? Pin
Member 103173545-Oct-13 6:37
Member 103173545-Oct-13 6:37 
AnswerRe: why is not i can't insert ? Pin
Yildirim Kocdag11-Oct-13 0:31
Yildirim Kocdag11-Oct-13 0:31 
GeneralRe: why is not i can't insert ? Pin
Member 1031735412-Oct-13 4:32
Member 1031735412-Oct-13 4:32 
GeneralMy vote of 4 Pin
Sudhakar Shinde22-Apr-13 19:24
Sudhakar Shinde22-Apr-13 19:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.