Android ListView Page Load (server side +android) Demo

Source: Internet
Author: User

Android ListView page Loading function is often used in the actual development, is the content that each developer must master, this demo gives the service end of the +android end of the code, and successfully passed the test.

The server uses eclipse with the myeclipse,android-side.

Realize:

The server has a total of 100 data, divided into four pages, each page has 25 data.


Source:

Service side:

You need to import these jar packages in the diagram.


Before running the Android terminal code, you need to open the server:


The following first gives the server code:

Class Empdatasource:

Package Com.android.divpage;import java.util.arraylist;import java.util.list;/** * Server data * @author Administrator * */ public class Empdatasource {list<string> list, public list<string> Getdatasource () {list = new arraylist< String> (); for (int i = 0; i <; i++) {List.add ("Hellonihao" +i);} return list;}}

Devidepage:

Package Com.android.divpage;public class Devidepage {private int pagesize;//the number of bars displayed per page private int recordcount;// Total number of records private int currentpage;//current page private int pagecount;//total pages public devidepage (int pageSize, int recordCount, int curre Ntpage) {this.pagesize = Pagesize;this.recordcount = Recordcount;this.setcurrentpage (currentPage);} public int getpagesize () {return pageSize;} public void setpagesize (int pageSize) {this.pagesize = pageSize;} public int GetRecordCount () {return recordCount;} public void Setrecordcount (int recordCount) {this.recordcount = RecordCount;}  /** * Get total pages */public int Getpagecount () {PageCount = recordcount/pagesize;int mod = recordCount% pagesize;if (mod! = 0) {pagecount++;} return PageCount = = 0? 1:pagecount;} public void Setpagecount (int pagecount) {this.pagecount = PageCount;} public int getcurrentpage () {return currentpage;} /** * Set positioning on the current page */private void setcurrentpage (int currentpage) {int activepage = currentpage <= 0? 1:currentpage;acti Vepage = ActivepagE > Getpagecount ()? Getpagecount (): Activepage;this.currentpage = ActivePage;} public int Getfromindex () {return (currentPage-1) * pageSize;} public int Gettoindex () {return math.min (RecordCount, currentpage * pageSize);}}

Empaction:

Package Com.android.divpage;import Java.io.ioexception;import Java.io.printwriter;import java.util.List;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Net.sf.json.JSONArray ;p ublic class Empaction extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) Throws Servletexception, IOException {this.dopost (request, response);} Jsonarray array = null;public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("Text/html;charset=utf-8"); Request.setcharacterencoding (" Utf-8 "); Response.setcharacterencoding (" Utf-8 "); PrintWriter writer = Response.getwriter (); Empdatasource DataSource = new Empdatasource ();/** * Get data from Empdatasource class */list<string> list = Datasource.getdatasource (); String PageNo = Request.getparameter ("PageNo"); int currentpage = 1;//The current page is the firstPage if (PageNo! = null) {currentpage = Integer.parseint (PageNo);} /** * Page: There are 25 data per page, because there are 100, so there are a total of 4 pages. */devidepage putil = new Devidepage (+ list.size (), currentpage); int start = Putil.getfromindex (); int end = Putil.gettoin Dex (); list<string> sublist = list.sublist (start, end); array = Jsonarray.fromobject (sublist); writer.println (array); Writer.flush (); Writer.close ();}}


Android side;

Layout file:

<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:paddingbottom= "@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 ">    <listview        android:id=" @+id/listview "        android:layout_width=" Match_parent "        android:layout_height= "match_parent"        android:layout_alignparenttop= "true"        android:layout_ Centerhorizontal= "true" >    </ListView></RelativeLayout>

Mainactivity:

Remember to change the IP address in the path to your own native IP address.

