星期五, 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);
    }
}



沒有留言:

張貼留言