随着3.0我们得到了花式LoaderManager
,它使用AsyncTaskLoader
,CursorLoader
,和其他自定义Loader
实例处理数据加载。但是通过阅读这些文档,我只是无法理解这些观点:这些比使用旧的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会自动为你做,并且照顾正确创建和关闭光标的活动生命周期的基础上。
另请注意,使用此代码并不需要您认为确保长时间运行的工作是在主UI线程上执行的。 LoaderManager和CursorLoader负责所有这些工作,确保您在与光标交互时不会阻塞主线程。要正确地做到这一点,您实际上需要在点上同时激活两个Cursor对象,因此您可以继续使用当前光标显示交互式UI,而下一个显示正在加载。 LoaderManager为你做所有这些。
这只是一个非常简单的API--不需要了解AsyncTask并思考需要在后台运行什么,不需要考虑活动生命周期或如何在Activity中使用旧的“托管游标”API (无论如何,这并不像LoaderManager那样工作)。
(顺便说一下,不要忘记新的“支持”静,让您使用完整LoaderManager API在旧版Android下降到1.6库!)
很好的回答!是的,对于初学者来说,误用AsyncTask还是太容易了 - 它无法轻松处理配置更改,如果您需要在onProgressUpdate等中使用Context,以确保不会导致内存泄漏。 – 2011-04-09 09:06:20
也许是我,但这似乎不容易! – Ants 2011-11-24 03:36:09
@hackbod我已经尝试了Android 4.0和支持库,并且它看起来像cursor _is not_保留配置更改。我甚至发现了一个相关的bug:http://code.google.com/p/android/issues/detail?id=25112 – inazaruk 2012-04-05 09:15:18
- 1. LoaderManager的范围是什么?
- 2. 使用OHS 11g网络服务器的多个实例的优点是什么?
- 3. 那么Android 3.0中片段的确切优势是什么?
- 4. 使用Spring PropertySource的优点是什么?
- 5. 使用DataRelation的优点是什么?
- 6. 使用Signalr的优缺点是什么
- 7. 使用Object.assign()的优点是什么?
- 8. 使用“option explict”的优点是什么?
- 9. 使用automapper的优点是什么?
- 10. 为什么在使用点实例时使用按需实例
- 11. 实施单用户会话的优点和缺点是什么?
- 12. generator.throw()的优点是什么?
- 13. NSBinaryStoreType的优点是什么?
- 14. mysqli_stmt_bind_result的优点是什么?
- 15. RTSP的优点是什么?
- 16. PyTables的优点是什么?
- 17. AspectJ的优点是什么?
- 18. java中的匿名类的用例和优点是什么?
- 19. Sitecore:Sitecore.Web.WebUtil.Redirect优于Response.Redirect的优点是什么?
- 20. mootools优于jquery的优点是什么?
- 21. QAbstractItemModel优于QStandardItemModel的优点是什么?
- 22. 什么是使用大型CSS文件的优点和缺点?
- 23. @Autowired注释的优点是什么?
- 24. 使用依赖注入优于新的优点是什么?
- 25. 使用FutureTask优于Callable的优点是什么?
- 26. 使用特征优于抽象类的优点是什么?
- 27. 使用requireJS优化器时,buildlayered javascript的优点是什么?
- 28. 使用jQuery UI Position实用程序使用CSS位置的优点是什么?
- 29. Android +使用LoaderManager和ArrayAdapter?
- 30. IDE中实时协作的优点和缺点是什么?
退房[**这个岗位**](HTTP ://www.androiddesignpatterns.com/2012/06/app-force-close-honeycomb-ics.html)...第一部分列出了在不推荐的'startManagingCursor'上使用'LoaderManager'的优点... – user1422551 2012-08-03 22:46:47
[**了解'LoaderManager' **](http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html)是一个很好的学习文章。 – 2012-09-01 19:54:06