CursorLoader为多个ContentProviders多个、CursorLoader、ContentProviders

2023-09-05 06:28:38 作者:画个逗号给明天

我需要做一个ListAdapter的起价多ContentProviders p $ psents数据。该ContentProviders自己重新present每一个表从关系型数据库。

I need to make a ListAdapter that presents data from multiple ContentProviders. The ContentProviders themselves represent one table each from relational database.

我想使用CursorLoader系统检索汇总数据到ListView控件。 这是可以做到1装载机或做我需要使用多个装载机?我倒是preFER使用一个。

I want to use the CursorLoader system to retrieve aggregate data into ListView. Is this possible to do with 1 loader or do I need to use multiple loaders? I'd prefer to use one.

我不知道我怎么能有2 ContentProviders互相交流之外做手工code这似乎不是一个很好的选择无论是加入。的

推荐答案

您必须编写自定义Loader类。例如:

You will have to write a Custom Loader class. For example:

public class FooLoader extends AsyncTaskLoader {

    Context context;

    public FooLoader(Context context) {
        super(context);
        this.context = context;
    }

    @Override
    public Cursor loadInBackground() {
        Log.d(TAG, "loadInBackground");
        YourDatabase dbHelper = new YourDataBase(context);
        SQLiteDatabase db= dbHelper.getReadableDatabase();

        /*** create a custom cursor whether it is join of multiple tables or complex query**/
        Cursor cursor = db.query(<TableName>, null,null, null, null, null, null, null);
        return cursor; 
    }
}

在调用活动或片段的onCreate()方法,你需要调用自定义的类装载器:

In the calling activity or fragments onCreate() method, you would need to call the custom loader class:

public class MyFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate():" + mContent);
        Loader loader = getLoaderManager().initLoader(0, null, this);
        loader.forceLoad();
    }   

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        Log.d(TAG, "onCreateLoader()")  ;
        return new FooLoader(getActivity());
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        Log.d(TAG, "onLoadFinished");            
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {   
    }
}