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 contextR.layout.list_item, // Layout for a single rownull, // No Cursor yetmFromColumns, // Cursor columns to usemToFields, // Layout fields to use0 // 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); }總結
以上是生活随笔為你收集整理的Android官方开发文档Training系列课程中文版:后台加载数据之处理CursorLoader的查询结果的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入解析Node.js setTimeo
- 下一篇: 我们的实践: 400万全行业动态事理图谱