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

前端 未结 2 932
半阙折子戏
半阙折子戏 2021-01-26 14:15

So inside a IntentService, the app maybe active or inactive , onHandleIntent gets called , where I have placed this below code.This is where I store th

相关标签:
2条回答
  • 2021-01-26 14:50

    As per the error message: Once you obtain any Realm objects on 1 thread, they can ONLY be accessed on that thread. Any access on other threads will throw that exception.

    "doInBackground" from AsyncTask is run on a background thread. "onPostExecute" is run on the UI thread. So here you get Realm objects on a background thread, and try to access them on the UI thread => Exception.

    You should either do everything on the background thread, or everything on the UI thread.

    If you're doing a very complex query, i suggest using "findAllAsync" on the RealmQuery, as this will run the query on a background thread, and move them over to the main thread, but it's handled internally by Realm in a safe manner.

    0 讨论(0)
  • 2021-01-26 14:59
    for (AppItem item : appItems) { 
    

    If appItems contains managed RealmObjects that you obtained from a RealmResults on the UI thread, then accessing them will fail on the background thread.

    realm.executeTransactionAsync((realm) -> { gives you a Realm as parameter that is running on Realm's thread executor, so that must be used to obtain managed RealmResults/RealmObjects inside the transaction.

    So you need to re-query the objects inside realm.executeTransactionAsync if the objects are managed.

                public void execute(Realm realm) {
                    for (AppItem item : realm.where(AppItem.class).findAll()) { 
    
    0 讨论(0)
提交回复
热议问题