2

I have a fragment that uses multiple CursorLoaders. All works fine. Now I need to add an AsyncTaskLoader as well, to the same fragment.

Question is, how can I use the same LoaderManager.LoaderCallbacks interface to manage both my CursorLoaders and AsyncTaskLoader?

My thought is that since CursorLoader is-a AsyncTaskLoader, then I should be able to adapt the LoaderCallBacks to both, but I may be miss the boat...

4

2 回答 2

2

这仅在所有加载器返回相同类型时才有效。如果这是真的,那么您只需为您启动的每个加载程序指定唯一的 ID。相同的 ID 被传递到 onCreateLoader() 调用中,因此您只需检查该 ID 以确定要创建的加载程序。

于 2012-06-28T12:40:48.360 回答
0

看来我这个问题太晚了,希望它可以帮助一些人。

我刚刚在同一个 Activity 中完成了一个带有多个加载器的项目,一个 CursorLoader 用于数据库,另一个 AsynctaskLoader 用于网络作业。

    class YourActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks {
    // you still implements LoaderManager.LoaderCallbacks but without add <returnType> 
    //and you have to cast the data into your needed data type in onLoadFinished()

        Private int loader1 = 1;   // eg. CursorLoaderId
        private int loader2 =2;    //eg. AsynctaskLoaderId

        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

// init loader with different Id
        getSupportLoaderManager().initLoader(yourLoaderId, null, this);
    }
        @Override
        public Loader onCreateLoader(int id, Bundle args) {
            if (id == loader1 ) {

                //YourLoaderClass1 is you loaderClass where you implement onStartLoading and loadingInBackground() 
                return new YourLoaderClass1();  
            } else if (id == loader2 ) {

                return new YourLoaderClass2();
            }
            return null;
        }

        @Override
        public void onLoadFinished(Loader loader, Object data) {
            int id = loader.getId();// find which loader you called
            if (id == loader1 ) {

                yourMethod1((List< >) data); // eg. cast data to List<String>
            } else if (id == loader2 ) {
                yourMethod1((String) data); // eg. cast data to String
            }
        }

        @Override
        public void onLoaderReset(Loader loader) {
            int id = loader.getId();
            if (id == loader1 ) {

            } else if (id == loader2 ) {

            }
        }
    }

这是我在其他问题下的回答和我的项目链接

于 2017-10-27T02:49:20.013 回答