Saturday, 16 May 2015

Android Import Mobile ContactsTo Database


Add the below function to your Activity Class

public String importAllcontacts() 
{
   JSONObject object = new JSONObject();
   ContentResolver cr = getContentResolver();
   Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
   String phone = null;
   String name = null;
    if (cur .getCount() > 0) {
    while (cur.moveToNext()) {
    String idcur.getString(cur 
.getColumnIndex(ContactsContract.Contacts._ID));
    Cursor pCur 
      cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
      ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = ?", new String[] { id }, null);
      while (pCur.moveToNext()) 
         {
            phone pCur.getString(pCur.getColumnIndex
                       (ContactsContract.CommonDataKinds.Phone.NUMBER));
            name  = pCur.getString(pCur.getColumnIndex
                    (ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
try  {

object.put("PhoneNo", phone);
object.put("DISPLAY_NAME", name);
         } 
               catch (JSONException e) 
                        
            {

e.printStackTrace();
}
}
      pCur.close();
       Cursor emailCur;

   emailCur= ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, 
   ContactsContract.CommonDataKinds.Email.CONTACT_ID
+ " = ?", new String[] { id }, null);
   while (emailCur.moveToNext()) 
         {
        String emailContact emailCur.getString(emailCur 
.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
          try {

object.put("emailContact", emailContact);

} catch (JSONException e) {

e.printStackTrace();
}
}
 emailCur.close();
}                              

}
return object.toString();
}


Add these permissions to your Manifest file


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

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