Android ListView动态更新数据

Android ListView就是可以显示一行行Item的控件,有时候数据非常多,通常需要分页显示,但为了减少用户的输入,我们可以动态更新ListView,把下一页要显示的数据的添加到当前ListView中。

先看看效果:

Android-ListView

需要注意的是程序在什么时候去更新数据,listVIew的setOnScrollListener监听是否滚到了最后一条记录。

取到的数据加到list中,最后记得调用adapter的notifyDataSetChanged,通知listview改变。

主文件:

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Toast;

public class ListViewActivity extends Activity {
	private ListView listView;
	
    // 定义适配器
	private ListItemAdapter listadpter;
	
    // 定义每一页显示行数
	private int VIEW_COUNT = 20;
	
    // 定义的页数
	private int index = 0;
	
    // 当前页
	private int currentPage = 1;
	
    // 所以数据的条数
	private int totalCount;
	
    // 每次取的数据,只要最后一次可能不一样。
	private int maxResult;
	
    // 泛型集合ArrayList
	private ArrayList arrayList = new ArrayList();
	
    // 数据操作的dao类
	StudentsDAO dao = new StudentsDAO(ListViewActivity.this);
	
    // 实体bean
	Students students = new Students();
	
    // 标记:上次的ID
	private boolean isUpdating = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
        // 初始化界面
		initView();
		
        // 插入100条记录。
		dao.insert();
		totalCount = dao.getCount();
		maxResult = getMaxResult();
		
        // 调用dao里面的selectAll()方法
		arrayList = dao.getAllItems(index, maxResult);
		
        // 实例化适配器
		System.out.println("arrlist-->" + arrayList.size());
		listadpter = new ListItemAdapter(ListViewActivity.this, arrayList);
		
        // 填充适配器
		listView.setAdapter(listadpter);

		listView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				if (firstVisibleItem + visibleItemCount == totalItemCount
						&& !isUpdating) {
					if (totalItemCount < totalcount)="" {="" 防止最后一次取数据进入死循环。="" toast.maketext(listviewactivity.this,="" "正在取第"="" +="" (++currentpage)="" +="" "的数据",="" toast.length_long).show();="" asyncupdatedatastask="" asyncupdateweibodatastask="new" asyncupdatedatastask();="" asyncupdateweibodatastask.execute();="" }="" system.out.println("begin="" update-------------");="" }="" }="" });="" }="" 初始化界面方法="" private="" void="" initview()="" {="" todo="" auto-generated="" method="" stub="" listview="(ListView)" findviewbyid(r.id.list);="" }="" class="" asyncupdatedatastask="" extends="">> {

		@Override
		protected List doInBackground(Void... params) {
			// TODO Auto-generated method stub
			isUpdating = true;
			index += VIEW_COUNT;
			List list = new ArrayList();
			list = dao.getAllItems(index, maxResult);
			return list;
		}

		@Override
		protected void onPostExecute(List result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			arrayList.addAll(result);
			listadpter.notifyDataSetChanged();
			isUpdating = false;
			System.out.println("end update--------------");
		}
	}

	private int getMaxResult() {
		int totalPage = (totalCount + VIEW_COUNT - 1) / VIEW_COUNT;
		return totalCount - (totalPage - 1) * VIEW_COUNT;
	}
}

数据库Dao文件:

package com.shao.list;

import java.util.ArrayList;
import java.util.Random;

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

public class StudentsDAO extends SQLiteOpenHelper {

	private final static String AUDIODATABASE_NAME = "student.db";
	private final static String TABLE = "student";
	private final static String COLUM_ID = "id";
	private final static String COLUM_NAME = "name";
	private final static String COLUM_AGE = "age";
	private final static int DATABASE_VERSION = 1;
	private long row;
	private ArrayList arrayList;

	public StudentsDAO(Context context) {
		super(context, AUDIODATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		String sql = "CREATE TABLE " + TABLE + " (" + COLUM_ID
				+ " INTEGER primary key autoincrement, " + " " + COLUM_NAME
				+ " text, " + " " + COLUM_AGE + " int)";
		db.execSQL(sql);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		String sql = "DROP TABLE IF EXISTS " + TABLE;
		db.execSQL(sql);
	}

	public long insert() {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues cv = new ContentValues();
		Random random = new Random();
		for (int i = 1; i <= 100;="" i++)="" {="" cv.put(colum_id,="" i);="" cv.put(colum_name,="" "name"="" +="" string.valueof(i));="" cv.put(colum_age,="" random.nextint(100));="" row="db.insert(TABLE," null,="" cv);="" }="" db.close();="" return="" row;="" }="" 查询记录的总数="" public="" int="" getcount()="" {="" sqlitedatabase="" db="getWritableDatabase();" string="" sql="select count(*) from  +=" table=" +=" ";="" cursor="" c="db.rawQuery(sql," null);="" c.movetofirst();="" int="" length="c.getInt(0);" c.close();="" db.close();="" system.out.println("length--="">"+length);
		return length;
	}

	public ArrayList getAllItems(int firstResult, int maxResult) {
		arrayList = new ArrayList();
		SQLiteDatabase db = getWritableDatabase();
		String sql = "select * from  + TABLE +  limit ?,?";
		Cursor cursor = db.rawQuery(
				sql,
				new String[] { String.valueOf(firstResult),
						String.valueOf(maxResult) });
		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			Students students = new Students();
			students.setId(cursor.getInt(0));
			students.setName(cursor.getString(1));
			students.setAge(cursor.getInt(2));
			arrayList.add(students);
		}
		cursor.close();
		db.close();
		return arrayList;
	}

	public ArrayList selectAll() {
		arrayList = new ArrayList();
		SQLiteDatabase db = this.getWritableDatabase();
		Cursor cursor = db.query(TABLE, null, null, null, null, null, null);
		if (cursor != null && cursor.getCount() > 0) {
			cursor.moveToFirst();
		}
		for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
			Students students = new Students();
			students.setId(cursor.getInt(0));
			students.setName(cursor.getString(1));
			students.setAge(cursor.getInt(2));
			arrayList.add(students);
		}
		cursor.close();
		db.close();
		return arrayList;

	}

}
暂无评论
  • 1:请一针见血的评论。
  • 2:评论需要审核通过后才能显示。
  • 3:评论字数限制在1000字以内。
  • 当前字数:0
热门文章
推荐文章
随机文章
关于本站 - 广告服务 - 版权声明 - 联系我们 - 友情链接 - 网站地图 - 帮助中心