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.
Update - Fixed It turns out that there is nothing wrong with the query, problem is that I was calling it from IntentService. I was trying to seed the database on app first run, so I fixed this like this:
protected void onHandleIntent(Intent intent) {
Realm realm = Realm.getDefaultInstance();
//Add sample Customers to database
List<Customer> customers = SampleCustomerData.getCustomers();
realm.beginTransaction();
for (Customer customer: customers){
customer.setId(customerPrimaryKey.getAndIncrement());
realm.copyToRealm(customer);
}
realm.commitTransaction();
realm.close();
}
That fixed, outside of the IntentService, the query works fine when called from a UI Thread.