At the beginning of android3.0, a new loader was added. Loader the way the data is loaded is asynchronous.
Features of loader:
1. Suitable for activity and fragment
2. Provides an asynchronous load data mechanism
3. Monitor the data source and pass new results when the data source changes
4. Automatically reconnect to the last data Loader cursor, no need to requery the data
Usage: monitor data sources, such as ContentProvider.
Cursorloader is a subclass of Asynctaskloader, Asynctaskloader will provide asyntask to operate. Therefore, the UI thread is not blocked.
Example: Get mobile phone number
public class Mainactivity extends Listactivity implements loadercallbacks<cursor> {
Listactivity can not write Setcontentview (R.layout.activity_main) because it contains a default layout.
Listactivity android:id= "@android: Id/list" for the ListView in the corresponding layout
public static final int ID = 110;
Simplecursoradapter adapter;
string[] showcontent = new string[] {
Phone.number};
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
adapter = new Simplecursoradapter (This,
Android. R.layout.simple_list_item_1, NULL, Showcontent,
New int[] {Android. R.ID.TEXT1});
Setlistadapter (adapter);
Parameters: Id,bundle Object (second parameter in Oncreateloader (),loadercallbacks<d> Object
Getloadermanager (). Initloader (ID, NULL, this);
}
@Override
public boolean Oncreateoptionsmenu (Menu menu) {
Getmenuinflater (). Inflate (R.menu.main, menu);
return true;
}
//Create loader object, Cursorloader object (features with Asynctask) will loads the data in the background line, and finally return a cursor
public loader<cursor> oncreateloader (int arg0, Bundle arg1) {
uri Uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
//If Java.lang.IllegalArgumentException:column ' _id ' does not exist appears,
//is string[] projection not written in ' _id '.
//simplecursoradapter is displayed according to ' _id ' when displayed. Therefore cannot have ' _id '
cursorloader loader = new Cursorloader (this, URI, NULL, NULL,
NULL, NULL);
return Loader;
}
Loader is called when the data has been read for the first time, or when the data source has changed
public void onloadfinished (loader<cursor> Loader, cursor cursor) {
A loadermanager can manage multiple loader, so the ID of the loader is judged
Switch (Loader.getid ()) {
Case ID:
Load query to data on ListView
Adapter.swapcursor (cursor);
Break
Default
Break
}
}
@Override
public void Onloaderreset (loader<cursor> arg0) {
Adapter.swapcursor (null);//Remove reference
}
}
Loader Loading Data asynchronously