我想将所有 Realm 操作(读/写)从 Activities/Fragments(在大多数示例中实现)移动到单独的类/类层。
我的问题是,如果不直接在 Activity/Fragment 中使用,我应该何时何地调用 Realm.getInstance() 和 Realm.close()?什么是好的模式?
假设所有操作都可以在 UI 线程中执行,而无需在 AsyncTasks 中执行。
谢谢
最佳答案
你可以像这样把它放在辅助类中:
public class RealmHelper {
private static RealmHelper realmHelper;
private static Realm realm;
public static RealmHelper getInstance(Context context) {
realm = Realm.getInstance(context);
if(realmHelper == null) {
realmHelper = new RealmHelper();
}
return realmHelper;
}
private RealmHelper() {
}
public void saveMy(MyModel my) {
realm.beginTransaction();
realm.copyToRealmOrUpdate(my);
realm.commitTransaction();
}
...
然后在需要的时候调用它:
...
RealmHelper realmHelper = RealmHelper.getInstance(getApplicationContext());
realmHelper.saveMy(my);
...
关于android - 在 Activity 之外调用 Realm.close(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29725805/