Android: LoaderCallbacks.OnLoadFinished called twice

前端 未结 10 2287
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 11:05

I noticed strange situation using Android Loaders and Fragments. When I invoke LoaderManager.initLoader() after orientation change onLoadFinished is not called (although doc

10条回答
  •  暖寄归人
    2020-12-04 11:34

    Since all searching for this subject inevitably ends up here, I just wanted to add my experience. As @jperera said, the culprit was that LoaderManager will call onLoadFinished() if the loaders already exist. In my case, I had fragments in a FragmentPager and scrolling 2 tabs away and then scrolling next to it again would cause my old fragment to begin creating itself.

    Since placing initLoader() inside onCreate() also causes double callbacks, I placed the initLoader() inside onResume(). But the sequence of events ends up being onCreate(), LoaderManager calls callbacks since loaders exist, then onResume() is called, triggering another initLoader() and onLoadFinished() sequence. IE, another double callback.

    solution

    I found a quick solution by "Matt". After all your data is loaded (if you have more than one loader), destroy all of the loaders so their callbacks won't be called an extra time.

提交回复
热议问题