Tuesday, August 19, 2014

How to read contacts from phone and sim card in android


Here are the Two function i have implemented one for displaying the sim contacts and one for
phone contacts

1) Display Sim Contacts


private void displaySIMContacts() 

{
   try
   {
      String simPhoneId = null;
      String simPhoneNum = null;
      String simPhoneName = null;
      Uri simUri = Uri.parse("content://icc/adn");
      Cursor simCusor = getContentResolver().query(simUri, null, null, null, null);                                                   while(simCursor.moveToNext())
      {
        simPhoneId = simCursor.getString(simCursor.getColumnIndex("_id");
        simPhoneNum = simCursor.getString(simCursor.getColumnIndex("name");
        simPhoneName = simCursor.getString(simCursor.getColumIndex("number);
        Log.v(TAG, " id = " + simPhoneId + " - name = " + simPhoneName + " - number = " +  simPhoneNumber); 
      }
    } catch (Exception e)
    {
        e.printStackTrace();
    }
}


2) Display All Phone Contacts

private void dispalyPhoneContacts()

{
   Cursor cursor = getContentResolver().query(                                                                                                                         ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);

   while (cursor.moveToNext())
  {
      String name                               =cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.v(TAG, "Name = " + name+ " - number = " +  phoneNumber); 

   }
}


Note:- You need to provide the read contacts permission in android manifest file
<uses-permission android:name="android.permission.READ_CONTACTS"/>

You can call these functions either on button click or as you need.

No comments:

Post a Comment