Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android之數據庫異步加載利器--Loaders

Android之數據庫異步加載利器--Loaders

編輯:關於Android編程

 

Loaders,中文可理解為“加載器”,在Android3.0中新增。從字面含義可見其功能,即提供數據加載。特別地,加載數據的方式為異步。它具有以下特點:

Loaders用於所有的Activity和Fragment; 提供異步數據裝載機制;監控他們的來源數據變化情況,在數據發生變化的時候傳遞新的結果;自動重連到最後一個數據加載器游標,因此不需要重新查詢數據

 

如何在應用中使用Loaders

使用Loaders的先決條件:

需要一個Activity 或者 Fragmnet一個LoaderManager實例一個用於加載數據的的CursorLoader對象(依賴於ContentProvider)一個LoaderManager.LoaderCallbacks的實現類.一個數據展現適配器,比如SimpleCursorAdapter一個數據源,比如ContentProvider

 

啟動數據加載器Loaders

LoaderManager管理者一個Activity或者Fragment中的一個或多個Loader實例,每個Activity或者Fragment只有對應一個LoaserManager。
一般在Activity的onCreate方法或者Fragment的onActivityCreated方法中初始化一個Loader:
getLoaderManager().initLoader(0, null, this);
參數:

1、 第一個參數:0 為Loader的唯一標識ID;
2、 第二個參數: 為Loader的構造器可選參數,這裡為null;
3、 第三個參數:this,這裡表示當前Activity對象或者Fragment對象,提供給LoaderManager對象進行數據匯報。
InitLoader()方法保證了Loader初始化及對象激活,執行這個方法有2個可能的結果:

1、 如果ID存在,則重復利用;
2、 如果ID不存在,則出發LoaderManager.LoaderCallbacks的onCreateLoader()方法新創建一個Loader並返回;

 

不管在什麼情況下,只有Loader狀態發生了變化,與之關聯的LoaderManager.LoaderCallbacks實現類都會被告知;

你可能注意到了,initLoader返回的Loader對象並未與任何變量關聯,那是因為LoaderManager有自動的Loader管理功能;LoaderManager在必要的時候自動啟動及停止數據加載操作,並且維護者Loader的狀態;這就意味著,你很少直接與Loader進行交互。一般地,使用LoaderManager.LoaderCallbacks的onCreateLoader()方法去干預數據加載的過程中的特殊事件。


如何重啟數據加載器Loaders

在上面創建Loaders時,如果ID不存在則創建,否則使用舊的Loader,但有些時候,我們需要清理掉舊的數據重新開始。
使用restartLoaser()可以做到。比如,SearchView.OnQueryTextListener的實現類,在查詢條件發生改變時重啟Loaders,以便獲取最新的查詢結果。

 

public boolean onQueryTextChanged(String newText) {

    // Called when the action bar search text has changed.  Update

    // the search filter, and restart the loader to do a new query

    // with this filter.

    mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;

    getLoaderManager().restartLoader(0, null, this);

    return true;
}

如何使用LoaderManager的回調方法

 

LoaderManager.LoaderCallbacks 接口是客戶端與LoaderManager進行交互的腰帶。
Loader ,特別是CursorLoader,期望在停止狀態後保存它們的狀態。這樣的話,用戶在交互過程中,就避免了數據的重新加載而導致UI卡死的局面。使用回調函數,就可以知道什麼時候去創建一個新的Loader,並且告知應用程序什麼時候停止使用Loader加載的數據。

回調方法有:

onCreateLoader():根據給定的ID創建新的Loader;onLoaderFinished():當Loader完成數據加載後調用;onLoaderReset():Loader重置,使之前的數據無效;
onCreateLoader使用實例:

 

 

// If non-null, this is the current filter the user has provided.

String mCurFilter;

...

public Loader onCreateLoader(int id, Bundle args) {

    // This is called when a new Loader needs to be created.  This

    // sample only has one Loader, so we don't care about the ID.

    // First, pick the base URI to use depending on whether we are

    // currently filtering.

    Uri baseUri;

    if (mCurFilter != null) {

        baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,

                  Uri.encode(mCurFilter));

    } else {

        baseUri = Contacts.CONTENT_URI;

    }

 

    // Now create and return a CursorLoader that will take care of

    // creating a Cursor for the data being displayed.

    String select = (( + Contacts.DISPLAY_NAME +  NOTNULL) AND (

            + Contacts.HAS_PHONE_NUMBER + =1) AND (

            + Contacts.DISPLAY_NAME +  != '' ));

    return new CursorLoader(getActivity(), baseUri,

            CONTACTS_SUMMARY_PROJECTION, select, null,

            Contacts.DISPLAY_NAME +  COLLATE LOCALIZED ASC);
}

