【发布时间】:2017-06-04 18:00:35
【问题描述】:
我有一个 Realm 线程导致崩溃,我不确定为什么不允许这样做,或者如何解决它。下面是一些示例代码:
public class UploadPostService extends IntentService {
public UploadPostService() {
super("UploadPostService");
}
@Override
protected void onHandleIntent(Intent intent) {
String uniqueCode = intent.getStringExtra("uniqueCode");
OurApi api = OurApi.build(this, Application.apiRoot);
final Realm r = Realm.getDefaultInstance();
final RealmResults<Post> thePosts = r.where(Post.class)
.equalTo("post.code", uniqueCode)
.findAll();
if (thePosts != null && thePosts.size() > 0) {
for (final Post post : thePosts) {
api.uploadMedia(paramsToUpload, new Callback<Post>() {
@Override
public void success(Post postResponse, Response response) {
if (post.isValid()) {
r.beginTransaction();
post.setAField(blah); // CRASHES HERE
r.commitTransaction();
}
}
}
etc...
API 完成 Retrofit 调用后,它会在设置“Post”对象上的任何字段时崩溃,但以下情况除外:
"java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created."
我很好奇最干净的解决方案应该是什么?假设回调位于与 IntentService 不同的线程上。我需要更新实际的 Post,但它不允许我这样做;我尝试创建单独的 Realm 实例,但它不允许我更新 Post,因为它不是(显然)从同一个实例中查询的。
这对我们的代码至关重要,所以我有点难过。提前感谢您的任何建议!
【问题讨论】: