- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在 Application 对象上使用一个静态全局 Realm 实例(从未关闭),仅用于 UI 线程,
@UiThread
public static Realm getRealm() {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
return realmInstance;
} else {
Timber.e("Illegal access to getRealmObservable");
throw new IllegalStateException("Only UI Thread can access this realm");
}
}
和 WorkerThread 的另一个单一使用 Realm 如下:
@WorkerThread
public static void executeOnSingleUseRealm(final Realm.Transaction transaction) {
if (Thread.currentThread() == Looper.getMainLooper().getThread()) {
Timber.e("Wrong thread for Realm");
throw new IllegalStateException("Wrong thread for Single use Realm");
}
Realm realm = null;
try {
realm = Realm.getDefaultInstance();
realm.executeTransaction(transaction);
} catch (Exception e) {
Timber.e(e, "Exception in Single Use Realm transaction");
throw e;
} finally {
if (realm != null) {
realm.close();
}
}
}
但是我仍然看到在使用单个全局 Realm 实例时发生崩溃:This Realm instance has already been closed, making it unusable.
我什至不知道这怎么可能。
下面是我如何初始化 Realm 实例:
创建时的应用
void onCreate(){
....
Observable
.fromCallable(() -> {
Realm.init(SVApplication.this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.build();
Realm.compactRealm(realmConfiguration);
Realm.setDefaultConfiguration(realmConfiguration);
return true;
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((v) -> onRealmLoaded());
}
}
void onRealmLoaded(){
realmInstance = Realm.getDefaultInstance();
....
}
这是其中一项 Activity 的崩溃之一:
void onStart(){
.... subscribeUntilDetach(realmInstance.where(Notification.class).findAllAsync().asObservable()
.onBackpressureLatest()
.switchIfEmpty(emptyNotification())
.map(notifications -> notifications.where().isNull("readTime").or().isEmpty("readTime").count())
.onBackpressureLatest()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(count -> {
if (count == 0L) {
mNotificationBadge.setVisibility(View.GONE);
} else {
mNotificationBadge.setText(String.format(Locale.getDefault(), "%d", count));
mNotificationBadge.setVisibility(View.VISIBLE);
}
}, throwable -> Timber.e(throwable, "Error setting notification count")));
}
@Override
protected void onPause() {
super.onPause();
if (isFinishing()) {
mCompositeSubscription.clear();
}
}
protected void subscribeUntilDetach(@NonNull Subscription subscription) {
mCompositeSubscription.add(subscription);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mCompositeSubscription.hasSubscriptions()) {
mCompositeSubscription.unsubscribe();
}
}
在某些 Activity 中,这条线也会因同样的错误而崩溃:
mCompositeSubscription.unsubscribe();
这是来自 Crashlytics 的堆栈跟踪,可能不完全准确。
Fatal Exception: java.lang.RuntimeException: Unable to resume activity {com.myapp.mobile/com.teknoloji.myapp.ui.pages.HomeActivity}: rx.b.f: This Realm instance has already been closed, making it unusable.
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3353)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by rx.b.f: This Realm instance has already been closed, making it unusable.
at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(Unknown Source)
at rx.internal.util.InternalObservableUtils$ErrorNotImplementedAction.call(Unknown Source)
at rx.internal.util.ActionSubscriber.onError(Unknown Source)
at rx.observers.SafeSubscriber._onError(Unknown Source)
at rx.observers.SafeSubscriber.onError(Unknown Source)
at rx.exceptions.Exceptions.propagate(Unknown Source)
at rx.observers.SafeSubscriber.onNext(Unknown Source)
at rx.internal.producers.SingleProducer.request(Unknown Source)
at rx.Subscriber.setProducer(Unknown Source)
at rx.Subscriber.setProducer(Unknown Source)
at rx.internal.operators.OperatorSingle$ParentSubscriber.onCompleted(Unknown Source)
at rx.internal.operators.OperatorTake$1.onNext(Unknown Source)
at rx.internal.operators.NotificationLite.next(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.accept(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitFirst(Unknown Source)
at rx.subjects.BehaviorSubject$1.call(Unknown Source)
at rx.subjects.BehaviorSubject$1.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.Observable.create(Unknown Source)
at rx.Observable.unsafeCreate(Unknown Source)
at rx.Observable.create(Unknown Source)
at com.teknoloji.myapp.ui.pages.HomeActivity.onStart(Unknown Source)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1288)
at android.app.Activity.performStart(Activity.java:6279)
at android.app.Activity.performRestart(Activity.java:6325)
at android.app.Activity.performResume(Activity.java:6330)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by java.lang.IllegalStateException: This Realm instance has already been closed, making it unusable.
at io.realm.BaseRealm.checkIfValid(Unknown Source)
at io.realm.Realm.init(Unknown Source)
at com.teknoloji.myapp.ui.pages.HomeActivity.lambda$onStart$3(Unknown Source)
at com.teknoloji.myapp.ui.pages.HomeActivity$$Lambda$1.call(Unknown Source)
at rx.internal.util.ActionSubscriber.onNext(Unknown Source)
at rx.observers.SafeSubscriber.onNext(Unknown Source)
at rx.internal.producers.SingleProducer.request(Unknown Source)
at rx.Subscriber.setProducer(Unknown Source)
at rx.Subscriber.setProducer(Unknown Source)
at rx.internal.operators.OperatorSingle$ParentSubscriber.onCompleted(Unknown Source)
at rx.internal.operators.OperatorTake$1.onNext(Unknown Source)
at rx.internal.operators.NotificationLite.next(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.accept(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitNext(Unknown Source)
at rx.subjects.SubjectSubscriptionManager$SubjectObserver.emitFirst(Unknown Source)
at rx.subjects.BehaviorSubject$1.call(Unknown Source)
at rx.subjects.BehaviorSubject$1.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.subjects.SubjectSubscriptionManager.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.internal.operators.OnSubscribeLift.call(Unknown Source)
at rx.Observable.create(Unknown Source)
at rx.Observable.unsafeCreate(Unknown Source)
at rx.Observable.create(Unknown Source)
at com.teknoloji.myapp.ui.pages.HomeActivity.onStart(Unknown Source)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1288)
at android.app.Activity.performStart(Activity.java:6279)
at android.app.Activity.performRestart(Activity.java:6325)
at android.app.Activity.performResume(Activity.java:6330)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3336)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3384)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1443)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
最佳答案
问题是:
A closed exception indicates that you're attempting to use a closed realm, utilizing Realm in a way that would not be promoted as the best practice. ... Each activity is supposed to have its own realm instance for best performance. ... create a realm instance at onCreate() and destroy the instance at onDestory(). https://github.com/realm/realm-java/issues/2594#issuecomment-211793848
此外
...it is not a good idea that keep a static field of Realm in the class. It is recommended to control the Realm's life cycle within the Activity/Fragment/etc https://realm.io/docs/java/latest/#controlling-the-lifecycle-of-realm-instances
因为在 Realm 中创建新实例,当至少有一个打开时,速度非常快,不要害怕创建多个 Realm 实例。
Realm 的一位高级软件工程师指出 here :
As long as you have at least one instance open on a thread calling Realm.getInstance() it is just a HashMap lookup... Best practise is to keep the Realm instance open for as long as your thread lives.
最佳实践在 Realm documentation 中有所描述。 :
// Setup Realm in your Application
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder().build();
Realm.setDefaultConfiguration(realmConfiguration);
}
}
// onCreate()/onDestroy() overlap when switching between activities.
// Activity2.onCreate() will be called before Activity1.onDestroy()
// so the call to getDefaultInstance in Activity2 will be fast.
public class MyActivity extends Activity {
private Realm realm;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
// ...
}
@Override
protected void onDestroy() {
super.onDestroy();
realm.close();
}
}
对于工作线程,documentation recommends在开始时获取一个新的 Realm 实例并在结束时关闭它。
protected Void doInBackground(Void... params) {
Realm realm = Realm.getDefaultInstance();
try {
// ... Use the Realm instance ...
} finally {
realm.close();
}
return null;
}
关于android - Realm 自行关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43619625/
目前有没有办法允许多个用户访问同一个 Realm? 现在我能找到的唯一方法是使用“应用程序帐户”而不是用户帐户,如 another question 中所建议的那样。 . 谢谢! 最佳答案 通常,您可
我有一个在 Ubuntu 服务器上运行的 Realm Object Server (v. 1.0)。我是否应该能够通过 Realm Browser 连接到它?应用程序? 这是我尝试过的。 文件 > 打
我正在使用 React-Native。在此我指的是 this在 React-Native 中使用 Realm 数据库的文档。我可以创建 react-native 数据库,但无法在 Realm-Stud
我想使用 Realm Mobile Platform 为我的应用程序提供同步,但不强制用户注册或登录。也就是说,我想先使用本地 Realm,然后切换到同步 Realm,如果用户决定使用该功能。 这可能
在主线程上写入 Realm 可以吗? 基本上,我想在开始 ActivityA 之前将一些 ObjectA 写入 Realm。 ActivityA 启动后,它需要立即访问(在 onCreate 中)Ob
表格大小有限制吗?我需要平均每秒添加一次新数据。我正在从蓝牙设备保存信息,因此每秒都会收到应用程序处于前台/后台的更新。 谢谢 最佳答案 Realm 使用内存映射来访问文件。根据操作系统的不同,每个进
假设有两个表 Box 和 Item。盒子里可能有很多元素,一件元素只有一个盒子。我想获取给定数组中包含盒子的所有项目。我怎么能这么做呢?在 CD 中,我将通过 Item 类中的谓词和属性来完成此操作,
我正在使用 realm-js 通过 React Native 为用户在他们的设备上存储数据,并且在工作流中有一点我想复制本地 Realm 中的所有数据进入同步 Realm (在 ROS 上持久化)。我
是否可以在不同用户之间共享同一个对象?这样,即使他们拥有自己的私有(private)对象,他们也可以在其中一些对象上进行共享/协作。我该怎么做? 最佳答案 来自 Realm 的 Katsumi。 Re
在Realm中有两种写事务的方式,它们有什么区别? 1. try! realm.write { ... } 2. realm.beginWrite() ... try! realm.commitW
我需要向 Realm 写入大量数据(例如 200000 输入),我使用 realm.add() 在后台线程中写入数据。但它收到了崩溃消息: Terminating app due to uncaugh
在 iOS 上,可以检查 Realm 的内容通过使用 Realm Browser 打开相应的文件来数据库.可以使用以下代码行打印该文件的路径(如 here 所述): print(Realm.Confi
realm.io 数据库是否支持多列索引或排序索引? documentation没有提到这些功能,但这似乎很奇怪,因为 Realm 被宣传为核心数据的替代品。 最佳答案 是的! Realm 允许您在单
我们在 AWS ECS 中运行 Keycloak docker 镜像,我们需要一种使用 ansible 导出 Realm 和所有用户以实现自动化目的的方法。我们可以使用 ansible 运行以下命令来
我正在考虑将新的 Realm 移动平台用于我的一个项目。我已经阅读了指南,并且能够在本地启动并运行它没有问题。我的问题是,部署 Realm 对象服务器以便远程运行的最佳方式是什么?我通读了找到的指南
我想在我的 Realm 数据库中使用已经预填充的数据来交付我的应用程序。我是否必须简单地将它复制到文档目录中,或者还有其他事情要做吗? 最佳答案 Realm 的文档中有一节关于 "Bundling a
我已按 Realm 创建了数据库,但无法找到该文件,因为我的操作系统(Yosemite)在/private/var/mobile 中没有移动文件夹。 我应该如何访问我的 Realm 以在浏览器中运行?
我有两个 Realm : public class ChatRealm extends RealmObject { private String id; private RealmLi
像上图一样,我想将RealmObject重命名为WeekRealmObject,这样命名更清晰。我尝试搜索 Stackoverflow 并检查 Realm Swift 文档及其示例,但似乎只能通过迁移
我通过 SyncCredentials 登录 Realm 允许创建用户,代码如下: SyncCredentials credentials = SyncCredentials.usernamePass
我是一名优秀的程序员,十分优秀!