The previous two articles respectively introduced the implementation of Onscrolllistener and the change of contentprovider monitoring data, below we have two knowledge points to achieve a small project
Project requirements
Use when the ContentProvider listener class has data updates, prompt at the current interface, and implement a pull-down refresh with Onscrolllistener
Achieve results
Display data via ContentProvider in the interface
When the listener class is changed
Display data after a drop-down refresh
Implementation steps
- Android_sqlite Project
- Defining an Action ID
- Match result Code
- Inheriting the ContentProvider class override method
- OnCreate Initializing Data Databasehelper
- GetType
- Returns the type of operation if you manipulate multiple records then mine type vnd.android.cursor.dir/begins
- If the data for the operation has only one record then mine type vnd.android.cursor.item/start
- Insert
- Match URI
- Insert operation
- Monitor data changes
- Update
- Match multiple data or 1 data
- Update action
- Monitor data changes
- Query
- Match multiple data or 1 data
- Query operations
- Delete
- Match multiple data or 1 data
- Delete operation
- Monitor data changes
Android_providers Project
- Get Control Object
- Listview
- Tv_tip,tv_name,tv_phone
- Get Content Parser Object
- Initializing data
- Executing a query from a content parser object
- Set Adapter
- Register Listener
- New class inherits Contentobserver classes
- Binding Handler Objects
- Processing data on request
- Overriding the onchange (Booleab selfchange) method to send a handler message
- Implement the Onscrolllistener interface and implement the method
- Onscroll
- Onscrollstatechanged
- Initializing data
- Hide Tip
Key code: The Usercontentproviders class in the Android_sqlite projectPackage Com.example.android_sqlite.provider;import Com.example.android_sqlite.database.databasehelper;import Android.content.contentprovider;import Android.content.contenturis;import Android.content.contentvalues;import Android.content.urimatcher;import Android.database.cursor;import Android.database.sqlite.sqlitedatabase;import Android.net.uri;public class Usercontentproviders extends ContentProvider {//action flag private static final String Authoritie = "Www.csdn.com.provider.userContentProvider";//defines the matching code returned by URI resolution private static final int usercode = 1;private static final int userscode = 2;private static Urimatcher urimatcher;private String users_dir = "Vnd.android.cursor.dir/use Rs ";p rivate String users_item =" Vnd.android.cursor.item/users ";p rivate databasehelper dh;static {// Instantiate the Urimatcher object urimatcher = new Urimatcher (urimatcher.no_match);//Match the result code Urimatcher.adduri (Authoritie, "users", Userscode); Urimatcher.adduri (Authoritie, "users/#", Usercode);} /** * After Usercontentprovider is created, it is called when otherWhen the program accesses Contentprivider for the first time, the ContentProvider will be created */@Overridepublic Boolean onCreate () {dh = new Databasehelper ( GetContext ()); return false;} /** * url:http://www.baidu.com/index.html: HTTP protocol Access website * www.baidu.com: Domain part/index.html: site Resources * URI:CONTENT://WW W.csdn.com.provider.usercontentprovider/user * Content://android's ContentProvider rules * Www.csdn.com.provider.userContentProvider: Authorities * User: Resource section (Data section) in a file sink when a visitor needs to access a different resource This part is a dynamic change. This section can be defined by itself * * Urimatcher: Match Uri *//** * Query method */@Overridepublic Cursor query (Uri uri, string[] projection, Strin G selection,string[] Selectionargs, String sortOrder) {sqlitedatabase db = Dh.getwritabledatabase (); Cursor C = Null;switch ((Urimatcher.match (URI))) {Case usercode://an entry long id = Contenturis.parseid (URI); c = Db.query ("Us ERs ", projection," userid= ", new string[] {id+" "}, NULL, NULL, sortOrder); Break;case userscode:c = Db.query (" Users ", p Rojection, Selection, Selectionargs, Null,null, SortOrder); Break;default:throw new illegalArgumentException ("unknow uri" + uri);} return c;} /** * Returns the type of operation if you manipulate multiple records then mine type vnd.android.cursor.div/start * If the data for the operation has only one record then mine type vnd.android.cursor.item/start */@ Overridepublic string GetType (Uri uri) {String value = Null;switch (Urimatcher.match (URI)) {Case Usercode:value = Users_it Em;break;case userscode:value = Users_dir;break;} return null;} /** * Insert operation */@Overridepublic URI insert (URI uri, contentvalues values) {if (Urimatcher.match (URI)! = Userscode) {throw new IllegalArgumentException ("unknow uri" + uri);} Sqlitedatabase db = Dh.getreadabledatabase (), Long rowId = Db.insert ("Users", "username", values);//monitor data changes, Notifies listeners registered on the URI//parameter 1: Registered URI, Parameter 2: Listener GetContext (). Getcontentresolver (). Notifychange (URI, null); return Contenturis.withappendedid (URI, rowId);} /** * Update operation */@Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {Sqlitedat Abase db = Dh.getwritabledatabase (); int rows = -1;switch ((Urimatcher.match (URI))) {Case usercode://an entry long id = ContenTuris.parseid (URI); rows = Db.update ("Users", values, "Userid=?", new string[] {id+ ""});d B.close (); Break;case Userscode : rows = Db.update ("Users", values, selection, Selectionargs); Break;default:throw new IllegalArgumentException ("Unknow uri "+ uri);} GetContext (). Getcontentresolver (). Notifychange (URI, null); return rows;} /** * Delete operation */@Overridepublic int Delete (URI Uri, String selection, string[] selectionargs) {Sqlitedatabase db = Dh.getwrit Abledatabase (); int rows = -1;switch ((Urimatcher.match (URI))) {Case usercode://an entry long id = Contenturis.parseid (URI); rows = Db.delete ("Users", "Userid=?", new string[] {id + "}");d b.close (); Break;case userscode:rows = Db.delete ("Users", Selection, Selectionargs); Break;default:throw new IllegalArgumentException ("Unknow uri" + uri);} GetContext (). Getcontentresolver (). Notifychange (URI, null); return rows;}}
Android_providers Project Layout File Activity_main.xml<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:paddi ngbottom= "@dimen/activity_vertical_margin" android:paddingleft= "@dimen/activity_horizontal_margin" Android: paddingright= "@dimen/activity_horizontal_margin" android:paddingtop= "@dimen/activity_vertical_margin" tools: Context= ". Mainactivity "> <textview android:id=" @+id/tv_tip "android:layout_width=" Match_parent "Andro id:layout_height= "Wrap_content" android:layout_marginbottom= "15DP" android:gravity= "center" android:t Extcolor= "#FF0000" android:visibility= "Gone"/> <listview android:id= "@+id/lv_users" Android : layout_width= "match_parent" android:layout_height= "match_parent" android:layout_below= "@+id/ll_title" android:layout_margintop= "5DP" > </listview> <linearlayout android:id= "@+id/ll_title" android:layout_width= "Match_parent" Android:lay out_height= "Wrap_content" android:layout_below= "@+id/tv_tip" android:orientation= "Horizontal" > &L T TextView android:layout_width= "100DP" android:layout_height= "Wrap_content" android:text= " Name "/> <textview android:layout_width=" wrap_content "android:layout_height=" Wrap_conten T "android:text=" phone "/> </LinearLayout></RelativeLayout>
Item_phone.xml<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android " android:id=" @+id/ll_title " android:layout_width=" wrap_content " android:layout_height=" Wrap_content " android:orientation=" Horizontal "> <textview android:id=" @+id/tv_name " Android:layout_width= "100DP" android:layout_height= "wrap_content" android:text= "TextView" android: layout_margintop= "5DP" android:layout_marginbottom= "5DP"/> <textview android:id= "@+id/tv_ Phone " android:layout_width=" wrap_content " android:layout_height=" wrap_content " android:text=" TextView " android:layout_margintop=" 5DP " android:layout_marginbottom=" 5DP "/></linearlayout>
Android_providers Project Mainactivity Package Com.example.android_providers;import Android.app.activity;import Android.content.contentresolver;import Android.database.contentobserver;import Android.database.cursor;import Android.net.uri;import Android.os.Bundle; Import Android.os.handler;import Android.os.message;import Android.support.v4.widget.simplecursoradapter;import Android.view.view;import Android.widget.abslistview;import Android.widget.abslistview.onscrolllistener;import Android.widget.listview;import Android.widget.textview;public class Mainactivity extends Activity implements Onscrolllistener {private ListView lv_users;private TextView tv_tip;private simplecursoradapter adapter;private Contentresolver contentresolver;private static final String URL = "content:// Www.csdn.com.provider.userContentProvider/users ";p ublic static final int INSERT = 1;private Boolean flag = False;private Boolean islastrow = false; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); SetcontentvieW (r.layout.activity_main); lv_users = (ListView) Findviewbyid (r.id.lv_users); tv_tip = (TextView) Findviewbyid (r.id.tv _TIP);//Get content Parser Object contentresolver = Getcontentresolver (); initdate ();//Register Listener Getcontentresolver (). Registercontentobserver (Uri.parse (URL), True,new Usercontentobserver (handler)); Lv_users.setonscrolllistener (this );} /* * Initialize data */private void Initdate () {//execute query cursor c = contentresolver.query (Uri.parse (URL), new string[] {"UserID as _id "," username "," Userphone "}, NULL, NULL," UserID desc ");//Control Layer adapter = new Simplecursoradapter (This, r.layout.item_phone , C,new string[] {"username", "Userphone"}, new int[] {r.id.tv_name, R.id.tv_phone},simplecursoradapter.flag_register_ Content_observer); Lv_users.setadapter (adapter);} Class Usercontentobserver extends Contentobserver {private Handler handler;public usercontentobserver (Handler Handler) {super (handler); this.handler = handler;} @Overridepublic void OnChange (Boolean selfchange) {Super.onchange (selfchange);//Send Empty message handler.sendempTymessage (INSERT);}} Private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {super.handlemessage (msg); Switch (msg.what) {case INSERT:tv_tip.setVisibility (view.visible); flag = True;tv_tip.settext ("There is new information, drop-down load ..."); break;default:break;}}};/ * * View Firstvisibleitem The position of the first displayed entry (subscript starting from 0) visibleitemcontent * Number of items visible (contains not shown full) Totalvisibleitem total number of bars (subscript starting from 0) */@ overridepublic void Onscroll (abslistview view, int firstvisibleitem,int visibleitemcontent, int totalvisibleitem) {if ( Firstvisibleitem + visibleitemcontent) >= totalvisibleitem&& totalvisibleitem > 0) {//send request handling Islastrow = TR UE;}} The callback is being scrolled, the callback is 2-3 times, and the finger does not throw the callback 2 times. Scrollstate = 2 does not callback//callback order as follows//1th time: Scrollstate = Scroll_state_touch_scroll (1) is scrolling when the screen scrolls and the user uses a touch or finger still on the screen// 2nd time: Scrollstate = scroll_state_fling (2) The finger does the throwing action (the finger leaves the screen, the force slides a bit)//3rd time: scrollstate = scroll_state_idle (0) Stop scrolling @overridepublic void onscrollstatechanged (abslistview view, int scrollstate) {//(with new messages) when the update loads the data if (flag && SCrollstate = = onscrolllistener.scroll_state_fling) {//Initialize data initdate (); flag = false;tv_tip.setvisibility (View.GONE);} if (islastrow && scrollstate = = onscrolllistener.scroll_state_fling) {//Data Processing}}}
Reprint please indicate address
http://blog.csdn.net/zhaoyazhi2129/article/details/30064965