【问题标题】:Realm in IntentService - thread created crashIntentService 中的领域 - 线程创建崩溃
【发布时间】: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,因为它不是(显然)从同一个实例中查询的。

这对我们的代码至关重要,所以我有点难过。提前感谢您的任何建议!

【问题讨论】:

    标签: android realm


    【解决方案1】:

    这是因为 IntentService 在后台线程上运行,但您的 api 回调尝试在 UI 线程上运行,这意味着它与您的 RealmResults 所属的 Realm 实例所在的线程不同。

    另外,无论如何,您都将在 UI 线程上写入领域,这是不鼓励的。

    IntentService 中使用同步 API 调用。在 Retrofit 中,它是call.execute()

    我也希望你在 finally 块中关闭 Realm 实例!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多