Search code examples
javaandroidrealm

When app is not opened and when i try to insert Data in Realm I get Error "Realm cannot be automatically updated on a thread > without a looper"?


I am trying to insert the data in my Realm DB through FCM push notification, now when my app is opened and when a push notification arrives there everything works fine, but when my App is not opened and when the notification arrives then when I tried to insert the data I got the error `

java.lang.IllegalStateException: Callback cannot be delivered on current thread. Realm cannot be automatically updated on a thread without a looper.

My FCM code

            Realm realm = Realm.getDefaultInstance();

            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm bgRealm) {
                    story data = new story();
                    bgRealm.insertOrUpdate(data);
                }
            }, new Realm.Transaction.OnSuccess() {
                @Override
                public void onSuccess() {
                    // Transaction was a success.
                }
            }, new Realm.Transaction.OnError() {
                @Override
                public void onError(Throwable error) {
                    // Transaction failed and was automatically canceled.
                }
            });

Can anyone please tell me how can I overcome this problem when my app is not opened ??


Solution

  • You are using

    realm.executeTransactionAsync()
    

    That causes the problem, instead you should use syncronious version.

    realm.executeTransaction()
    

    For async queries, you need a looper to make sure the query result can be delivered back on Android.