CursorLoader(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)構造器參數解釋:
Context:上下文,這裡是Activity對象或者Fragment對象
Uri:內容檢索地址
Projection:要顯示的列,傳null表示查詢所有的列
Selection:查詢過濾語句,類似SQL WHERE ,傳null,表示查詢所有
selectionArgs:查詢參數,替換在selection中定義的 ?
sortOrder:排序定義,類似SQL ORDER BY

 

 

完整的實例

 

public static class CursorLoaderListFragment extends ListFragment

        implements OnQueryTextListener, LoaderManager.LoaderCallbacks {

 

    // This is the Adapter being used to display the list's data.

    SimpleCursorAdapter mAdapter;

 

    // If non-null, this is the current filter the user has provided.

    String mCurFilter;

 

    @Override public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

 

        // Give some text to display if there is no data.  In a real

        // application this would come from a resource.

        setEmptyText(No phone numbers);

 

        // We have a menu item to show in action bar.

        setHasOptionsMenu(true);

 

        // Create an empty adapter we will use to display the loaded data.

        mAdapter = new SimpleCursorAdapter(getActivity(),

                android.R.layout.simple_list_item_2, null,

                new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },

                new int[] { android.R.id.text1, android.R.id.text2 }, 0);

        setListAdapter(mAdapter);

 

        // Prepare the loader.  Either re-connect with an existing one,

        // or start a new one.

        getLoaderManager().initLoader(0, null, this);

    }

 

    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

        // Place an action bar item for searching.

        MenuItem item = menu.add(Search);

        item.setIcon(android.R.drawable.ic_menu_search);

        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        SearchView sv = new SearchView(getActivity());

        sv.setOnQueryTextListener(this);

        item.setActionView(sv);

    }

 

    public boolean onQueryTextChange(String newText) {

        // Called when the action bar search text has changed.  Update

        // the search filter, and restart the loader to do a new query

        // with this filter.

        mCurFilter = !TextUtils.isEmpty(newText) ? newText : null;

        getLoaderManager().restartLoader(0, null, this);

        return true;

    }

 

    @Override public boolean onQueryTextSubmit(String query) {

        // Don't care about this.

        return true;

    }

 

    @Override public void onListItemClick(ListView l, View v, int position, long id) {

        // Insert desired behavior here.

        Log.i(FragmentComplexList, Item clicked:  + id);

    }

 

    // These are the Contacts rows that we will retrieve.

    static final String[] CONTACTS_SUMMARY_PROJECTION = new String[] {

        Contacts._ID,

        Contacts.DISPLAY_NAME,

        Contacts.CONTACT_STATUS,

        Contacts.CONTACT_PRESENCE,

        Contacts.PHOTO_ID,

        Contacts.LOOKUP_KEY,

    };

    public Loader onCreateLoader(int id, Bundle args) {

        // This is called when a new Loader needs to be created.  This

        // sample only has one Loader, so we don't care about the ID.

        // First, pick the base URI to use depending on whether we are

        // currently filtering.

        Uri baseUri;

        if (mCurFilter != null) {

            baseUri = Uri.withAppendedPath(Contacts.CONTENT_FILTER_URI,

                    Uri.encode(mCurFilter));

        } else {

            baseUri = Contacts.CONTENT_URI;

        }

 

        // Now create and return a CursorLoader that will take care of

        // creating a Cursor for the data being displayed.

        String select = (( + Contacts.DISPLAY_NAME +  NOTNULL) AND (

                + Contacts.HAS_PHONE_NUMBER + =1) AND (

                + Contacts.DISPLAY_NAME +  != '' ));

        return new CursorLoader(getActivity(), baseUri,

                CONTACTS_SUMMARY_PROJECTION, select, null,

                Contacts.DISPLAY_NAME +  COLLATE LOCALIZED ASC);

    }

 

    public void onLoadFinished(Loader loader, Cursor data) {

        // Swap the new cursor in.  (The framework will take care of closing the

        // old cursor once we return.)

        mAdapter.swapCursor(data);

    }

 

    public void onLoaderReset(Loader loader) {

        // This is called when the last Cursor provided to onLoadFinished()

        // above is about to be closed.  We need to make sure we are no

        // longer using it.

        mAdapter.swapCursor(null);

    }
}


 

 

 

 

 

 

 

 

 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved