Android ListView page loading (SERVER + android) Demo

Source: Internet
Author: User

The Android ListView paging loading function is often used in actual development and is required by every developer. This Demo provides the code for both the server side and Android side and passes the test.

The server uses MyEclipse and the Android client uses Eclipse.

Implementation:

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


Source code:

Server:

Import the jar packages in the figure.


Before running the Android code, you must enable the server:


The following is 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 <100; I ++) {list. add ("hellonihao" + I);} return list ;}}

DevidePage:

Package com. android. divpage; public class DevidePage {private int pageSize; // number of entries displayed per page private int recordCount; // total number of records private int currentPage; // private int pageCount on the current page; // total number of pages public DevidePage (int pageSize, int recordCount, int currentPage) {this. pageSize = pageSize; this. recordCount = recordCount; this. setCurrentPage (currentPage);} public int getPageSize () {return pageSize;} public void setPageSize (in T pageSize) {this. pageSize = pageSize;} public int getRecordCount () {return recordCount;} public void setRecordCount (int recordCount) {this. recordCount = recordCount;}/*** obtain the total number of 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 to locate on the current page */private void setCurrentPage (int currentPage) {int activePage = currentPage <= 0? 1: currentPage; activePage = 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; public class EmpAction extends HttpServlet {public void doGet (HttpServletRequest request, HttpServlet Response 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 (); EmpDa TaSource dataSource = new EmpDataSource ();/*** get the data in the EmpDataSource class */List <String> list = dataSource. getDataSource (); String pageNo = request. getParameter ("pageNo"); int currentPage = 1; // the current page is the first page if (pageNo! = Null) {currentPage = Integer. parseInt (pageNo);}/*** page: each page has 25 data records. Because there are 100 data records, there are 4 pages in total. */DevidePage pUtil = new DevidePage (25, list. size (), currentPage); int start = pUtil. getFromIndex (); int end = pUtil. getToIndex (); List <String> subList = list. subList (start, end); array = JSONArray. fromObject (subList); writer. println (array); writer. flush (); writer. close ();}}


Android terminal;

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 replace the IP address in the path with the IP address of your local machine.

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. JSONExcepti On; 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 MainA Ctivity extends Activity {private String EMP_PATH = "http: // 172.16.17.36: 8080/JsonServiceDemo/servlet/EmpAction? PageNo = "; private ListView listView; private MyAdapter adapter; private boolean is_divPage; // whether to perform pagination operation private List <String> oneTotal = new ArrayList <String> (); // used to store one page of data private List <String> total = new ArrayList <String> (); // used to store all obtained data private ProgressDialog dialog; private static int pageNo = 1; // set the initialization value of pageNo to 1, that is, the data on the first page is obtained by default. @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); listView = (ListView) findViewById (R. id. listView); dialog = new ProgressDialog (MainActivity. this); dialog. setTitle ("warning"); dialog. setMessage ("loading information... "); adapter = new MyAdapter ();/*** used to obtain data... */new mytask(cmd.exe cute (EMP_PATH + pageNo); listView. setOnScrollListener (new OnScrollListener () {@ Overridepublic void onScrollStateChanged (AbsListView view, int scrollState) {/*** load more data when is_divPage is set to true, sliding stops, and pageNo <= 4 (because the server has 4 pages. */If (is_divPage & scrollState = OnScrollListener. SCROLL_STATE_IDLE & pageNo <= 4) {Toast. makeText (MainActivity. this, "getting more data... ", Toast. LENGTH_SHORT ). show (); new mytask(cmd.exe cute (EMP_PATH + pageNo);} else if (pageNo> 4) {/*** if pageNo> 4, the server does not have more data for loading. */Toast. makeText (MainActivity. this, "No more data... ", Toast. LENGTH_SHORT ). show () ;}}/*** when: the first visible item (firstVisibleItem) + the number of visible items (visibleItemCount) = the total number of all items, * If is_divPage is set to TRUE, data is loaded. * // @ Overridepublic void onScroll (AbsListView view, int detail, int visibleItemCount, int totalItemCount) {is_divPage = (firstVisibleItem + visibleItemCount = totalItemCount );}});} /*** MyTask inherits the thread pool AsyncTask for network data requests, json parsing, data update, and other operations. */Class MyTask extends AsyncTask <String, Void, String >{/ *** displays the dialog before the data request. * // @ Overrideprotected void onPreExecute () {super. onPreExecute (); dialog. show () ;}/ *** in the doInBackground method, perform time-consuming operations such as network requests. * // @ Overrideprotected String doInBackground (String... params) {return RequestData () ;}/ *** in this method, data is mainly processed and updated. * // @ Overrideprotected void onPostExecute (String result) {super. onPostExecute (result); if (result! = Null) {// If the obtained result data is not null, parse the result in JSON format. And displayed on the mobile phone screen. List <String> list = JSONAnalysis (result); total. addAll (list); adapter. bindData (total);/*** setAdapter is used when pageNo is equal to 1. If pageNo is not set later, notifyDataSetChanged is directly used to update data *, this avoids returning to the first page every time more data is loaded. */If (pageNo = 1) {listView. setAdapter (adapter);} adapter. notifyDataSetChanged (); pageNo ++;} else if (result = null) {Toast. makeText (MainActivity. this, "request data failed... ", Toast. LENGTH_LONG ). show () ;}// dialog. dismiss () ;}/ *** ListView adapter */class MyAdapter extends BaseAdapter {List <String> list;/*** bindData is used to transmit 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) {textVi Ew = new TextView (MainActivity. this);} else {textView = (TextView) convertView;} textView. setTextSize (20); 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.exe cute (get); if (response. getStatu SLine (). getStatusCode () = 200) {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 (); // clear the page before parsing to ensure that only the data on this page is stored to 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 (24); oneTotal. add (str0); oneTotal. add (str1); oneTotal. add (str2); oneTotal. add (str3); oneTotal. 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); oneTotal. add (str21); oneTotal. add (str22); oneTotal. add (str23); oneTotal. add (str24);} catch (JSONException e) {e. printStackTrace ();} return oneTotal; // only data on this page is returned }}

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


Source code download:

Click to download source code

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.