当它是同一个线程时,领域从错误的线程Android错误访问

时间:2017-04-06 13:51:25

标签: android multithreading event-handling realm

我一直在:

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部分中,我正常引用了realm对象。

1 个答案:

答案 0 :(得分:0)

我将线程更改为:

    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();

现在它有效。