【问题标题】:Realm access from incorrect thread Android Error when it is the same thread当它是同一个线程时,从错误的线程Android错误的领域访问
【发布时间】:2017-09-01 14:31:00
【问题描述】:

我不断得到:

java.lang.IllegalStateException: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.

但是线程在它甚至触及领域对象时就被中断了,我有什么办法解决这个问题吗?

    RealmConfiguration config = new RealmConfiguration.Builder()
            .name("CustomSchedule.realm")
            .schemaVersion(42)
            .build();
    mRealm = Realm.getInstance(config);

    mDays = app.getmDays();

    final Handler handler = new Handler();

    t = new Thread(new Runnable() {
        public void run() {
            while(!Thread.currentThread().isInterrupted()) {
                while (mDays.isEmpty()) {
                }
                Thread.currentThread().interrupt();
                startActivity();
                handler.post(this);
            }
        }
    });
    t.start();

    return rootView;
}

在 startActivity 部分中,我照常引用领域对象。

【问题讨论】:

    标签: android multithreading event-handling realm


    【解决方案1】:

    我将主题更改为:

        final Handler handler = new Handler();
    
        final Thread t = new Thread(new Runnable() {
            public void run() {
                while(!Thread.currentThread().isInterrupted()) {
                    while (mDays.isEmpty()) {
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            startActivity();
                        }
                    });
                    Thread.currentThread().interrupt();
                }
            }
        });
        t.start();
    

    现在它可以工作了。

    【讨论】:

      猜你喜欢
      • 2017-03-22
      • 2020-09-29
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多