116

对我来说,如果您有多个加载器,则不清楚如何获得正确的光标。假设您定义了两个不同的 Loader:

getLoaderManager().initLoader(0,null,this);
getLoaderManager().initLoader(1,null,this);

然后在onCreateLoader()你根据 id 做不同的事情:

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle arg1) {

    if (id==0){
               CursorLoader loader = new CursorLoader(getActivity(),
            MaterialContentProvider.CONTENT_URI,null,null,null,null);
    }else{
               CursorLoader loader = new CursorLoader(getActivity(),
            CustomerContentProvider.CONTENT_URI,null,null,null,null);
            };
    return loader;
} 

到目前为止,一切都很好。但是如何在onLoadFinished()中获得正确的光标,因为您没有任何 id 来识别正确的 Cursoradapter 的正确 Cursor。

@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor cursor) {


    mycursoradapter1.swapCursor(cursor);
    if(isResumed()){
        setListShown(true);
    }else {
        setListShownNoAnimation(true);
    }



}
//and where to get the cursor for mycursoradapter2

还是我错了,这是在一个片段中获取两个不同光标适配器的结果的错误方法。

4

3 回答 3

120

Loader 类有一个名为getId()的方法。我希望这会返回您与加载程序关联的 id。

于 2011-10-31T17:45:19.263 回答
32

使用Loader的getId()方法:

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    switch (loader.getId()) {
        case 0:
            // do some stuff here
            break;
        case 1:
            // do some other stuff here
            break;
        case 2:
            // do some more stuff here
            break;
        default:
            break;
    }
}    
于 2014-01-23T19:39:10.090 回答
8

If your loaders have nothing in common but the class type of the result (here: Cursor), you're better off creating two separate LoaderCallbacks instances (simply as two inner classes in your Activity/Fragment), each one dedicated to one loader treatment, rather than trying to mix apples with oranges.

In your case it seems that both the data source and the result treatment are different, which requires you to write the extra boilerplate code to identify the current scenario and dispatch it to the appropriate code block.

于 2014-04-20T00:54:54.520 回答