jean d'arme jean d'arme - 1 year ago 155
Android Question

How to read contacts in Android using Realm?

I can't find any solutions to read contacts from Android and save them in Realm. Anyone done that before?

I know that I will have to use

Contacts Provider
, but this is all I know. AFAIK, Realm doesn't support
so...what else?

Answer Source

Create RealmObject, read the data from content provider, save data to RealmObject, save data in Realm:

// background thread
Realm realm = null;
try {
    realm = Realm.getDefaultInstance();
    realm.executeTransaction(new Realm.Transaction() {
        public void execute(Realm realm) {
            RealmContact realmContact = new RealmContact();
            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));
} finally {
    if(realm != null) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download