Loader異步加載數據

在android3.0開始,新增了Loader.  Loader加載數據的方式是異步的。
Loader的特色:
 1.適合於activity和fragment
 2.提供了異步加載數據機制
 3.監控數據源,當數據源發生改變時,會傳遞新結果
 4.自動重連到最後一個數據加載器遊標,不須要從新查詢數據java


使用狀況:對數據源監控,好比contentProvider.
     CursorLoader是AsyncTaskLoader的子類,AsyncTaskLoader會提供AsynTask去操做。故不會阻塞UI線程。android


實例:獲取手機號碼
public class MainActivity extends ListActivity implements LoaderCallbacks<Cursor> {
    //ListActivity能夠不寫setContentView(R.layout.activity_main),由於其含有默認的佈局。
 //ListActivity對應佈局中的ListView的   android:id="@android :id/list"
 public static final int ID = 110;異步

 SimpleCursorAdapter adapter;
 String[] showContent = new String[] {
          Phone.NUMBER};ide

 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);佈局

  adapter = new SimpleCursorAdapter(this,
    android.R.layout.simple_list_item_1, null, showContent,
    new int[] { android.R.id.text1});
  
  setListAdapter(adapter);this

  
  //參數:id,Bundle對象(onCreateLoader()中第二個參數),LoaderCallbacks<D> 對象
  getLoaderManager().initLoader(ID, null, this);
 }.net

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {線程

  getMenuInflater().inflate(R.menu.main, menu);對象

  return true;
 }
     //建立Loader對象,CursorLoader對象(含有AsyncTask的功能)會本身在後臺線程加載數據,最後返回一個cursor
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
  Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
    //如果出現java.lang.IllegalArgumentException: column '_id' does not exist,
      //則是String[] projection中沒有寫入 '_id'。
      //simplecursoradapter在顯示時根據'_id'來顯示。故不能沒有'_id'
  CursorLoader loader = new CursorLoader(this, uri, null, null,
    null, null);
  return loader;
 }get

 //Loader第一次讀取完數據,或者數據源發生變化時會被調用
 public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
  //一個loadermanager能夠管理多個loader,故對loader的id進行判斷
  switch (loader.getId()) {
   case ID:
    // 將查詢到數據加載到listview上
    adapter.swapCursor(cursor);
    break;
 
   default:
    break;
  }

 }

 @Override
 public void onLoaderReset(Loader<Cursor> arg0) {
  adapter.swapCursor(null);//移除引用
 }

}

相關文章
相關標籤/搜索