http://blog.163.com/cazwxy_12/blog/static/898763720122721228265/
Loaders,中文可理解为“加载器”,在Android3.0中新增。从字面含义可见其功能,即提供数据加载。特别地,加载数据的方式为异步。它具有以下特点:
l Loaders用于所有的Activity和Fragment;
l 提供异步数据装载机制;
l 监控他们的来源数据变化情况,在数据发生变化的时候传递新的结果;
l 自动重连到最后一个数据加载器游标,因此不需要重新查询数据
使用Loaders的先决条件:
l 需要一个Activity 或者 Fragmnet
l 一个LoaderManager实例
l 一个用于加载数据的的CursorLoader对象(依赖于ContentProvider)
l 一个LoaderManager.LoaderCallbacks的实现类.
l 一个数据展现适配器,比如SimpleCursorAdapter
l 一个数据源,比如ContentProvider
LoaderManager管理者一个Activity或者Fragment中的一个或多个Loader实例,每个Activity或者Fragment只有对应一个LoaserManager。
一般在Activity的onCreate方法或者Fragment的onActivityCreated方法中初始化一个Loader:
getLoaderManager().initLoader(0, null, this);
参数:
1、 第一个参数:0 为Loader的唯一标识ID;
2、 第二个参数: 为Loader的构造器可选参数,这里为null;
3、 第三个参数:this,这里表示当前Activity对象或者Fragment对象,提供给LoaderManager对象进行数据汇报。
InitLoader()方法保证了Loader初始化及对象激活,执行这个方法有2个可能的结果:
1、 如果ID存在,则重复利用;
2、 如果ID不存在,则出发LoaderManager.LoaderCallbacks的onCreateLoader()方法新创建一个Loader并返回;
不管在什么情况下,只有Loader状态发生了变化,与之关联的LoaderManager.LoaderCallbacks实现类都会被告知;
你可能注意到了,initLoader返回的Loader对象并未与任何变量关联,那是因为LoaderManager有自动的Loader管理功能;LoaderManager在必要的时候自动启动及停止数据加载操作,并且维护者Loader的状态;这就意味着,你很少直接与Loader进行交互。一般地,使用LoaderManager.LoaderCallbacks的onCreateLoader()方法去干预数据加载的过程中的特殊事件。
在上面创建Loaders时,如果ID不存在则创建,否则使用旧的Loader,但有些时候,我们需要清理掉旧的数据重新开始。
使用restartLoaser()可以做到。比如,SearchView.OnQueryTextListener的实现类,在查询条件发生改变时重启Loaders,以便获取最新的查询结果。
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.LoaderCallbacks 接口是客户端与LoaderManager进行交互的腰带。
Loader ,特别是CursorLoader,期望在停止状态后保存它们的状态。这样的话,用户在交互过程中,就避免了数据的重新加载而导致UI卡死的局面。使用回调函数,就可以知道什么时候去创建一个新的Loader,并且告知应用程序什么时候停止使用Loader加载的数据。
回调方法有:
l onCreateLoader():根据给定的ID创建新的Loader;
l onLoaderFinished():当Loader完成数据加载后调用;
l onLoaderReset():Loader重置,使之前的数据无效;
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(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)构造器参数解释:
Context:上下文,这里是Activity对象或者Fragment对象
Uri:内容检索地址
Projection:要显示的列,传null表示查询所有的列
Selection:查询过滤语句,类似SQL WHERE ,传null,表示查询所有
selectionArgs:查询参数,替换在selection中定义的 ?
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);
}}