- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
上面代码中,realm不能在新的Thread中执行它的事务,没有报错,但是也没有执行。
我已经尝试将事务放在线程之外,问题是它消耗了 UI 线程,但它工作得很好,我想在 Retrofit 和 Realm 工作时向用户显示平滑加载
threadNova = new Thread() {
@Override
public void run() {
super.run();
try {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();
Realm realm = Realm.getDefaultInstance();
realm.executeTransaction(realm1 -> {
//Save things on bank
// No errors but don't enter here either
});
} catch (IOException e) {
e.printStackTrace();
}
}
};
最佳答案
您需要调用 Realm.close()
。
您使用没有循环器的 Java 线程,这意味着您的 Realm 在您调用 Realm.close()
之前不会刷新,因此请在 finally block 中关闭您的 Realm。
try(Realm realm = Realm.getDefaultInstance()) {
Response<Retorno> response = getCall.execute();
final Retorno responsebody = response.body();
realm.executeTransaction(realm1 -> {
//Save
});
} catch (IOException e) {
e.printStackTrace();
}
}
来自文档:
If you obtain a Realm instance from a thread associated with a Looper, the Realm instance comes with an auto-refresh feature. (Android’s UI thread is a Looper.) This means the Realm instance will be periodically updated to the latest version. This lets you keep your UI constantly updated with the latest content with almost no effort!
If you get a Realm instance from a thread that does not have a Looper attached, objects from that instance won’t be updated until you call the waitForChange method. Holding on to an old version of your data is expensive in terms of memory and disk space, and the cost increases with the number of versions between the one being retained and the latest. This is why it is important to close the Realm instance as soon as you are done with it in the thread.
If you want to check whether your Realm instance has auto-refresh activated or not, use the isAutoRefresh method. soon as you are done with it in the thread.
关于android - Realm 无法在新线程中执行 executeTransaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54736819/
我是一名优秀的程序员,十分优秀!