3.0では、AsyncTaskLoader
、CursorLoader
、およびその他のカスタムLoader
のインスタンスを使用してデータ読み込みを処理するファンシーなLoaderManager
が得られました。しかし、私はちょうどポイントを得ることができなかったこれらのためのドキュメントを読んで:データの読み込みのために良い古いAsyncTask
を使用するだけでなく、これらはどのように優れていますか?Android 3.0 - LoaderManagerインスタンスを正確に使用する利点は何ですか?
答えて
よく実装するのが簡単で、ライフサイクル管理に関するすべてのことを考慮しているため、エラーが起こりにくいです。
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);
}
}
が正しく、このフル例を実装する:
ただ、ユーザーが対話的にアクションバーでクエリ入力フィールドを介して、結果セットをフィルタリングすることができますカーソル問合せの結果を示すために、サンプルコードを見てあなた自身がAsyncTaskを使ってもっと多くのコードを組み込むことになります...そして、それでも、あなたは完全でうまくいくものとして何かを実装しようとしていますか?たとえば、ロードされたCursorをアクティビティ構成の変更全体に保持するため、新しいインスタンスの作成時に再クエリする必要はありませんか? LoaderManager/Loaderは自動的にそれを行います。また、アクティビティのライフサイクルに基づいてCursorを正しく作成して閉じる処理も行います。
また、このコードを使用しても、長時間実行されている作業がメインのUIスレッドから実行されていることを確認する必要はありません。 LoaderManagerとCursorLoaderはそのすべてを処理し、カーソルと対話しながらメインスレッドを決してブロックしないようにします。これを正しく行うには、実際にポイントで同時に2つのCursorオブジェクトをアクティブにする必要があります。そのため、次のカーソルがロードされている間は、現在のCursorでインタラクティブなUIを表示し続けることができます。 LoaderManagerはそれをすべて行います。
これはほんの遥かに単純なAPIで、AsyncTaskについて知る必要はなく、バックグラウンドで何を実行する必要があるか、アクティビティライフサイクルについて考える必要はなく、アクティビティの古い「マネージドカーソル」APIを使用する必要はありません(これは、とにかくLoaderManagerと同様に機能しませんでした)。
(ところであなたは1.6までのAndroidの古いバージョンのフルLoaderManagerのAPIを使用してみましょう新しい「サポート」の静的ライブラリを忘れないように!)
すばらしい答え!はい、初心者がAsyncTaskを誤用するのはまだまだ容易ではありませんでした。設定変更を簡単に処理できず、 'onProgressUpdate'などでコンテキストが必要な場合は、メモリリークを起こさないように注意する必要がありました。 –
多分それは私ですが、これは簡単ではありません! – Ants
@hackbod私はAndroid 4.0とサポートライブラリの両方を試しましたが、カーソルが_変更されていない_のように見えます。私もこれに関連するバグを見つけました:http://code.google.com/p/android/issues/detail?id=25112 – inazaruk
- 1. Python 3を使用する利点/利点は何ですか?
- 2. プロキシキャッチサーバーを使用する利点と欠点は何ですか?
- 3. 使用する利点何
- 4. Redisインスタンスは正確に何ですか?
- 5. プライベートクラウドをデータセンターに使用する利点は何ですか?
- 6. Saxonを.netに使用する利点は何ですか?
- 7. TextBox上でRichTextBoxを使用する利点は何ですか?
- 8. メソッドシグネチャでジェネリックを使用する利点は何ですか?
- 9. MVVMLightでSimpleIoCを使用する利点は何ですか?
- 10. サプライヤをJavaで使用する利点は何ですか?
- 11. C#でインターフェイスを使用する利点は何ですか?
- 12. WebアプリケーションでEJBを使用する利点は何ですか?
- 13. wpfでWeb APIを使用する利点は何ですか?
- 14. pgbouncerでトランザクションプーリングを使用する利点は何ですか?
- 15. __iter __()でyieldを使用する利点は何ですか?
- 16. Pythonでcimportを使用する利点は何ですか?
- 17. ThreadPoolExecutorでWaterMarkExecutorを使用する利点は何ですか?
- 18. AWSでDockerを使用する利点は何ですか?
- 19. ErlangでRabbitMQを使用する利点は何ですか?
- 20. Subversionを使用する利点は何ですか?
- 21. emacsオートフィルモードを使用する利点は何ですか?
- 22. FetchXmlを使用する利点は何ですか?
- 23. Animator.StringtoHash( "")を使用する利点は何ですか?
- 24. 名前空間を使用する利点は何ですか?
- 25. Redux over Reactを使用する利点は何ですか?
- 26. エラーバックを使用する利点は何ですか?
- 27. babel-plugin-react-intlを使用する利点は何ですか?
- 28. SFSafariViewControllerを使用する主な利点は何ですか?
- 29. Oracle Designerを使用する利点は何ですか?
- 30. Object.assign()を使用する利点は何ですか?
[** **この記事を]チェックアウト(HTTP ://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html)...最初の部分は、廃止された 'startManagingCursor'の上に' LoaderManager'を使用する利点を列挙しています... – user1422551
[** LoaderManager' **の理解(http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html)は、学ぶべき素晴らしい投稿です。 –