I'm working on Realm DB.
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?
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 RealmResults<Dog> dogs;
private final RealmChangeListener<Dog> listener = new RealmChangeListener<Dog>() {
@Override
public void onChange(RealmResults<Dog> dogs) {
if(dogs.isValid()) {
if(dogs.isEmpty()) {
// dog does not exist
} else {
Dog dog = dogs.get(0);
// dog exists
}
}
}
};
dogs = realm.where(Dog.class).equalTo("id", 1L).findAllAsync();
dog.addChangeListener(realmChangeListener);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With