Android官方开发文档Training系列课程中文版:后台加载数据之处理CursorLoader的查询结果

来源:互联网 发布:手机淘宝修改发货地址 编辑:程序博客网 时间:2024/06/06 05:49

原文地址:http://android.xsoftlab.net/training/load-data-background/handle-results.html

就像上节课所说的,我们应该在onCreateLoader()内使用CursorLoader来加载数据。那么在数据加载完毕之后,加载结果会通过LoaderCallbacks.onLoadFinished()方法传回到实现类中。该方法的其中一个参数为包含查询结果的Cursor对象。你可以通过这个对象来更新UI数据或者用它来做进一步的操作。

除了onCreateLoader()及onLoadFinished()这两个方法之外,还应当实现onLoaderReset()方法。这个方法会在上面返回的Cursor对象所关联的数据发生变化时调用。如果数据发生了变化,那么Android框架会重新进行查询。

处理查询结果

为了显示Cursor对象中的数据,这里需要实现AdapterView的相关方法以及CursorAdapter的相关方法。系统会自动的将Cursor中的数据转换到View上。

你可以在展示数据之前将数据与Adapter对象进行关联,这样的话系统才会自动的更新View:

public String[] mFromColumns = {    DataProviderContract.IMAGE_PICTURENAME_COLUMN};public int[] mToFields = {    R.id.PictureName};// Gets a handle to a List ViewListView mListView = (ListView) findViewById(R.id.dataList);/* * Defines a SimpleCursorAdapter for the ListView * */SimpleCursorAdapter mAdapter =    new SimpleCursorAdapter(            this,                // Current context            R.layout.list_item,  // Layout for a single row            null,                // No Cursor yet            mFromColumns,        // Cursor columns to use            mToFields,           // Layout fields to use            0                    // No flags    );// Sets the adapter for the viewmListView.setAdapter(mAdapter);.../* * Defines the callback that CursorLoader calls * when it's finished its query */@Overridepublic void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {    ...    /*     * Moves the query results into the adapter, causing the     * ListView fronting this adapter to re-display     */    mAdapter.changeCursor(cursor);}

移除旧的Cursor引用

CursorLoader会在Cursor处于无效状态时对其进行重置。这种事件会经常发生,因为Cursor所关联的数据会经常发生变化。在重新查询之前,系统会调用所实现的onLoaderReset()方法。在该方法内,应将当前Cursor的所持有的引用置空,以防止内存泄露。一旦onLoaderReset()方法执行完毕,CursorLoader就会重新进行查询。

/* * Invoked when the CursorLoader is being reset. For example, this is * called if the data in the provider changes and the Cursor becomes stale. */@Overridepublic void onLoaderReset(Loader<Cursor> loader) {    /*     * Clears out the adapter's reference to the Cursor.     * This prevents memory leaks.     */    mAdapter.changeCursor(null);}
0 0