Realm query sometimes returning no data
Goal
Query and load a list of objects in a RecyclerView.
Expected Results
The database is already populated with data, so the expected result is the list with several objects in it when opening the Activity.
Actual Results
We get no exceptions, what happens is that most of the times the query returns the list with the objects in it, but sometimes the query returns an empty list. We are not performing any write operation at that time, the data was saved in the database long time ago. When this strange error happens and the list is show as empty, going back to the previous activity and re opening the one of the list fixes the problem. We are wondering if the AsyncTask could have something to do with this.
Another important thing is that on my debugging I was able to log some data and noticed that when the error happens performing a count returns 0 instead of 1 for example. But when going back and opening the list again will return count 1 as expected.
This does not happen frequently, I mean I can for example open the list 20 times successfully and the 21 attempt loads and empty list.
Steps & Code to Reproduce
What we do is simple, open a new Activity that should query the Realm database and populate a RecyclerView with data. The query is done by an Interactor class that is used by the Presenter (we are using an MVP structure), which task is only load the list of objects in background using an Android AsyncTask, as follows:
@Override
public void loadCustomWorkoutsFromDatabase(OnCustomWorkoutsLoaderListener onCustomWorkoutsLoaderListener) {
try {
mOnCustomWorkoutsLoaderListener = onCustomWorkoutsLoaderListener;
new GetCustomWorkoutsTask().execute();
} catch (RealmException realmExecption){
onCustomWorkoutsLoaderListener.onWorkoutsLoadingError();
}
}
private class GetCustomWorkoutsTask extends AsyncTask<Void , Void, ArrayList<Routine>> {
protected ArrayList<Routine> doInBackground(Void... params) {
return getCustomWorkouts();
}
protected void onPostExecute(ArrayList<Routine> customWorkoutsList) {
if(customWorkoutsList != null)
mOnCustomWorkoutsLoaderListener.onWorkoutsLoadedSuccessfully(customWorkoutsList);
else
mOnCustomWorkoutsLoaderListener.onWorkoutsLoadingError();
}
}
private ArrayList<Routine> getCustomWorkouts(){
List<Routine> routineList = mRoutineRepository.query(new FindAllNotDefaultRoutinesSpecification());
return new ArrayList<>(routineList);
}
We are also using a Repository pattern, so the query is done as follows:
@Override
public List<Routine> query(Specification specification) {
final RealmRoutineSpecification.MultipleResults realmSpecification = (RealmRoutineSpecification.MultipleResults) specification;
final Realm realm = Realm.getInstance(mRealmConfiguration);
final RealmResults<RealmRoutine> realmResults = realmSpecification.toMultipleResults(realm);
final List<Routine> routinesList = new ArrayList<>();
for(RealmRoutine realmRoutine : realmResults){
routinesList.add(mRealmRoutineToRoutineMapper.map(realmRoutine));
}
realm.close();
return routinesList;
}
And the actual query Specification is done follows:
public class FindAllNotDefaultRoutinesSpecification implements RealmRoutineSpecification.MultipleResults {
@Override
public RealmResults<RealmRoutine> toMultipleResults(Realm realm) {
RealmResults<RealmRoutine> realmResults = realm.where(RealmRoutine.class).equalTo(RealmRoutine.Fields.IS_DEFAULT, false).findAll();
return realmResults.sort(RealmRoutine.Fields.SORT);
}
}
Version of Realm and tooling
Realm version(s): 2.2.0
Realm sync feature enabled: yes/no
Android Studio version: 2.2.2
Which Android version and device: Android 6, Galaxy S6 and others.
AsyncTasks run in a threadpool, so if multiple queries are executed alongtime each other (for example a query is started while a transaction is currently open elsewhere which finishes only after Realm.getDefaultInstance() is called), then your Realm could get retained to a previous version.
Realm is guaranteed to be up-to-date on the UI thread, and RealmChangeListeners are notified whenever changes occur. Executing queries on background threads inside thread pools that create unmanaged lists that are passed across threads can result in inconsistency, as you can see.
Therefore, the core problem here is the faulty abstraction of Realm using a Repository pattern designed for raw SQLite, cutting off Realm's auto-updates and reactivity.
As for the workaround, just call RealmRefresh.refreshRealm(realm) after Realm.getDefaultInstance() as per http://stackoverflow.com/a/38839808/2413303
I see, then should I need to create the class RealmRefresh? I was trying to copy the class from the link you provided and I am getting an error with this line:
realm.handlerController.handleMessage(message);
The error is that 'io.Realm.BaseRealm' is not public in 'io.realm' and cannot be accessed from outside package.
yeah, the package must be io.realm
Understood, I am going to test.
So, your recommendation is avoid using a repository pattern when using realm?
Thanks for the quick answers.
your recommendation is avoid using a repository pattern
Not the Repository pattern per say, the real issue is the mapping to unmanaged objects with which you pass them from background thread to UI thread.
Repository pattern should allow returning either ObservableList with RealmResults wrapped on the UI thread in a callback, or (for SQLite) an ObservableList with a result set, from a background thread, with SqlBrite handling the reactivity.
Like this article says, you're supposed to let Realm have both the data layer, and the reactive notifications for said data layer. Using it as a non-reactive database is a suboptimal solution.
@Dansanchez I'm closing the issue and I hope @Zhuinden's many suggestions have help you. Don't hesitate to reopen or create new issue if you have further questions.
@Dansanchez you can follow following example to create Repository that reactively listens to RealmResults on background looper thread
@Zhuinden That link doesn't work
Because the sample was renamed and is in https://github.com/Zhuinden/simple-stack/blob/master/simple-stack-example-mvp-fragments/src/main/java/com/zhuinden/simplestackdemoexamplefragments/data/repository/TaskRepository.java , but https://github.com/Zhuinden/realm-monarchy also provides this functionality while being a better wrapper.
I don't understand how it solves the problem. It is sending Optional instead of the empty list. I am talking about line 136
Yeah I do think sending a Single in general is a mistake.
This solves problem for me:
return Single.create( e -> {
ArrayList
RxJavaInterop.toV2Observable(realm.where(CollectionModel.class)
.findAllAsync()
.asObservable())
.take(10)
.filter(RealmResults::isLoaded)
.subscribe(collectionModels -> {
arrayList.addAll(collectionModels);
e.onSuccess(arrayList);
});
});
returning null plz help me out
RealmQuery
I don't know where realmSuperInstance is initialized and I don't know what thread this is on, so I. Can't know
Hey thanks for reply and this is from activity main thread and realmSuperInstance is initialized In oncreate method
Thanks and Regards , Ashish Chaugule, 9096832006.
On Jan 25, 2018 12:06 AM, "Gabor Varadi" [email protected] wrote:
I don't know where realmSuperInstance is initialized and I don't know what thread this is on, so I. Can't know
— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/realm/realm-java/issues/3932#issuecomment-360230808, or mute the thread https://github.com/notifications/unsubscribe-auth/AP_qumITZJGfW7R2EpxNTdcLhDE9kSd7ks5tN3gbgaJpZM4LR7b_ .
@AshishChagugule then it's only possible for it to not be there if it's not in the Realm.
Unless you wrote to Realm on a background thread in doInBackground() of an AsyncTask, then did a finish() in onPostExecute(), and navigated back before the UI thread was notified that the background thread write occurred.
It will very helpfull to me if you look in this two attach file and help me out
android code
i am getting null on mRound
RealmQuery
Thanks and Regards , Ashish Chaugule, 9096832006.
On Jan 25, 2018 1:10 AM, "Gabor Varadi" [email protected] wrote:
@AshishChagugule https://github.com/ashishchagugule then it's only possible for it to not be there if it's not in the Realm.
Unless you wrote to Realm on a background thread in doInBackground() of an AsyncTask, then did a finish() in onPostExecute(), and navigated back before the UI thread was notified that the background thread write occurred.
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/realm/realm-java/issues/3932#issuecomment-360249661, or mute the thread https://github.com/notifications/unsubscribe-auth/AP_quhRAu4gIWFu7GqXf_qxZ8dPPdv6oks5tN4cggaJpZM4LR7b_ .
You could use findFirst() and check if != null
Yes we have added the same code to check null on the incoming object but we are getting null after our app gets crashed for some reasons. We are not getting how to solve the problem.
Thanks and Regards , Ashish Chaugule, 9096832006.
On Jan 25, 2018 7:11 PM, "Gabor Varadi" [email protected] wrote:
You could use findFirst() and check if != null
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/realm/realm-java/issues/3932#issuecomment-360469402, or mute the thread https://github.com/notifications/unsubscribe-auth/AP_quiGBG0lb2pZpxBIQgDksbjth-HWMks5tOISSgaJpZM4LR7b_ .
Without an exception stack trace and complete relevant code, there isn't much I can do
but you can ask for some help at help[at]realm.io