顯示具有 Loader 標籤的文章。 顯示所有文章
顯示具有 Loader 標籤的文章。 顯示所有文章

星期五, 8月 22, 2014

Loader (二)

Using the LoaderManager Callbacks

LoaderManager.LoaderCallbacks是一個回調介面讓使用者能與LoaderManager互動。

Loader,尤其是CursorLoader,預期在停止後保留它們的資料。這允許應用程式保留住它們的資料跨越activity或fragment的onStop()及onStrat()方法,以便當使用者回到應用程式,他們不需要等待資料重新載入。你可以使用LoaderManager.LoaderCallbacks方法知道何時建立新的loader,並告訴應用程式何時該停止使用loader的資料。

LoaderManager.LoaderCallbacks包含這些方法

  • onCreateLoader() - 為特定ID建立及回傳新的loader
  • onLoaderFinished() - 當先前建立的loader完成資料加載時呼叫
  • onLoaderReset() - 當先前建立的loader被重置時呼叫,從而使得其資料不可用

onCreateLoader

當你試著存取loader時(例如,透過initLoader()),它會檢查特定ID的loader是否存在。如果不存在,它會觸發LoaderManager.Loadercallbacks方法的onCreateLoader()方法,這是建立新loader的地方,通常會是CursorLoader,但是你可以執行你自己的loader子類。

在此例中,這個onCreateLoader()方法會建立一個CursorLoader,你必須使用建構子建立CursorLoader,建構子需要完整的資訊去查詢Content Provider。具體來說,建構子需要以下資訊
  • uri - 對於要取得content的URI
  • projection - 哪些columns回傳的列表,傳入null將會回傳所有columns,這樣是無效率的
  • selection - 過濾器宣告回傳哪些rows,格式如SQL WHERE條文(排除WHERE本身)。傳入null會回傳特定uri的所有rows
  • selectionArgs - 在selection中可能會包含多個?s,這將從selectionArgs的值取代,依它們在selection出現的順序。這些值被用字串綁定
  • sortOrder - 如何指揮rows,格式為SQL ORDER BY條文(排除ORDER BY本身)。傳入null使用預設的排序方式,它可能沒有排序
舉例

// If non-null, this is the current filter the user has provided.
String mCurFilter;
...
public Loader<Cursor> 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");
}


onLoadFinished

此方法當先前loader已經完成加載資料時被呼叫,此方法保證在最後供應給loader的資料釋放之前被呼叫。在此刻,你應該移除所有使用的舊資料,但不應該自己完成釋放資料,因為擁有資料的loader會照料它們。

一旦loader知道應用程式不會在使用資料,loader就會釋放資料。例如,如果資料是來自CursorLoader的cursor,你不應該呼叫close()。如果此cursor被放入CursorAdapter,你應該使用SwapCursor()方法,如此舊的cursor不會被關閉。

舉例

// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // Swap the new cursor in.  (The framework will take care of closing the
    // old cursor once we return.)
    mAdapter.swapCursor(data);
}


onLoaderReset

當先前的loader被重置時會呼叫此方法,如此使資料為不可用的。此回調方法讓你找出資料和時被釋放,如此你可以移除你的參考。

以下執行為swapCursor()方法,傳入參數為null

// This is the Adapter being used to display the list's data.
SimpleCursorAdapter mAdapter;
...
public void onLoaderReset(Loader<Cursor> 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);
}


Example

以下例子為在Fragment上用ListView顯示查詢聯絡人content provider的結果,使用CursorLoader管理作用在proivder的查詢。

為了讓應用程式存取使用者的聯絡人資料,它的manifest必須包含權限READ_CONTACTS。

public static class CursorLoaderListFragment extends ListFragment
        implements OnQueryTextListener, LoaderManager.LoaderCallbacks<Cursor> {

    // 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<Cursor> 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<Cursor> 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<Cursor> 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);
    }
}



Loader (一)

Loader讓異步加載資料到Activity或Fragment更加容易,loaders有以下特點
  • 它們是提供給每個Activity或Fragment用的
  • 它們提供異步的資料加載
  • 它們監測資料來源並在內容改變時傳送新的結果
  • 當Cursor更改設定正在重建時,它們會自動地重新連接最後的loader的Cursor,所以他們不需重新查詢它們的數據。
Using Loader in an Application

如何在應用程式中使用Loader,應用程式典型地使用loader包含以下
  • 一個Activity或Fragment
  • 一個LoaderManager的實例
  • 一個CursorLoader藉由ContentProvider加載資料。另外,可以執行自己的Loader或AsyncTaskLoader的子類從其他資料來源加載。
  • 執行LoaderManager.LoaderCallbacks,這是產生新Loader及管理參考到已存在的Loader的地方
  • 顯示Loader資料的方法,如SimpleCursorAdapter
  • 一個資料來源,如ContentProvider,當使用一個CursorLoader

Starting a Loader

LoaderManager管理在Activity或Fragment一個或多個Loaders,每個Activity或Fragment只能有一個Loader。

初始化Loader典型方式是在Activity的onCreate()方法或是Fragment中的onActivityCreate()方法,以下

// Prepare the loader.  Either re-connect with an existing one,
// or start a new one.
getLoaderManager().initLoader(0, null, this);

initLoader()方法傳入的參數為
  • 唯一的識別碼用來識別loader,此例中,ID為0
  • 可選的參數在建構時提供loader(此例中為null)
  • 一個LoaderManager.Loadercallbacks的實施,LoaderManager呼叫報告loader事件,此例中,本地類別實施LoaderManager.LoaderCallback介面,所以傳入this參考到自己
initLoader()方法呼叫確保loader被初始化與活躍,它有兩種可能的結果

  • 如果指定給loader的ID已存在,重複使用最後建立的loader
  • 如果指定給loader的ID不存在,initLoader()方法會觸發LoaderManager.LoaderCallbacks方法的onCreateLoader(),這是執行程式去實例及回傳新loader的地方
在任一情況下,特定的LoaderManager.LoaderCallbacks實施是與loader關聯的,且在loader狀態改變時被呼叫。如果在呼叫的當下呼叫者在其開始狀態,並且請求的loader已存在且產生了資料,系統會立即呼叫onLoadFinish(),所以必須準備這樣的情況發生。

注意initLoader()方法會回傳被建立的Loader,但你不需要取得一個參考給它,LoaderManager會自動地管理loader的生命週期,必要時刻LoaderManager會啟動和停止加載,並維護loader的狀態及其關聯的資料。這意味著,你很少直接與loader互動。當特別的事件發生時,你一般必須使用LoaderManager.LoaderCallbacks方法去干預加載的程序。


Restarting a Loader

當你使用initLoader()方法時,如果指定ID有以存在的loader,它會使用已存在的loader;如果沒有,他會建立一個。但是有時候想要拋棄舊資料並重新開始。

拋棄舊資料,使用restartLoader()。例如,SearchView.OnQueryTextListener在使用者的查詢改變時重新開始loader,loader需要重新開始,如此它才能使用被修訂的搜尋過濾器去做新的查詢。

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;
}