---
title: "ListView分页（一）"
author: "jonsamwang"
date: "2014-07-04T15:34:59Z"
tags: []
categories: ["移动开发"]
slug: "listview"
draft: false
lastmod: "2014-07-04T15:34:59Z"
id: 2088332
url: "https://jonsam.iteye.com/blog/2088332"
---

**Android ListView 实现分页数据显示**

**1、MiaiActivity 类：主要的Activity类**

public class MianActivity extends Activity implements OnScrollListener {

 private ListView listView = null;  
 private int currentPage = 1;  
 private int lineSize = 25;// 每页显示  
 private int pageSize = 1;// 总页数  
 private int lastitem = 0;  
 private int allrecorders = 0;// 总记录数  
 private SimpleAdapter adapter = null;  
 private List&lt;Map&lt;String, Object&gt;&gt; listdata = null;  
 // 定义在下方显示 信息  
 private LinearLayout bottomLayout = null;  
 private TextView loadInfo = null;  
 //  
 private android.widget.LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
   LinearLayout.LayoutParams.FILL\_PARENT,  
   LinearLayout.LayoutParams.WRAP\_CONTENT);

 @Override  
 protected void onCreate(Bundle savedInstanceState) {  
  super.onCreate(savedInstanceState);  
  setContentView(R.layout.activity\_mian);  
  // 初始化  
  initWidget();  
  // 加载显示数据  
  showAlldata();  
  // 计算总页数  
  this.pageSize = (this.allrecorders % lineSize == 0) ? this.allrecorders  
    / lineSize : this.allrecorders / lineSize + 1;

 }

 public void initWidget() {  
  bottomLayout = new LinearLayout(this);  
  this.loadInfo = new TextView(this);  
  this.loadInfo.setText("加载中ING....");  
  this.loadInfo.setGravity(Gravity.CENTER);  
  this.loadInfo.setTextColor(Color.BLACK);  
  this.loadInfo.setTextSize(30);  
  bottomLayout.addView(loadInfo, layoutParams);

 }

 @Override  
 public boolean onCreateOptionsMenu(Menu menu) {  
  // Inflate the menu; this adds items to the action bar if it is present.  
  getMenuInflater().inflate(R.menu.mian, menu);  
  return true;  
 }

 // 显示ListView数据  
 public void showAlldata() {  
  listView = (ListView) findViewById(R.id.listView1);  
  ListQueryDAO queryDao = new ListQueryDAO(this);  
  // 求出总记录数  
  allrecorders = queryDao.getCountRow();  
  listdata = queryDao.findData(currentPage, lineSize);  
  this.adapter = new SimpleAdapter(this, listdata,  
    R.layout.list\_view\_layout, DBHelper.LinkanColumns.COLUMNS,  
    new int\[] { R.id.myviewId, R.id.myviewName, R.id.myviewPhone });  
  listView.addFooterView(bottomLayout);  
  listView.setAdapter(this.adapter);  
  listView.setOnScrollListener(this);  
 }

 public void appendData() {  
  ListQueryDAO queryDao = new ListQueryDAO(this);  
  List&lt;Map&lt;String, Object&gt;&gt; newdata = queryDao.findData(this.currentPage,  
    lineSize);  
  listdata.addAll(newdata);  
  this.adapter.notifyDataSetChanged();

 }

 // 监听来自屏幕滚动  
 @Override  
 public void onScroll(AbsListView listview, int firstVisiableitem,  
   int visiableItemCount, int tatalItemCount) {  
  // TODO Auto-generated method stub  
  this.lastitem = firstVisiableitem + visiableItemCount - 1;  
 }

 @Override  
 public void onScrollStateChanged(AbsListView arg0, int scrollstatus) {  
  // TODO Auto-generated method stub  
  if (this.lastitem == this.adapter.getCount()  
    && this.currentPage &lt; this.pageSize  
    && scrollstatus == OnScrollListener.SCROLL\_STATE\_IDLE) {  
   this.currentPage++;  
   this.listView.setSelection(this.lastitem);  
   this.appendData();  
  }

 }

}

