Android implementation of ListView paging method _android

Source: Internet
Author: User
Tags stub

This article illustrates how Android implements ListView paging. Share to everyone for your reference. The specific analysis is as follows:

Recently did the next ListView pagination, with pagination on the web is a meaning, the need for those several paging parameters, the difference is sqlite in the page of the query statement, simple method needs to use the Limit,offset keyword, the former is to query the number of records displayed on each page, the latter is over the number of records, To be clear is to ignore the number of rows in front of the record, how many rows to take

I used an important class page for pagination, passing it in as a parameter by encapsulating the page class, and returning it was also a Page object

Import java.util.Collections; 
Import java.util.List; 
 /** * Note that all serial numbers start at 1. 
 * * @param the type of record in page <T>. 
  * * * */public class Page<t> {//--common variable--//publicly static final String ASC = "ASC"; 
  public static final String DESC = "DESC"; --Paging parameter--//protected int pageno = 0;//The current page number < How to fetch the data > protected int pageSize = 1;//number of records per page protecte 
  D String by = null; 
  protected String order = null; 
  Protected Boolean autocount = true; 
  --Return results--//protected list<t> result = Collections.emptylist (); 
    protected long TotalCount = -1;//Total Record number//--constructor--//public page () {} public page (final int pageSize) { 
  SetPageSize (pageSize); 
    The public Page (final int pageSize, final Boolean autocount) {setpagesize (pageSize); 
  Setautocount (Autocount); 
   //--Access query parameter function--///** * Gets the page number of the current page, the ordinal number starts at 0, and the default is 0. 
  * * public int Getpageno () {return pageno; 
  /** * Sets the page number of the current page, starting at 0, and automatically adjusts to 0 when the number is below 0. * * public void Setpageno (final int pageno) {This.pageno = PageNo; 
    if (PageNo < 0) {This.pageno = 0; 
   /** * Gets the number of records per page and defaults to 1. 
  * * public int getpagesize () {return pageSize; 
   /** * Sets the number of records per page, automatically adjusts to 0 when less than 0. 
    * * public void setpagesize (final int pageSize) {this.pagesize = pageSize; 
    if (PageSize < 0) {this.pagesize = 0; 
   }/** * Calculates the position of the first record of the current page in the total result set according to PageNo and PageSize, and the ordinal number starts at 0. 
  * * public int GetFirst () {return (PageNo * pageSize) + 1; 
   /** * Gets the sort field with no default value. Multiple sort fields are separated by ', '. 
  */Public String Getorderby () {return by; 
   /** * Sets the sort field, with multiple sort fields separated by ', '. 
  */public void Setorderby (final String by) {This.orderby = by; 
   /** * Gets the sort direction. 
  */Public String GetOrder () {return order; 
   /** * Sets the Sort method. 
  * * @param an optional value of DESC or ASC/public void Setorder (String order) {This.order =;/** * Automatically executes the count query to retrieve the total number of records when querying an object, and defaults to false. 
  * * Public boolean Isautocount () {return autocount; 
   /** * Automatically executes a count query to get the total number of records when querying an object. 
  * * public void Setautocount (final Boolean autocount) {this.autocount = Autocount; 
   //--access the query result function--///** * Gets the list of records in the page. 
  * * Public list<t> GetResult () {return result; 
   /** * Sets the list of records within the page. 
  * * public void Setresult (final list<t> result) {This.result = result; 
   /** * Gets the total number of records, the default value is-1. 
  * * Public long Gettotalcount () {return totalcount; 
   /** * Sets the total number of records. 
  */public void Settotalcount (final long totalcount) {this.totalcount = TotalCount; 
   /** * Calculates the total number of pages based on pagesize and TotalCount, and the default value is-1. 
    */Public long gettotalpages () {if (TotalCount < 0) return-1; 
    Long Count = totalcount/pagesize; 
    if (totalcount% pageSize > 0) {count++; 
  return count; /** * Is there a nextPage. */public Boolean ishasnext () {return (PageNo + 1 < gettotalpages ()); 
   /** * Gets the page number of the next page and the serial number starts at 0. 
   * Still return last serial number when current page is last. 
    * * public int getnextpage () {if (Ishasnext ()) return PageNo + 1; 
  else return pageno; 
   /** * Whether there is a previous page. 
  * * Public boolean ishaspre () {return (pageNo-1 >= 0); 
   /** * Gets the page number of the previous page and the serial number starts at 1. 
   * The current page is returned to the first page number. 
    * * public int getprepage () {if (Ishaspre ()) return pageNo-1; 
  else return pageno; } 
}

The following is the encapsulated Pojo object, and the interface ListView item display relies on it

public class Record {private Integer rId; 
  Private String Fromuser; 
  Private String Touser; 
  Private String content; 
  Private String Rtime; 
  Private Integer isreaded; 
  Public Integer Getrid () {return rId; 
  The public void Setrid (Integer rId) {this.rid = RId; 
  Public String Getfromuser () {return fromuser; 
  } public void Setfromuser (String fromuser) {this.fromuser = Fromuser; 
  Public String Gettouser () {return touser; 
  } public void Settouser (String touser) {this.touser = Touser; 
  Public String getcontent () {return content; 
  public void SetContent (String content) {this.content = content; 
  Public String Getrtime () {return rtime; 
  } public void Setrtime (String rtime) {this.rtime = Rtime; 
  Public Integer getisreaded () {return isreaded; 
  The public void setisreaded (Integer isreaded) {this.isreaded = isreaded; }
}

Well, look at the important method in the DAO class is also the Page object, the action in the DAO class is to assign values to the total number of records and the result list

Public page<record> getrecordpage (page<record> Page, String loginName, string contactname) {int 
    PageSize = Page.getpagesize (); 
    int pageno = Page.getpageno (); String sql = "SELECT * from" + Contactsmanagerdbadapter.tablename_record + "where" (Fromuser =? and Touser =?) 
        or (Fromuser =? and Touser =?) " 
    + "Limit" + string.valueof (pageSize) + "Offset" + string.valueof (PageNo * pageSize); 
    String[] Selectionargs = {loginName, ContactName, ContactName, loginName}; 
    Cursor Cursor = msqlitedatabasewritable.rawquery (sql, Selectionargs); 
    list<record> result = new arraylist<record> (); 
      For (Cursor.movetofirst ();!cursor.isafterlast (); Cursor.movetonext ()) {The record record = The new record (); 
      Record.setrid (cursor.getint (0)); 
      Record.setfromuser (cursor.getstring (1)); 
      Record.settouser (cursor.getstring (2)); 
      Record.setcontent (Cursor.getstring (3)); ReCord.setrtime (Cursor.getstring (4)); 
      Record.setisreaded (Cursor.getint (5)); 
    Result.add (record); 
    } page.settotalcount (GetRowCount (LoginName, ContactName)); 
    Page.setresult (result); 
    Cursor.close (); 
return page; 
      /** * Total record number/public int getrowcount (string loginName, String contactname) {String sql = ' select * from ' + Contactsmanagerdbadapter.tablename_record + "where" (Fromuser =? and Touser =?) 
    or (Fromuser =? and Touser =?) "; 
    String[] Selectionargs = {loginName, ContactName, ContactName, loginName}; 
    Cursor Cursor = msqlitedatabasewritable.rawquery (sql, Selectionargs); 
    int count = Cursor.getcount (); 
    Cursor.close (); 
return count; 

 }

About listview Display and custom adapters, not mentioned here, in short the interface to the previous page and the Next button click event needs to refresh ListView

public class ChatHistory extends activity {ListView Historyview; 
  Button prevpagebtn; 
  Button nextpagebtn; 
  TextView Historypagetv; 
  Button backchatshistorybtn; 
  Button deletehistorybtn;  
  List<record> historyrecordlist; 
  Page<record> page; 
  String LoginName; 
  String ContactName; 
  Chathistoryservice Chathistoryservice; 
  Contactsmanagerdbadapter Dbadapter; 
  Private Baseadapter adapter; 
  private static final int status_change = 0; 
  Private Handler Mhandler; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method stub Super.oncre 
    Ate (savedinstancestate); 
    Setcontentview (r.layout.chats_history); Historyview = (ListView) Findviewbyid (Android. 
    R.id.list); 
    PREVPAGEBTN = (Button) Findviewbyid (r.id.chat_prev_page); 
    NEXTPAGEBTN = (Button) Findviewbyid (r.id.chat_next_page); 
    Historypagetv = (TextView) Findviewbyid (r.id.history_page); BACKCHATSHISTORYBTN = (Button) FindviewbyId (r.id.back_chats_history); 
    DELETEHISTORYBTN = (Button) Findviewbyid (r.id.delete_history); 
    Sharedpreferences sharedata = ChatHistory.this.getSharedPreferences ("Data", 0); 
    LoginName = sharedata.getstring ("LoginName", ""); 
    ContactName = Getintent (). Getstringextra ("ContactName"); 
    Dbadapter = new Contactsmanagerdbadapter (Getapplicationcontext ()); 
    Dbadapter.open ();
    Chathistoryservice = new Chathistoryservice (chathistory.this); 
    page = new page<record> (); 
    Page.setpagesize (8); 
    page = chathistoryservice.gethistorypage (page, LoginName, ContactName, dbadapter); 
    Historyrecordlist = Page.getresult (); 
    Updatetextview (); 
    Prevpagebtn.setonclicklistener (Prevpagebuttonlistener); 
    Nextpagebtn.setonclicklistener (Nextpagebuttonlistener); 
    Backchatshistorybtn.setonclicklistener (Backbuttonlistener); 
    Deletehistorybtn.setonclicklistener (Deletehistorybuttonlistener); 
    adapter = new Historylistadapter (chathistory.this); HIstoryview.setadapter (adapter); Mhandler = new Handler () {public void Handlemessage (msg) {switch (msg.what) {case S 
          Tatus_change://Handling UI updates and other operations UpdateUI (); 
    } 
       }; 
  }; 
  private void UpdateUI () {//Detailed update adapter.notifydatasetchanged ();//Update ListView Updatetextview (); /** * Update page number * * private void Updatetextview () {if (historyrecordlist.size () = 0) {Historypage 
    Tv.settext (0 + "/" + 0); 
    else{Historypagetv.settext (Page.getpageno () + 1 + "/" + page.gettotalpages ()); } public class Historylistadapter extends baseadapter{private class Recentviewholder {TextView Sende 
      R_context; 
    TextView Rtime; 
    Context context; 
    Layoutinflater Minflater; 
      Public Historylistadapter {this.context = context; Minflater = (layoutinflater) context.getsystemservice (context.layout_infLater_service); @Override public int GetCount () {//TODO auto-generated a stub return historyrecordlist.si 
    Ze (); @Override public Object getitem (int position) {//TODO auto-generated method stub return Histor 
    Yrecordlist.get (position); @Override public long getitemid (int position) {//TODO auto-generated method stub return Positi 
    On @Override public View getview (int position, View Convertview, ViewGroup parent) {//TODO auto-generate 
      D method stub Recentviewholder holder; 
        if (Convertview = = null) {Convertview = minflater.inflate (r.layout.message_layout, NULL); 
        Holder = new Recentviewholder ();
        Holder.sender_context = (TextView) convertview. Findviewbyid (r.id.message_view_sender_content); 
        Holder.rtime = (TextView) convertview. Findviewbyid (R.id.message_view_timestamp); convertview.seTtag (holder); 
      else {holder = (Recentviewholder) convertview.gettag (); 
      The Record record = Historyrecordlist.get (position); 
        if (record!= null) {Holder.sender_context.setText (Record.getfromuser () + ":" + record.getcontent ()); 
      Holder.rTime.setText (Record.getrtime ()); 
    return convertview; 
    }/** * Previous-page button listener Event/Onclicklistener Prevpagebuttonlistener = new Onclicklistener () {@Override public void OnClick (View v) {//TODO auto-generated Method stub if (Page.ishaspre ()) {PAGE.SETPA 
        Geno (Page.getpageno ()-1); 
        historyrecordlist = chathistoryservice.gethistorypage (page, LoginName, ContactName, Dbadapter). GetResult (); 
        msg = new Message (); 
        Msg.what = Status_change; 
  Mhandler.sendmessage (msg);//Send message to handler, update UI}}}; /** * Next Page button Monitor event * * Onclicklistener Nextpagebuttonlistener = new Onclicklistener (){@Override public void OnClick (View v) {//TODO auto-generated Method stub if (Page.ishasnext ()) { 
        Page.setpageno (Page.getpageno () + 1); 
        historyrecordlist = chathistoryservice.gethistorypage (page, LoginName, ContactName, Dbadapter). GetResult (); 
        msg = new Message (); 
        Msg.what = Status_change; 
  Mhandler.sendmessage (msg);//Send message to handler, update UI}}}; 
    /** * Delete History button listener/Onclicklistener Deletehistorybuttonlistener = new Onclicklistener () {@Override 
  public void OnClick (View v) {//TODO auto-generated Method stub}}; /** Exit Chat Interface Listener */Onclicklistener Backbuttonlistener = new Onclicklistener () {@Override public void OnClick (V 
      Iew v) {//TODO auto-generated Method Stub//return to chat interface finish (); 
    Dbadapter.close (); 
  } 
  }; @Override public boolean onKeyDown (int keycode, keyevent event) {//press the return button on the keyboard if (keycode = = Keyevent.keycode_back) 
      {Finish (); 
      Dbadapter.close (); 
    return true; 
    else {return Super.onkeydown (KeyCode, event); }
  }
}

On the previous page, the next page of the action is to determine whether there is a previous page and the next page in the case of the page number PageNo add and subtract operation
Finally, writing Chathistoryservice.java always feels superfluous.

public class Chathistoryservice {context context 
  ; 
  Public Chathistoryservice { 
    This.context = context; 
  } 
  Public page<record> gethistorypage (page<record> Page, String loginName, 
      string ContactName, Contactsmanagerdbadapter dbadapter) { 
    Recorddao Recorddao = new Recorddao (dbadapter); 
    return Recorddao.getrecordpage (page, LoginName, ContactName); 
  } 
  public int Deletehistory (string loginName, 
      string ContactName, Contactsmanagerdbadapter dbadapter) { 
    Recorddao Recorddao = new Recorddao (dbadapter); 
    Return Recorddao.deletehistoryrecord (LoginName, ContactName); 
  } 
 

Let's put an XML layout file on it.
Chats_history.xml

<?xml version= "1.0" encoding= "UTF-8"?> <!--and Friends Chat window. xml--> <linearlayout xmlns:android= "http:// Schemas.android.com/apk/res/android "android:orientation=" vertical "android:layout_width=" Fill_parent "Android: layout_height= "Fill_parent" android:background= "@color/white" > <listview android:id= "@android: Id/list" Android:layout_width= "Fill_parent" android:layout_height= "200dip" android:layout_weight= "1" android:transcriptMo De= "Normal" android:fadingedge= "None" android:padding= "4px" android:fastscrollenabled= "true" Android:smoothscrol Lbar= "false" android:focusable= "true" android:dividerheight= "0dip" android:cachecolorhint= "#00000000" Android:di vider= "@drawable/divider"/> <!--reference chat content. xml--> <linearlayout android:layout_width= "Fill_parent" a ndroid:layout_height= "50.0dip" android:orientation= "horizontal" android:background= "#ccc" android:paddingleft= " 3dip "android:paddingtop=" 3dip > <buttOn android:id= "@+id/chat_prev_page" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:background= "@drawable/chat_prev_page"/> <textview android:id= "@+id/history_page" Android:layout_ Width= "30.0dip" android:layout_height= "25.0dip" android:gravity= "center" android:text= "1/1"/> <bu Tton android:id= "@+id/chat_next_page" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" and roid:background= "@drawable/chat_next_page"/> <button android:id= "@+id/delete_history" android:layout_width= 
    "Wrap_content" android:layout_height= "wrap_content" android:background= "@drawable/delete_history_button"/> <button android:id= "@+id/export_history" android:layout_width= wrap_content "android:layout_height=" Wrap_conte 
      NT "android:background=" @drawable/export_history_button "/> <button android:id=" @+id/back_chats_history " Android:layout_width= "Wrap_contenT "android:layout_height=" wrap_content "android:background=" @drawable/back_btn "/> </LinearLayout> ;/linearlayout>

Message_layout.xml

<?xml version= "1.0" encoding= "UTF-8"?> 
<!--message content display--> <linearlayout 
xmlns:android= 
 " Http://schemas.android.com/apk/res/android " 
 android:layout_width=" fill_parent " 
 android:layout_height=" Wrap_content " 
 android:orientation=" vertical " 
 > 
 <!--android:background=" @drawable/item_style " --> 
  <textview android:id= "@+id/message_view_sender_content" 
    android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" 
    android:autolink= "all"/> 
  <textview android:id= "@+id/ Message_view_timestamp " 
    android:layout_alignparentright=" true "android:layout_width=" Wrap_content 
    " android:layout_height= "Wrap_content" android:layout_below= "@+id/message_view_message" 
    android:layout_ gravity= "right"/> 
</LinearLayout> 

Finally look at the effect of it, don't bully me not to put the database to build a table statement, look at my Pojo class to know my database table how to build

I hope this article will help you with your Android program.

Related Article

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.