Phan Van Linh Phan Van Linh - 20 days ago 9
Android Question

Realm where with Date return null

Here is my Realm database
enter image description here

Here is my code for find value with where and equalTo, when I use

int
it working, and if I use
Date
it not working.

You will see in the image below,
realmNumber
return value, and
realmDate
return null
enter image description here

realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(final Realm bgRealm) {

StepEntry realmNumber = bgRealm.where(StepEntry.class).equalTo("steps", 0).findFirst();

Date date = stepEntry.getDate();
StepEntry realmDate = bgRealm.where(StepEntry.class).equalTo("date", date).findFirst();
}
});


How can I make
Realm
where work with
Date

Answer

If you cannot find your object with equalTo(field, Date) then that means the Date you provide in the condition does not match.

Realm has milisecond precision since 0.90.0, so your Date must match in terms of hours, minutes, seconds, miliseconds (technically the long epoch time value must be the exact same)

StepEntry realmDate = bgRealm.where(StepEntry.class).equalTo("date", date).findFirst();

If there is an object in the database with the given date (date.getTime() is the same as for the date in the database) then it works.