**2、SQLite数据库封装类**

  **DBHelper.java类**

package com.tsinghua.datasource;

import android.content.ContentValues;  
import android.content.Context;  
import android.database.Cursor;  
import android.database.sqlite.SQLiteDatabase;  
import android.database.sqlite.SQLiteDatabase.CursorFactory;  
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper {  
 private Context context;  
 private SQLiteDatabase dbInstance;  
 private DBCreator dbCreator;  
 private String tableName="myAddressBook";

 public static final int DB\_VERSION = 1;

 public static final String DB\_NAME = "db\_addressbook.db";

 public static final String TABLE\_NAME\_LINKMAN = "myAddressBook";

 public DBHelper(Context context) {  
  this.context = context;  
 }

 public static final String CREATE\_TABLE = new StringBuffer()  
   .append("Create table ").append(TABLE\_NAME\_LINKMAN).append(" (")  
   .append(LinkanColumns.COLUMN\_ID).append(" integer primary key,")  
   .append(LinkanColumns.COLUMN\_NAME).append(" text not null,")    
   .append(LinkanColumns.COLUMN\_PHONE).append(" text )")  
   .toString();

 public static final String QUERY\_LINKMAN\_TABLE = new StringBuilder()  
   .append("select * from ").append(TABLE\_NAME\_LINKMAN)  
   .toString();

 public static final class LinkanColumns {  
  public static final String COLUMN\_ID = "\_id";//  
  public static final String COLUMN\_NAME = "name";  
  public static final String COLUMN\_PHONE = "phoneName";

  public static final String\[] COLUMNS = { COLUMN\_ID, COLUMN\_NAME,  
    COLUMN\_PHONE };  
 }  
 //打开  
 public void open() {  
  dbCreator = new DBCreator(context, DBHelper.DB\_NAME, null,  
    DBHelper.DB\_VERSION, DBHelper.CREATE\_TABLE, tableName);  
  dbInstance = dbCreator.getWritableDatabase();  
 }

 public void close() {  
  dbCreator.close();  
 }

 public long insert(ContentValues values) {  
  return dbInstance.insert(tableName, null, values);  
 }

 public int update(ContentValues values, String whereClause,  
   String\[] whereArgs) {  
  return dbInstance.update(tableName, values, whereClause, whereArgs);  
 }

 public int delete(String whereClause, String\[] whereArgs) {  
  return dbInstance.delete(tableName, whereClause, whereArgs);  
 }

 public Cursor query(String sql, String\[] selectionArgs) {  
  return dbInstance.rawQuery(sql, selectionArgs);  
 }

 public Cursor query() {  
  return dbInstance.query(tableName, null, null, null, null, null,  
    DBHelper.LinkanColumns.COLUMN\_NAME);  
 }

 public void setTableName(String tableName) {  
  this.tableName = tableName;  
 }

   
 // database Operation 类  
 private class DBCreator extends SQLiteOpenHelper {  
  private Context context;  
  private String createTableSql;  
  private String tableName;

  public DBCreator(Context context, String name, CursorFactory factory,  
    int version, String createTableSql, String tableName) {  
   super(context, name, factory, version);  
   this.context = context;  
   this.createTableSql = createTableSql;  
  // this.tableName = tableName;  
  }

  @Override  
  public void onCreate(SQLiteDatabase db) {  
   db.execSQL(createTableSql);  
  }

  @Override  
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
   db.execSQL("drop table if exists " + tableName);  
   onCreate(db);  
  }  
 }  
}

 

  **Dao封装类，ListQueryDAO .java 继承自DBHelper类** 

 

/\**  
 *  
 * @author Administrator 分页查询  
 *  
 \*/  
public class ListQueryDAO extends DBHelper {

 public ListQueryDAO(Context context) {  
  super(context);  
  // TODO Auto-generated constructor stub  
 }

