转载

java – 从不正确的线程Android访问Realm

我在 Android

上处理这个问题:

领域从错误的线程访问. Realm对象只能在创建它们的线程上访问.

我想在我的RemoteViewsFactory中使用Realm

public class RemoteViewsX implements RemoteViewsFactory {

    public RemoteViews getViewAt(int paramInt) {
    if (this.results != null && this.results.size() != 0 && this.results.get(paramInt) != null) {
    //FAILED HERE
    }

}

这次通话失败了!为什么?

我在班上取这样的数据:

public void onDataSetChanged() {
        Realm realm = Realm.getInstance(RemoteViewsX.this.ctx);
        this.results =  realm.where(Model.class).findAll();
}

我这样调用了我的remoteFactory:

public class ScrollWidgetService extends RemoteViewsService {
    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new RemoteViewsX (getApplicationContext());
    }
}

任何的想法 ?

如果问题是由另一个线程调用onDataSetChanged和getViewAt引起的,那么可以强制它们使用相同的线程,创建自己的HandlerThread,如下所示:
public class Lock {
    private boolean isLocked;

    public synchronized void lock() throws InterruptedException {
        isLocked = true;
        while (isLocked) {
            wait();
        }
    }

    public synchronized void unlock() {
        isLocked = false;
        notify();
    }
}

public class MyHandlerThread extends HandlerThread {
    private Handler mHandler;

    public MyHandlerThread() {
        super("MY_HANDLER_THREAD");
        start();
        mHandler = new Handler(getLooper());
    }

    public Handler getHandler() {
        return mHandler;
    }
}

public class RemoteViewsX implements RemoteViewsFactory {
    private MyHandlerThread mHandlerThread;
    ...
}

public void onDataSetChanged() {
    Lock lock = new Lock();
    mHandlerThread.getHandler().post(new Runnable() {
        @Override
        public void run() {
            Realm realm = Realm.getInstance(ctx);
            results = realm.where(Model.class).findAll();
            lock.unlock();
        }
    });
    lock.lock();
}

public RemoteViews getViewAt(int paramInt) {
    Lock lock = new Lock();
    final RemoteViews[] result = {null};
    mHandlerThread.getHandler().post(new Runnable() {
        @Override
        public void run() {
            // You can safely access results here.
            result[0] = new RemoteViews();
            lock.unlock();
        }
    });
    lock.lock();
    return result[0];
}

我从这个页面复制了Lock类: http://tutorials.jenkov.com/java-concurrency/locks.html

完成任务后,不要忘记退出处理程序线程.

翻译自:https://stackoverflow.com/questions/30320774/realm-access-from-incorrect-thread-android

原文  https://codeday.me/bug/20190111/500870.html
正文到此结束
Loading...