0

In Realm, I am using executeTransactionasync method and in execute I am calling a method from utility class but when I am calling this method I am getting an error

Realm objects can only be accessed on the thread they where created

Utils.class

public void update_data(final Realm realm) {
    data bgTran = realm.where(data.class).equalTo("obj", "hello").findFirst();
    if(bgTran!= null){
        bgTran.settime("7 June");
    }
}

Activity Class Code

realm.executeTransactionAsync(new Realm.Transaction() {
    @Override
    public void execute(final Realm bgRealm) {
        utils.update_data(realm);
    }
}, new Realm.Transaction.OnSuccess() {
    @Override
    public void onSuccess() {

    }

}, new Realm.Transaction.OnError() {
    @Override
    public void onError(Throwable error) {
        //gettting Error Realm objects can only be accessed on the thread they where created
    }
});

Can anyone please tell me as the same realm is getting passed over the method call why is in UI thread then why am I getting the error.

But When I am writing whole executetransactionasync in Util class then it is running perfectly fine.

Utils.class

public void update_data(final Realm realm) {
     realm.executeTransactionAsync(new Realm.Transaction() {
         @Override
         public void execute(final Realm bgRealm) {
             data bgTran = bgRealm.where(data.class).equalTo("obj", "hello").findFirst();
             if(bgTran!= null){
                  bgTran.settime("7 June");
             }
         }
     }, new Realm.Transaction.OnSuccess() {
         @Override
         public void onSuccess() {

         }

     }, new Realm.Transaction.OnError() {
         @Override
         public void onError(Throwable error) {

         }
     });
}

Edit - The question is different from the marked question because there I know onpostExecute(UI Thread), doInBackground(Background Thread) they both access different Threads but the thing here is that as my code is in Activity Class so it will have a looper, so when I will call a method in util class now this class also can access to the looper because I am still in UI Thread then why this error is coming, Also if this error is coming then it should also come for the second case which I have mentioned but it is not ?

Also, how can I write a common logic like I wrote in update_data() and use it anywhere? Because otherwise, I would have to write the same code again and again in the every Realm executeTransactionasync ?

Sudhanshu Gaur
  • 7,486
  • 9
  • 47
  • 94

0 Answers0