Loader unable to retain itself during certain configuration change

前端 未结 4 614
渐次进展
渐次进展 2020-12-13 06:59

According to http://developer.android.com/guide/components/loaders.html, one of the nice thing about loader is that, it is able to retain its data during configuration chang

4条回答
  •  天命终不由人
    2020-12-13 07:40

    My answer is quite straight forward actually. Don't use AsyncTaskLoaders. Because a few bugs regarding AsyncTaskLoaders you knew it by now.

    A good combination would be a retainable (setRetainInstance(true) in onActivityCreated()) fragment with AsyncTask. Works the same way. Just have to restructure the code a bit.


    Message from OP

    Although the author doesn't provide any code example, this is the closest workable solution. I do not use the author proposed solution. Instead, I still rely on AsyncTaskLoader for all the necessary loading task. The workaround is that, I will rely on an additional retained fragment, to determine whether I should reconnect/create loader. The is the skeleton code on the whole idea. Works pretty well so far as long as I can tell.

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        ...
    
        dataRetainedFragment = (DataRetainedFragment)fm.findFragmentByTag(DATE_RETAINED_FRAGMENT);
        // dataRetainedFragment can be null still...
    }
    
    @Override
    public void onResume() {
        ...
        if (this.data == null) {
            if (dataRetainedFragment != null) {
                // Re-use!
                onLoadFinished(null, dataRetainedFragment);
            } else {
                // Prepare the loader.  Either re-connect with an existing one,
                // or start a new one.
                getLoaderManager().initLoader(0, null, this);
            }
        } else {
        }
    }
    
    @Override
    public void onLoadFinished(Loader arg0, Data data) {
        this.data = data;
    
        if (this.dataRetainedFragment == null) {
            this.dataRetainedFragment = DataRetainedFragment.newInstance(this.data);
            FragmentManager fm = getFragmentManager();
            fm.beginTransaction().add(this.dataRetainedFragment, DATE_RETAINED_FRAGMENT).commitAllowingStateLoss();            
        }
    

提交回复
热议问题