Val Okafor Val Okafor - 1 month ago 26
Android Question

Your Realm is opened from a thread without a Looper

I thought I was following the recommended Realm approach for running Async data inserts like this:

public void addCustomer(final Customer customer) {
Realm insertRealm = Realm.getDefaultInstance();
insertRealm.executeTransactionAsync(new Realm.Transaction() {
@Override
public void execute(Realm backgroundRealm) {
long id = customerPrimaryKey.incrementAndGet();
customer.setId(id);
backgroundRealm.copyToRealm(customer);
}
}, new Realm.Transaction.OnSuccess() {
@Override
public void onSuccess() {
Log.d(LOG_TAG, "Customer Added");
}
}, new Realm.Transaction.OnError() {
@Override
public void onError(Throwable error) {
Log.d(LOG_TAG, error.getMessage());
}
});

insertRealm.close();

}


However, when I run the above code I get "Your Realm is opened from a thread without a Looper and you provided a callback, we need a Handler to invoke your callback"

I am running this code in a non-Activity class, what I am doing wrong here and how can I fix it. Thanks.

Answer

You need to call addCustomer from UI thread.

Comments