mahdi pishguy mahdi pishguy - 4 months ago 44
Android Question

Android how can i use Realm on Thread

in my application i read contacts which saved on phone, this may be take a long time, then i put that on

Thread
nested that i'm using
Realm
but i get this error:

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


and my solutions dont resolve this problem such as :

new Handler().post(new Runnable() {
@Override
public void run() {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
}
});
}
});


OR

new Handler(getMainLooper()).post(new Runnable() {
@Override
public void run() {
realm.executeTransaction(new Realm.Transaction() {
@Override
public void execute(Realm realm) {
}
});
}
});


on nested Thread,

Answer

The problem is not that you're using Realm in a different thread, the problem is that you're using the instance on the real in a different thread. Usually that's an easy fix, something like that should do:

Realm realmForThisThread = Realm.getDefaultInstance();
realmForThisThread.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
    }
}