Querying local database usage in real time using loader

Source: Internet
Author: User
Tags static class

When I look at the Android document, I see something like this: Loader

What the hell is that thing?

Introduced in Android 3.0, loaders make it easy-asynchronously load data in an activity or fragment. Loaders have these characteristics:

1, they is available to every Activity and Fragment. Support Activity and fragment

2, they provide asynchronous loading of data. can be downloaded asynchronously

3. They monitor the source of their data and deliver new results when the content changes. Notifies clients promptly when data sources change

4, they automatically reconnect to the last loader's cursor when being recreated after a configuration change. Thus, they don ' t need to re-query their data. Automatic reconnection when configuration change occurs

Loader technology provides us with the following core classes:

    • Loadermanager: Can be loadermanager by activity or the Getloadermanager () method of fragment, used to manage loader, An activity or fragment can only have one loadermanager.
    • Loadermanager.loadercallbacks: Used to interact with Loadermanager, where you can create loader objects.
    • Asynctaskloader: Abstract class, can be asynchronous loading data loader, seemingly internal also through Asyntask implementation, you can inherit it to build their own loader, you can also use the existing subclasses, For example, an asynchronous query database can use Cursorloader.

      The following steps can generally be used with loader:

      1, initialize the loader, you can use Initloader (IntID, Bundle args, Loadermanager.loadercallbackscallback) method to initialize.
      ID: Identifies the ID of the loader, an activity or fragment can have only one loadermanager, but may have multiple loader, differentiated by ID. When you create a new loader, if you find a loader that already has the same ID, the loader will be reused and not recreated.
      Args: Parameters passed to the new loader.

      Callback: Callback interface.

      2, the implementation of Loadermanager.loadercallbacks in the method, loadermanager.loadercallbacks need to implement the methods are:
      Publicloader oncreateloader (int id, Bundle args): Creates a new loader,id for Loaderid, and if a loader already has the same ID, the loader will be reused and will not be recreated. Args is the parameter passed at initialization time. The method begins an asynchronous query and returns a generic class, and if the query database can return a cursorloader, the custom loader can be returned. Public voidonloadfinished (Loader Loader, D data): This method is called at the end of the asynchronous query and returns the query result data. public void Onloaderreset (Loader Loader): The Loader () method is automatically called when Loader.reset () is called to empty the Loader data, but when the system destroys Loader.reset We generally do not need to call manually, only in the Onloaderreset method, you will use the loader removal.

      3, using Restartloader (IntID, Bundle args, Loadermanager.loadercallbacks callback) method for data update, and initialization of a, if there is the same ID loader exist, The loader is reused and the data in the original loader is emptied, and if not, a new one is created. This method is typically used when you need to update the data, for example, in the following example, when searching for key changes, you need to call this method to query the data from the new asynchronous.

public class Collectdetail extends Activity implements loadercallbacks<cursor> {

Private ListView ListView;
Private Simplecursoradapter adapter;
Private Loadermanager Loadermanager;
Private Mysqliteopenhelper Openhelper;
private static Sqlitedatabase db;
Private TextView Textview_empty;

@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);

Remove title bar
Requestwindowfeature (Window.feature_no_title);
Setcontentview (R.layout.activity_collect_detail);

Openhelper = new Mysqliteopenhelper (this);

Get DB Object
db = Openhelper.getwritabledatabase ();

ListView = (ListView) Findviewbyid (R.id.collect_listview);
Textview_empty = (TextView) Findviewbyid (r.id.textview_collect_empty);//When the ListView is empty

Create adapter (data is null "NULL" at this time)
adapter = new Simplecursoradapter (this, r.layout.collect_listview_item, NULL, new String []{"title", "nickname", "Create _time "}, New Int[]{r.id.collect_item_title,r.id.collect_item_nickname,r.id.collect_item_create_time}, Cursoradapter.flag_register_content_observer);

Listview.setadapter (adapter);

Listview.setemptyview (textview_empty);//Setting the view displayed when no data is set

Get Loadermanager Manager Object
Loadermanager = Getloadermanager ();
Initialize Loader

