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

原文地址: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 View
ListView 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 view
mListView.setAdapter(mAdapter);
...
/*
 * Defines the callback that CursorLoader calls
 * when it's finished its query
 */
@Override
public 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.
 */
@Override
public void onLoaderReset(Loader<Cursor> loader) {

    /*
     * Clears out the adapter's reference to the Cursor.
     * This prevents memory leaks.
     */
    mAdapter.changeCursor(null);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值