如何在Thread中获取RealmList?

时间:2017-05-06 23:49:02

标签: java android multithreading arraylist realm

您好我的应用程序需要从RealmObject(PlayList.class)获取RealmList。问题是我试图在其他线程上执行此操作。(一些带有tick()方法的循环引擎)所以我的解决方案是从RealmObject获取RealmList并将其转换为ArrayList,而不是我想要的任何东西线程。

这是我得到的崩溃

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

这是我的RealmObject类

public class PlaylistModel extends RealmObject implements Serializable {

    public int id;
    public String path;
    public String fileName;
    public String duration;
    public RealmList<Note> notes;

这是我的Note类

public class MidiModel extends RealmObject implements Serializable {

    private String tag;
    private long spaceTime = -1;

这就是我获取数据的方式

public RealmResults<PlaylistModel> getPlaylist(){
    realm.beginTransaction();
    RealmResults<PlaylistModel> realmResults = realm.where(PlaylistModel.class).findAll();
    realm.commitTransaction();
    return realmResults;
}

这就是我试图在不同的线程中读取RealmList的方法

  public void tick(){
        Note model =  noteList.get(index);
        index++;
    }

我怎样才能使它有效? 在操作之前,我是否需要将RealmList转换为ArrayList? 请帮助:)

1 个答案:

答案 0 :(得分:0)

托管的RealmObjects不能在线程之间传递,因此您需要在后台线程上通过其主键从为该线程打开的Realm实例重新查询它。

Executor executor = Executors.newSingleThreadedPool(); // like new Thread().start();

public void doSomething(final String pkValue) {
    executor.execute(new Runnable() {
        @Override
        public void run() {
            try(Realm realm = Realm.getDefaultInstance()) { // beginning of thread
                doThingsWithMyObject(realm, pkValue);
            } // end of thread
        }
    }
}

public void doThingsWithMyObject(Realm realm, String pkValue) { // <-- pass Realm instance
    MyObject myObject = realm.where(MyObject.class).equalTo("id", pkValue).findFirst(); // <-- requery
    RealmList<Note> notes = myObject.getNotes();
    // ... do things with notes
}