Search code examples
androiddatabasesqlitedatatablescontacts

How to get Contacts in a Table in Android using SQLite?


I want to get the contacts stored on the phone into a table created in my SQLite db. The columns show the different fields e.g Name, phone number, email etc and each row shows a different contact. How do I achieve this?


Solution

  • Use androids content provider to get contacts data as a cursor and then iterate cursor rows and save data to sqlite

    First add permission:-

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

    Then in java class:-

    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
    while (phones.moveToNext())
    {
      String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
      String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
    
    }
    phones.close();
    

    In while loop add to your sqlite data base