The first parameter is used to mark a loader. Because Loadermanager can manage multiple loader

The second parameter, "Bundle args", is a query condition, and unconditional is null.

The third parameter is the callback method (loadercallbacks<cursor>) after the initialization of loader, which typically allows the activity to be implemented at this time


Loadermanager.initloader (1, null,this);

Click on the ListView setting entry to display the data
Listview.setonitemclicklistener (New Onitemclicklistener () {

@Override
public void Onitemclick (adapterview<?> parent, view view,
int position, long ID) {
// Jump to Details interface
String sql = "Select _id,title,nickname,create_time,flag from collect";

Cursor cursor = db.rawquery (sql, NULL);
Cursor.movetoposition (position);//move cursor cursor to this position position

//Get more information about this entry from the cursor
String _id = cursor.getstring (Cursor.getcolumnindex ("_id"));
String title = cursor.getstring (Cursor.getcolumnindex ("title"));
String nickname = cursor.getstring (Cursor.getcolumnindex ("nickname"));
String create_time = cursor.getstring (Cursor.getcolumnindex ("Create_time"));
int flag = Cursor.getint (Cursor.getcolumnindex ("flag"));

Intent Intent = new Intent ();
Bundle Bundle =new Bundle ();
Bundle.putstring ("id", _id);
Bundle.putstring ("title", title);
Bundle.putstring ("nickname", nickname);
Bundle.putstring ("Create_time", create_time);
Bundle.putint ("flag", flag);
Intent.putextras (bundle);

Intent.setclass (Collectdetail.this, itemlistview.class);

StartActivity (Intent);


}
});

Register context menu to delete this entry and implement update data on the ListView
Registerforcontextmenu (listview);



}
Create a context Menu

@Override
public void Oncreatecontextmenu (ContextMenu menu, View V,
Contextmenuinfo menuinfo) {
Getmenuinflater (). Inflate (R.menu.collect_listview, menu);
Super.oncreatecontextmenu (menu, V, menuinfo);
}
When the entry in the context menu is clicked, delete this entry and restart Loader
@Override
public boolean oncontextitemselected (MenuItem item) {

Adaptercontextmenuinfo Menuinfo = (adaptercontextmenuinfo) item.getmenuinfo ();
int position = Menuinfo.position;

cursor cursor = adapter.getcursor ();//Get to Cursor from adapter

Cursor.movetoposition (position);
String _id = cursor.getstring (Cursor.getcolumnindex ("_id"));//The _id that gets to this location information is more _id to delete

String sql = "Delete from collect where _id= '" "+_id+" ";
Db.execsql (SQL);

Loadermanager.restartloader (1, NULL, this);//restart via Loadermanager Loader
return super.oncontextitemselected (item);
}

3 methods that must be executed when an interface callback is executed

First get to Loader object

@Override
Public loader<cursor> oncreateloader (int id, Bundle args) {
Myasynctaskloader loader = new Myasynctaskloader (this);
return loader;
}

The method that is called when the data is loaded, which causes the adapter to displace the data as "data"

@Override
public void onloadfinished (loader<cursor> Loader, Cursor data) {


Adapter.swapcursor (data);

}

when the loader restart is the method called, the data in the adapter is replaced with an empty

@Override
public void Onloaderreset (loader<cursor> Loader) {

Adapter.swapcursor (NULL);

}

write a class that inherits Asynctaskloader<cursor> ( This class must be defined as static type )
public static class Myasynctaskloader extends asynctaskloader<cursor>{

Public Myasynctaskloader (Context context) {
Super (context);
TODO auto-generated Constructor stub
}
@Override
protected void onstartloading () {
TODO auto-generated Method Stub
Super.onstartloading ();
  forceload (); This method must be written so that it can be executed down Loadinbackground
}

@Override
Public Cursor Loadinbackground () {
String sql = "Select _id,title,nickname,create_time from collect";
Cursor cursor_collect = db.rawquery (sql, NULL);

return cursor_collect;
}

}


}

Use loader to query local database usage in real time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.