jean d'arme jean d'arme - 3 months ago 36
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
Cursor
so...what else?

Answer

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() {
        @Override
        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));
               realmContact.setName(name);
               realmContact.setPhoneNumber(phoneNumber);
               realm.insertOrUpdate(realmContact);
            }
        }
    });
} finally {
    if(realm != null) {
        realm.close();
    }
}