Package Com.listviewdemo_divpage;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.util.arraylist;import Java.util.list;import Org.apache.http.HttpResponse; Import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httpget;import Org.apache.http.impl.client.defaulthttpclient;import Org.json.jsonarray;import Org.json.JSONException;import Android.app.activity;import Android.app.progressdialog;import Android.os.asynctask;import Android.os.Bundle; Import Android.view.view;import Android.view.viewgroup;import Android.widget.abslistview;import Android.widget.abslistview.onscrolllistener;import Android.widget.baseadapter;import Android.widget.ListView; Import Android.widget.textview;import Android.widget.toast;public class Mainactivity extends Activity {private String Emp_path = "http://172.16.17.36:8080/JsonServiceDemo/servlet/EmpAction?pageNo=";p rivate ListView listview;private Myadapter Adapter;private Boolean Is_divpage;//Whether to do paging operation private list<string> onetotal = new arraylist<string> ();//For storing a page of data private list<string> Total = new arraylist<string> ();//used to store all data obtained private progressdialog dialog;private static int pageno = 1;// Set the initialization value of PageNo to 1, which is the first page of data obtained by default. @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); listview = (ListView) Findviewbyid (r.id.listview);d ialog = new ProgressDialog ( Mainactivity.this);d ialog.settitle ("Warning");d ialog.setmessage ("Loading information ..."); adapter = new Myadapter ();/** * used to get data ... */ New MyTask (). Execute (emp_path + pageno); Listview.setonscrolllistener (new Onscrolllistener () {@Overridepublic void Onscrollstatechanged (abslistview view, int scrollstate) {/** * When paging operation Is_divpage true, sliding stop, and pageno<= 4 (here because the server has 4 pages of data), load more data. */if (is_divpage && scrollstate = = Onscrolllistener.scroll_state_idle && pageno <=4) {Toast.maketext (Mainactivity.this, "getting more data ...", toast.length_shORT). Show (); new MyTask (). Execute (emp_path+pageno);} else if (PageNo >4) {/** * If pageno>4 indicates that there is no more data on the server to load. */toast.maketext (Mainactivity.this, "No more data ...", Toast.length_short). Show ();}} /** * When: the first visible item (FIRSTVISIBLEITEM) + the number of visible items (visibleitemcount) = ALL item Total, * Is_divpage becomes true, this time the data is loaded. */@Overridepublic void onscroll (abslistview view, int firstvisibleitem,int visibleitemcount, int totalitemcount) {Is_ Divpage = (Firstvisibleitem + visibleitemcount = = Totalitemcount);}});} /** * MyTask inheritance thread pool Asynctask used for network data requests, JSON parsing, data update and other operations. */class MyTask extends Asynctask<string, Void, string> {/** * Data request before display dialog. */@Overrideprotected void OnPreExecute () {super.onpreexecute ();d ialog.show ();} /** * In the Doinbackground method, do some time-consuming operations such as network requests. */@Overrideprotected string Doinbackground (String ... params) {return RequestData ();} /** * In this method, the main processing of some data, update. */@Overrideprotected void OnPostExecute (String result) {Super.onpostexecute (result); if (result! = NULL) {// If the result data obtained is not NULL, it is parsed by JSON. and displayed inOn the phone screen. list<string> list = jsonanalysis (result); Total.addall (list); Adapter.binddata (total);/** * When PageNo equals 1, it will be setadapter, will not be set again, direct notifydatasetchanged, to update the data *, so as to avoid each load more data, will be back to the first page. */if (PageNo = = 1) {Listview.setadapter (adapter);} Adapter.notifydatasetchanged ();p ageno++;} else if (result = = null) {Toast.maketext (mainactivity.this, "Request data Failed ...", Toast.length_long). Show (); Dialog.dismiss ();}} /** * The adapter for the ListView */class Myadapter extends Baseadapter {list<string> list;/** * Binddata is used to pass data to the adapter. * @param list */public void Binddata (list<string> list) {this.list = list;} @Overridepublic int GetCount () {return list.size ();} @Overridepublic Object getItem (int position) {return list.get (position);} @Overridepublic long Getitemid (int position) {return position;} @Overridepublic view GetView (int position, view Convertview, ViewGroup parent) {TextView TextView = null;if (Convertview = = null) {TextView = new TextView (mainactivity.this);} else {TextView = (TextView) CONVERTVIEW;} Textview.settextsize (Textview.settext); List.get (position); return textView;}} /** * Network data request * @return */public String RequestData () {HttpGet get = new HttpGet (Emp_path+pageno); HttpClient client = new Defaulthttpclient (); StringBuilder Builder = null;try {HttpResponse response = Client.execute (GET), if (Response.getstatusline (). Getstatuscode () = = () {InputStream InputStream = response.getentity (). getcontent (); BufferedReader reader = new BufferedReader (new InputStreamReader (InputStream)); builder = new StringBuilder (); String s = null;for (s = reader.readline (); s = null; s = Reader.readline ()) {builder.append (s);}}} catch (Exception e) {e.printstacktrace ();} return builder.tostring ();} /** * JSON parsing * @param result * @return */public list<string> jsonanalysis (String result) {onetotal.clear ();//first clear before parsing To ensure that only the data on the page is stored and avoid duplication. Jsonarray array = null;try {array = new Jsonarray (result);} catch (Jsonexception e) {e.printstacktrace ();} try {String str0 = array.getstring (0); String str1 = arrAy.getstring (1); String str2 = array.getstring (2); String STR3 = array.getstring (3); String STR4 = array.getstring (4); String STR5 = array.getstring (5); String STR6 = array.getstring (6); String STR7 = array.getstring (7); String str8 = array.getstring (8); String STR9 = array.getstring (9); String str10 = array.getstring (10); String Str11 = array.getstring (11); String str12 = array.getstring (12); String Str13 = array.getstring (13); String str14 = array.getstring (14); String str15 = array.getstring (15); String str16 = array.getstring (16); String str17 = array.getstring (17); String str18 = array.getstring (18); String str19 = array.getstring (19); String Str20 = array.getstring (20); String Str21 = array.getstring (21); String str22 = array.getstring (22); String str23 = array.getstring (23); String str24 = array.getstring; Onetotal.add (STR0); Onetotal.add (str1); Onetotal.add (str2); Onetotal.add (STR3); o Netotal.add (STR4); Onetotal.add (STR5); Onetotal.add (STR6); Onetotal.add (STR7); Onetotal.add (STR8); Onetotal.add ( STR9); OnetoTal.add (STR10); Onetotal.add (STR11); Onetotal.add (str12); Onetotal.add (Str13); Onetotal.add (Str14); Onetotal.add ( STR15); Onetotal.add (str16); Onetotal.add (str17); Onetotal.add (str18); Onetotal.add (STR19); Onetotal.add (STR20); o Netotal.add (STR21); Onetotal.add (STR22); Onetotal.add (Str23); Onetotal.add (STR24);} catch (Jsonexception e) {e.printstacktrace ();} Return onetotal;//only returns the data for this page}}

Remember to add network permissions in the Manifest.xml file.


Source code Download:

Click to download the source code

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.