Protonzz Baba Protonzz Baba - 3 months ago 33
Android Question

How to Store and Retreive only single Row/Value from Realm in Android

I'm working on Realm DB since 6 months, and its pretty good.

But i worked on saving multiple rows/values.


I want to save only single row.


I've tried many approches but didn't get any result and the thing is i'm also not getting any error :(

How to deal with this situation?

Thanks in advanced. :)

Answer

Defining schema:

public class Dog extends RealmObject {
    @PrimaryKey
    private long id;

    @Index
    private String name;

    public long getId() { return this.id; }
    public void setId(long id) { this.id = id; }
    public String getName() { return this.name; }
    public void setName(String name) { this.name = name; }
}

Writing into Realm:

Realm realm = null;
try {
    realm = Realm.getDefaultInstance();
    realm.executeTransaction(new Realm.Transaction() {
        @Override
        public void execute(Realm realm) {
            Dog dog = new Dog();
            dog.setId(1L);
            dog.setName("Fetch");
            realm.insertOrUpdate(dog);
        }
    });
} finally {
    if(realm != null) {
        realm.close();
    }
}

Retrieving from database (sync):

Dog dog = realm.where(Dog.class).equalTo("id", 1L).findFirst();
if(dog != null) {
    // dog
}

Retrieving from database (async on UI thread, 0.84.0+):

private final RealmChangeListener<Dog> listener = new RealmChangeListener<Dog>() {
    @Override
    public void onChange(Dog dog) {
        if(dog.isValid()) {
           // dog
        }
    }
};

Dog dog = realm.where(Dog.class).equalTo("id", 1L).findFirstAsync();
dog.addChangeListener(realmChangeListener);
Comments