FindFirst returns null

I use Realm to provide a database for my application. But...

After entering the system, the server returns the data, and I create an account (AccountManager) and save this data in the application database, for example (in AsyncTask, of course):

UserRealm userRealm = new UserRealm(); //setter of the userRealm... Realm realm = Realm.getInstance(context); realm.beginTransaction(); realm.copyToRealmOrUpdate(userRealm); realm.commitTransaction(); realm.close(); 

After that, I close LoginActivity and in onResume from MainActivity, I try to load the user like this (in AsyncTask, again ...):

 public static UserRealm getUser(Context context) { try { return Realm.getInstance(context).where(UserRealm.class).findFirst(); } catch (Exception e) { if(DebugUtil.DEBUG) { //enabled e.printStackTrace(); } } return null; } 

But this returns null, I do not know what is happening to it.

UserRealm: https://gist.github.com/ppamorim/88f2553a6ff990876bc6

+2
source share
1 answer

AsyncTask is located in threadpool and, given that you open Realm instances that you never close with your getUser() call, your version of Realm becomes locked in the version the first time getUser() called.

return Realm.getInstance(context) where (UserRealm.class) .findFirst (); // never closes

Thus, even if you make a transaction in another thread in threadpool, not all threads will be updated (since you blocked them on the old version by opening Realm instances that never close), and sometimes the object will be zero.

Solution, close all Realm instances in the background thread (or force update if for some reason this is not enough).

+1
source

All Articles