当领域关闭时,领域对象不可访问。 Android的

时间:2016-11-06 18:32:56

标签: android realm

我正在使用Realm for Android。

我有问题(不是一个大问题),我有这行代码:

Account account;
....
realm = Realm.getDefaultInstance();
account = realm.where(Account.class).findFirst();
realm.close();
if (account.getJid().equals(mUser.getText().toString())) { // User is the same as logged before
    launchLogin(mUser.getText().toString().split("@")[0],mPassword.getText().toString());

}

如果我启动应用程序,当执行到达IF语句时,它会崩溃,因为account对象确实存在。即使在db中存在帐户。 但是如果在IF内部移动realm.close(),则在启动登录(..)之后,它可以工作。

我所理解的是该帐户" dissapears"当我关闭领域db。我将来会遇到真正的问题。

所以我想知道如何制作"执着"这类问题。我的意思是,在查询之后关闭领域并且对象在它之后仍然存在。

3 个答案:

答案 0 :(得分:2)

只能从未关闭的Realm实例访问托管的RealmObject实例。

Following the official documentation, you should have an open instance for the UI thread bound to the lifecycle of the application itself.

来自文档:

// onCreate()/onDestroy() overlap when switching between activities so onCreate()
// on Activity 2 will be called before onDestroy() on Activity 1.

public class MyActivity extends Activity {
    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        realm = Realm.getDefaultInstance();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close();
    }
}

// Use onCreateView()/onDestroyView() for Fragments as onDestroy() might not be called.
public class MyFragment extends Fragment {
    private Realm realm;

    @Override
    public void onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        realm = Realm.getDefaultInstance();
        View view = inflater.inflate(R.layout.my_fragment, parent, false);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        realm.close();
    }
}

对于后台线程:

// Run a non-Looper thread with a Realm instance.
Thread thread = new Thread(new Runnable() {
    @Override
    public void run() {
        Realm realm = null;
        try {
            realm = Realm.getDefaultInstance();
            // ... Use the Realm instance ...
        } finally {
            if (realm != null) {
                realm.close();
            }
        }
    }
});

thread.start();

遵循文档,您提到的问题不会发生。

答案 1 :(得分:2)

除了EpicPandaForces的答案,如果你真的想关闭这个领域并放弃Realm提供的任何自动更新优势,你可以使用RealmObject

创建realm.copyFromRealm(realmObject);的非托管副本

答案 2 :(得分:0)

你应该在后台线程的开头打开Realm实例,在后台线程的执行结束时关闭它,

try {
    realm = Realm.getDefaultInstance();
    account = realm.where(Account.class).findFirst();

    if (account.getJid().equals(mUser.getText().toString())) { // User is the same as logged before
        launchLogin(mUser.getText().toString().split("@")[0],mPassword.getText().toString());

    } 
} finally {
     if(realm != null) {
          realm.close(); // important 
     } 
}