ロードされた武器--LoadersのAndroidの非同期データベース

英語のドキュメント出典:http://developer.android.com/guide/components/loaders.html

ローダー、中国はAndroid3.0に追加し、「ローダー」として理解しました。その機能は、すなわち、データのロードを提供する、文字通りの意味から見ることができます。具体的には、非同期データローディングモード。それは次の機能があります。

  • すべてのためのローダーおよびフラグメント活動。
  •  非同期データローディング機構を提供します。
  • その元データの変更、データ変更の転送時に新しい結果を監視します。
  • 最後のカーソル・データ・ローダーへの自動再接続は、再クエリデータへの必要はありません


アプリケーションローダーで使用する方法

使用ローダーの前提条件:

  • 活動やFragmnetが必要
  • LoaderManagerの例
  • (のContentProviderに依存する)データをロードするためCursorLoaderオブジェクト
  • LoaderManager.LoaderCallbacks実装クラス。
  • 例えばSimpleCursorAdapterとしてデータ表示アダプタ
  • このようなのContentProviderなどのデータソース、

データローダーローダーを起動します

LoaderManagerマネージャまたはフラグメントローダインスタンスの一つ以上、各アクティビティは、アクティビティまたはフラグメントLoaserManagerに対応します。
         :アクティビティは、一般のonCreateメソッドまたはその断片ローダ初期化方法onActivityCreatedさ
getLoaderManager()initLoader(0、NULL、この);.
パラメータ:

図1に示すように、最初のパラメータ:0は固有の識別IDローダーであり、
図2に示すように、二番目のパラメータ:ここで、オプションのコンストラクタパラメータローダ、NULL;
3、第三のパラメータ:この、現在のオブジェクトまたは活性を意味しますフラグメントのオブジェクトは、オブジェクトデータはLoaderManager報告に供給されます。
InitLoader()メソッドは、ローダの初期化とオブジェクトの活性化は、このアプローチの実装は、2つの可能な結果を有することを保証します。

1、IDは、再利用存在する場合、
2、IDが存在しない場合、LoaderManager.LoaderCallbacks onCreateLoader(のその後出発)新しいメソッドを作成し、ローダを返します。


いずれの場合も、実装クラスに関連付けられているだけローダーのステータスが変更されている、LoaderManager.LoaderCallbacksが語られます。

あなたは気づいたかもしれない、ローダーは、initLoaderは、任意の変数に関連付けられていない返されたオブジェクトを自動LoaderManagerローダーの管理機能があるのでそれはある。LoaderManagerが起動し、必要なときに自動的にデータの読み込み動作を停止し、擁護ローダー状態;これは、それはあなたがめったにローダーと直接対話しないことを意味します。一般的に、LoaderManager.LoaderCallbacks onCreateLoader()メソッドを使用することは、特別なイベントのデータローディングの過程に介入します。


データローダーローダーを再起動する方法

あなたは上記のローダーを作成するときにIDが存在しない場合、作成、または古いローダーを使用していますが、時々 、私たちは、古いデータが再起動されてきれいにする必要があります。
restartLoaser()を使用して行うことができます。クエリ条件が変更されたときにたとえば、SearchView.OnQueryTextListener実装クラスは、ローダーは、最新の結果を得るために、再起動してください。

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相互作用ベルトです。
ローダ、特にCursorLoader、停止状態にその状態を保存するために期待しています。UIスタックの状況につながったデータをリロード回避この場合には、ユーザとの対話プロセス、。新しいローダを作成するときに知ることができ、コールバック関数を使用し、ロードするためにデータローダの使用を停止するときにアプリケーションに指示します。

コールバックメソッドは、次のとおりです。

  • onCreateLoaderは():新しいローダー与えられたIDを作成します。
  • onLoaderFinished():完成されたデータのロードは、ローダーを呼び出すと、
  • onLoaderReset():ローダ、排尿する前にデータをリセットします。
 
onCreateLoader例:

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

CursorLoader(コンテキスト・コンテキスト、ウリURI、文字列[]投影、ストリング選択、文字列[] selectionArgs、文字列はsortOrder) パラメータのコンストラクタ:
コンテキスト:ここでコンテキスト、アクティビティオブジェクトまたはその断片は、オブジェクト
のURIを:コンテンツ検索アドレス
プロジェクション:表示します列、すべての列の照会にnullを渡す
の選択:クエリがnullを渡す、SQLに似た文をフィルタリングし、それがすべてのクエリを表す
代替の選択で定義されたクエリパラメータ、:selectionArgsを?
sortOrder:SQLのORDER BYと同様の定義で並べ替え、


完全な例

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

    }
}










ます。https://my.oschina.net/cjkall/blog/195770で再現

おすすめ

転載: blog.csdn.net/weixin_34132768/article/details/91756387