Reputation: 3437
I am trying to do an asynchronous write with Realm and I need to pass the value to be persisted to the executeTransaction
method like this:
public void updateAsync(final long id, final String title, final String content, final int color) {
mRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
Note note = getNoteById(id);
if (note != null){
note.setTitle(title);
note.setContent(content);
note.setColor(color);
realm.copyToRealmOrUpdate(note);
}
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(LOG_TAG, "Note Updated");
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.d(LOG_TAG, error.getMessage());
}
});
}
The above code block failed with the error: Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created
SO my question is, how can I pass parameters to the background thread in Realm?
Upvotes: 1
Views: 2384
Reputation: 3565
When calling executeTransactionAsync
, the execute
block will run in a background thread, any Realm objects access from that thread need to be created/queried on that thread from the Realm instance which is the param of execute
.
You can use the param realm
to do queries. Just modify your getNoteById(id)
to take the Realm instance as a param like getNoteById(Realm realm, int id)
, and use the realm
to do query.
Upvotes: 1