FindFirst返回null [英] FindFirst returns null

查看:742
本文介绍了FindFirst返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Realm为我的应用程序提供数据库.但是...

I'm using Realm to provide the database for my application. But...

登录后,服务器返回数据,我创建了(AccountManager的)帐户,并将这些数据保存在应用程序的数据库中,就像这样(当然是在AsyncTask上):

After login, the server returns the data and I create the account (of AccountManager) and save these datas at the database of the application, like this (at an 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();

之后,我关闭LoginActivity并在MainActivity的onResume上,尝试像这样加载用户(再次在AsyncTask上...):

After, I close the LoginActivity and at the onResume of the MainActivity, I try to load the user, like this(at an 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;
}

但这返回null,我不知道会发生什么.

But this returns null, I don't know what happens with it.

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

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

推荐答案

AsyncTask在线程池中,并且考虑到您打开了从未通过getUser()调用关闭的Realm实例,因此您的Realm版本被锁定为该版本首先叫getUser().

AsyncTask is in a threadpool, and considering you open Realm instances that you never close with your getUser() call, your Realm version becomes locked at the version when you first called getUser().

return Realm.getInstance(context) .where(UserRealm.class).findFirst(); //从未关闭

因此,即使您在线程池中的另一个线程上提交事务,也不是所有线程都是最新的(因为您通过打开从未关闭的Realm实例将它们锁定在旧版本上),有时该对象将是最新的.空.

So even though you commit a transaction on another thread in the threadpool, not all threads will be up to date (because you locked them on an old version by opening Realm instances that are never closed), and sometimes the object will be null.

解决方案,关闭后台线程上的所有Realm实例(或由于某种原因而强制进行更新).

Solution, close all Realm instances on background threads (or force an update if that's not enough for some reason).

这篇关于FindFirst返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