Luca Nicoletti
Luca Nicoletti

Reputation: 2407

realm access from icorrect thread even if I get another instance

I'm trying to retrieve some data & update them in a AsyncTask. The problem is I get a
Realm access from incorrect thread. Realm objects can only be accessed on the thread they were created.
error even if I'm updating my realm instance in the async task.
Here's my code:

 new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... params) {
                mRealm = Realm.getDefaultInstance();
                // my queries & updates
                return null;
            }
 }.execute();

Upvotes: 2

Views: 55

Answers (1)

Dhruv
Dhruv

Reputation: 1872

Try to create default insance in onPreExecute() method.

new AsyncTask<Void, Void, Void>(){
            private Realm mRealm;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                mRealm = Realm.getDefaultInstance();
            }

            @Override
            protected Void doInBackground(Void... params) {
                // my queries & updates
                return null;
            }
        }.execute();

Hope it will help you.

Upvotes: 2

Related Questions