 public long addInfo(Integer id, String \_name, String phone) {  
  open();  
  ContentValues values = new ContentValues();  
  values.put(DBHelper.LinkanColumns.COLUMN\_ID, id);  
  values.put(DBHelper.LinkanColumns.COLUMN\_NAME, \_name);  
  values.put(DBHelper.LinkanColumns.COLUMN\_PHONE, phone);  
  long id_ = insert(values);  
  close();  
  return id\_;  
 }

 public Cursor querInfo() {  
  open();  
  Cursor cursor = query();  
  return cursor;  
 }

 /\**  
  * 查询多少条  
  *  
  * @return  
  \*/  
 public int getCountRow() {  
  open();  
  int count = 0;  
  final String sql = new StringBuffer().append(  
    "select count(\_id) from " + DBHelper.TABLE\_NAME\_LINKMAN + "")  
    .toString();  
    
  Cursor row\_cursor = query(sql, null);  
  for (row\_cursor.moveToFirst(); !row\_cursor.isAfterLast(); row\_cursor  
    .moveToNext()) {  
   count = row\_cursor.getInt(0);

  }  
  close();  
  return count;  
 }

 public List&lt;Map&lt;String, Object&gt;&gt; findData(int current, int lineSize) {  
  List&lt;Map&lt;String, Object&gt;&gt; all = new ArrayList&lt;Map&lt;String, Object&gt;&gt;();  
  final String sql = new StringBuffer().append("SELECT  ")  
    .append(DBHelper.LinkanColumns.COLUMN\_ID).append(" ,")  
    .append(DBHelper.LinkanColumns.COLUMN\_NAME).append(" ,")  
    .append(DBHelper.LinkanColumns.COLUMN\_PHONE).append(" ")  
    .append(" FROM ").append(DBHelper.TABLE\_NAME\_LINKMAN).append(" LIMIT ?,?")  
    .toString();

  System.out.println(sql);  
  String selectArgs\[] = new String\[] {  
    String.valueOf((current - 1) * lineSize),  
    String.valueOf(lineSize) };  
  open();  
  Cursor result = query(sql, selectArgs);    
  for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {  
   Map&lt;String, Object&gt; maps = new HashMap&lt;String, Object&gt;();  
   maps.put(DBHelper.LinkanColumns.COLUMN\_ID, result.getInt(0));  
   maps.put(DBHelper.LinkanColumns.COLUMN\_NAME, result.getString(1));  
   maps.put(DBHelper.LinkanColumns.COLUMN\_PHONE, result.getString(2));  
   all.add(maps);  
  }  
  return all;  
 }

}

**二、布局类 activity\_mian.xml**

&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
    xmlns:tools="[http://schemas.android.com/tools](http://schemas.android.com/tools)"  
    android:id="@+id/mylayout"  
    android:layout\_width="fill\_parent"  
    android:layout\_height="fill\_parent"  
    android:orientation="vertical"  
    tools:context=".MianActivity" &gt;  
    &lt;ListView  
        android:id="@+id/listView1"  
        android:layout\_width="fill\_parent"  
        android:layout\_height="wrap\_content" &gt;  
    &lt;/ListView&gt;

&lt;/LinearLayout&gt;

 

**Liew的布局文件   list\_view\_layout.xml**

 

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;LinearLayout xmlns:android="[http://schemas.android.com/apk/res/android](http://schemas.android.com/apk/res/android)"  
    android:layout\_width="fill\_parent"  
    android:layout\_height="match\_parent"  
    android:orientation="horizontal" &gt;

    &lt;TextView  
        android:id="@+id/myviewId"  
        android:layout\_width="100px"  
        android:gravity="center\_horizontal"  
        android:layout\_height="wrap\_content"  
        android:textSize="30px"  
              
         /&gt;

    &lt;TextView  
        android:id="@+id/myviewName"  
        android:layout\_width="180px"  
        android:gravity="center\_horizontal"  
        android:layout\_height="wrap\_content"       
        android:textSize="30px"  
        /&gt;

    &lt;TextView  
        android:id="@+id/myviewPhone"  
        android:layout\_width="wrap\_content"  
        android:layout\_height="wrap\_content"  
     
        android:textSize="30px"  
        /&gt;

&lt;/LinearLayout&gt;