nani nani - 24 days ago 13
Android Question

Realm error: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your callback

I've made this code in the method

onComplete()
of the subscriber:

long size, perc;
public void onCompleted()
{
Log.wtf("on complete","On complete");
realm = Realm.getInstance(defaultConfig);
realm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm mRealm) {
AirportR airport = new AirportR();

size = airp.size();
Log.d("size:", String.valueOf(size));

for (int i = 0; i < airp.size(); i++)
{
airport.setId(Integer.parseInt(airp.get(i).getId()));

perc = i / size * 100;
Log.d("i + percentage", String.valueOf(i) + " - " + String.valueOf(perc));

mRealm.insertOrUpdate(airport);
}
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess()
{
}
}, new Realm.Transaction.OnError() {
public void onError(Throwable error) {
error.printStackTrace();
}
});


and when I use debugger, I see this error message:

java.lang.IllegalStateException: Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your callback


and I see that if I don't use
Transaction.Success()
and
Transaction.OnError()
it works good and I have only this problem if I use these.

Is there a way to fix it?

Thanks

Answer

onCompleted() doesn't seem to run on the UI thread. A normal background thread on a scheduler doesn't have a looper, so Realm cannot notify it when an async transaction is complete.

You should either use executeTransaction() because you're already on a background thread, or just run executeTransactionAsync() from a looper thread (for example the UI thread).

Comments