Android ListView分页载入(服务端+android端)Demo

Android ListView分页载入功能 在实际开发中经经常使用到,是每一个开发人员必须掌握的内容,本Demo给出了服务端+Android端的两者的代码,并成功通过了測试。

服务端使用MyEclipse,Android端使用Eclipse。

实现效果图:

服务端一共100条数据,共分四页,每页有25条数据。


源码:

服务端:

须要导入图中这几个jar包。


在执行Android端代码前,须要开启服务端:


以下先给出服务端的代码:

类EmpDataSource:

package com.android.divpage;


import java.util.ArrayList;
import java.util.List;
/**
 * 服务端数据
 * @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;// 每页显示的条数
	private int recordCount;// 记录的总条数
	private int currentPage;// 当前页
	private int pageCount;// 总页数

	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(int pageSize) {
		this.pageSize = pageSize;
	}

	public int getRecordCount() {
		return recordCount;
	}

	public void setRecordCount(int recordCount) {
		this.recordCount = recordCount;
	}

	/**
	 * 获得总页数
	 */
	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;
	}

	/**
	 * 设置定位在当前页
	 */
	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, 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();
		
		/**
		 * 获取EmpDataSource类中的数据
		 */
		List<String> list = dataSource.getDataSource();
		String pageNo = request.getParameter("pageNo");
		int currentPage = 1;//当前页是第一页
		if (pageNo != null) {
			currentPage = Integer.parseInt(pageNo);
		}
		/**
		 * 分页:每页有25条数据,由于有100条,所以总共同拥有4页。
		 */
		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端;

布局文件:

<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:

记住须要把路径中的ip地址换成你自己本机的ip地址。

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=";
	private ListView listView;
	private MyAdapter adapter;
	private boolean is_divPage;// 是否进行分页操作
	private List<String> oneTotal = new ArrayList<String>();// 用来存放一页数据
	private List<String> total = new ArrayList<String>();//用来存放获取的全部数据
	private ProgressDialog dialog;
	private static int pageNo = 1;//设置pageNo的初始化值为1,即默认获取的是第一页的数据。

	@Override
	protected 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("警告");
		dialog.setMessage("正在载入信息...");
		
		adapter = new MyAdapter();
		/**
		 * 用来获取数据...
		 */
		new MyTask().execute(EMP_PATH + pageNo);
		
		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				/**
				 * 当分页操作is_divPage为true时、滑动停止时、且pageNo<=4(这里由于服务端有4页数据)时,载入很多其它数据。
				 */
				if (is_divPage && scrollState == OnScrollListener.SCROLL_STATE_IDLE && pageNo <=4) {
					Toast.makeText(MainActivity.this, "正在获取很多其它数据...",Toast.LENGTH_SHORT).show();
					new MyTask().execute(EMP_PATH+pageNo);
				}else if (pageNo >4) {
					/**
					 * 假设pageNo>4则表示,服务端没有很多其它的数据可供载入了。
					 */
					Toast.makeText(MainActivity.this, "没有很多其它数据啦...", Toast.LENGTH_SHORT).show();
				}

			}
			/**
			 * 当:第一个可见的item(firstVisibleItem)+可见的item的个数(visibleItemCount)=全部的item总数的时候,
			 * is_divPage变为TRUE,这个时候才会载入数据。
			 */
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				is_divPage = (firstVisibleItem + visibleItemCount == totalItemCount);

			}
		});

	}
	/**
	 * MyTask继承线程池AsyncTask用来网络数据请求、json解析、数据更新等操作。
	 */
	class MyTask extends AsyncTask<String, Void, String> {
		/**
		 * 数据请求前显示dialog。
		 */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}
		
		/**
		 * 在doInBackground方法中,做一些诸如网络请求等耗时操作。
		 */
		@Override
		protected String doInBackground(String... params) {
			return RequestData();
		}
		
		/**
		 * 在该方法中,主要进行一些数据的处理,更新。
		 */
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null) {
				// 假设获取的result数据不为空,那么对其进行JSON解析。并显示在手机屏幕上。
				List<String> list = JSONAnalysis(result);
				total.addAll(list);
				adapter.bindData(total);
				/**
				 * 当pageNo等于1的时候才会setAdapter,以后不会再设置,直接notifyDataSetChanged,进行数据更新
				 * ,这样可避免每次载入很多其它数据的时候,都会又一次回到第一页。
				 */
				if (pageNo == 1) {
					listView.setAdapter(adapter);
				}
				adapter.notifyDataSetChanged();
					pageNo++;
			} else if (result == null) {
				Toast.makeText(MainActivity.this, "请求数据失败...", Toast.LENGTH_LONG)
						.show();
			}
//			dialog.dismiss();
		}
	}
	
	/**
	 * ListView的适配器
	 */
	class MyAdapter extends BaseAdapter {
		List<String> list;
		/**
		 * bindData用来传递数据给适配器。
		 * @param list
		 */
		public void bindData(List<String> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public 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(20);
			textView.setText(list.get(position));
			return textView;
		}

	}
	
	/**
	 * 网络数据请求
	 * @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() == 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解析
	 * @param result
	 * @return
	 */
	public List<String> JSONAnalysis(String result) {
		oneTotal.clear();//解析之前 先清理一下,以保证仅仅存储该页的数据,避免反复。
		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;//仅仅返回该页的数据
	}
}

记住要在Manifest.xml文件里加入网络权限。


源码下载:

点击下载源代码

posted @ 2015-05-12 20:12  hrhguanli  阅读(340)  评论(0编辑  收藏  举报