gpt4 book ai didi

android - 如何管理 Realm 实例?

转载 作者:行者123 更新时间:2023-11-29 16:57:39 27 4
gpt4 key购买 nike

我有一个管理多个 fragment 和嵌套 fragment 的 Activity,就像这样:

Activity -> RootFragment1 -> NestedFragment1、NestedFragment2
-> RootFragment2 -> NestedFragment3、NestedFragment4...

我用来获取一个 Realm 实例并在 onStart、onStop 方法中的每个嵌套 fragment 中关闭它,但有时我会遇到此异常:

Fatal Exception: java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.

是否有推荐的方法来获取 Realm 实例并关闭它?就我而言,我应该在 Activity 中获取一个实例并将其传递给我的 fragment 吗?

最佳答案

文档说您应该在 onCreateView()/onDestroyView() 中打开/关闭 Realm,但根据我的经验, fragment 生命周期异常不稳定,因此我可以向您展示另外两种方法。

1.) 在Activity.onCreate()Activity.onDestroy()中打开/关闭Realm,然后共享到fragments(甚至向下 View 层次结构!)使用 getSystemService()

public class MyActivity extends AppCompatActivity {
Realm realm;

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

@Override
protected void onDestroy() {
realm.close();
realm = null;
// ...
}

// -----------------------------
private static final String REALM_TAG = "__REALM__";

public static Realm getRealm(Context context) {
// noinspection ResourceType
return (Realm)context.getSystemService(REALM_TAG);
}

@Override
public Object getSystemService(@NonNull String name) {
if(REALM_TAG.equals(name)) {
return realm;
}
return super.getSystemService(name);
}
}

然后在 fragment 中你可以做

Realm realm = MyActivity.getRealm(getActivity());

在 View 中你可以做

Realm realm = MyActivity.getRealm(getContext());

2.) 使用保留的 fragment 作为生命周期监听器/Activity 引用计数器,为 UI 线程全局管理 Realm 生命周期。

/**
* Created by Zhuinden on 2016.08.16..
*/
public class RealmManager {
private static final String TAG = "RealmManager";

static Realm realm;

static RealmConfiguration realmConfiguration;

public static void init(Context context) {
Realm.init(context);
}

public static void initializeRealmConfig(Context appContext) {
if(realmConfiguration == null) {
Log.d(TAG, "Initializing Realm configuration.");
setRealmConfiguration(new RealmConfiguration.Builder(appContext).initialData(new RealmInitialData())
.deleteRealmIfMigrationNeeded()
.inMemory()
.build());
}
}

public static void setRealmConfiguration(RealmConfiguration realmConfiguration) {
RealmManager.realmConfiguration = realmConfiguration;
Realm.setDefaultConfiguration(realmConfiguration);
}

private static int activityCount = 0;

public static Realm getRealm() { // use on UI thread only!
return realm;
}

public static void incrementCount() {
if(activityCount == 0) {
if(realm != null) {
if(!realm.isClosed()) {
Log.w(TAG, "Unexpected open Realm found.");
realm.close();
}
}
Log.d(TAG, "Incrementing Activity Count [0]: opening Realm.");
realm = Realm.getDefaultInstance();
}
activityCount++;
Log.d(TAG, "Increment: Count [" + activityCount + "]");
}

public static void decrementCount() {
activityCount--;
Log.d(TAG, "Decrement: Count [" + activityCount + "]");
if(activityCount <= 0) {
Log.d(TAG, "Decrementing Activity Count: closing Realm.");
activityCount = 0;
realm.close();
if(Realm.compactRealm(realmConfiguration)) {
Log.d(TAG, "Realm compacted successfully.");
}
realm = null;
}
}
}

连同

public class RealmScopeListener
extends Fragment {
public RealmScopeListener() {
setRetainInstance(true);
RealmManager.incrementCount();
}

@Override
public void onDestroy() {
RealmManager.decrementCount();
super.onDestroy();
}
}

/**
* Created by Zhuinden on 2016.09.04..
*/
public class RealmActivity extends AppCompatActivity {
protected Realm realm;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
RealmManager.init(this);
RealmManager.initializeRealmConfig(getApplicationContext());

super.onCreate(savedInstanceState);
RealmScopeListener realmScopeListener = (RealmScopeListener)getSupportFragmentManager().findFragmentByTag("SCOPE_LISTENER");
if(realmScopeListener == null) {
realmScopeListener = new RealmScopeListener();
getSupportFragmentManager().beginTransaction().add(realmScopeListener, "SCOPE_LISTENER").commit();
}
realm = RealmManager.getRealm();
}
}

这允许您调用 RealmManager.getRealm() UI 线程,它的生命周期由保留 fragment 管理。

关于android - 如何管理 Realm 实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44331742/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com