Android ListView动态更新数据

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

先看看效果:

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

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

不废话,上代码。

主文件:

mport 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<Students> arrayList = new ArrayList<Students>();
    //数据操作的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 AsyncTask<Void, Void, List<Students>> {  

        @Override
        protected List<Students> doInBackground(Void... params) {
            // TODO Auto-generated method stub
            isUpdating = true;
            index += VIEW_COUNT;
            List<Students> list =new ArrayList<Students>();
            list = dao.getAllItems(index, maxResult);
            return list;
        }
        @Override
        protected void onPostExecute(List<Students> 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<Students> 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<Students> getAllItems(int firstResult, int maxResult) {
               arrayList=new ArrayList<Students>();
                 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<Students> selectAll() {
        arrayList=new ArrayList<Students>();
        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;  

    }  

}  
时间: 2024-10-24 11:11:54

Android ListView动态更新数据的相关文章

Android定时器,更新数据

做个笔记,Android中常用的定时器,用于定时更新ui数据等. 1.Handler + Runnable定时器 private Handler mHandler; private Runnable mRunnable; mHandler = new Handler(); mRunnable = new Runnable() { public void run () { //更新数据的方法 update(); } }; //定时启动线程(执行的线程,时间毫秒) mHandler.postDela

C#:使用ListView动态添加数据一直闪烁的解决办法

首先,自定义一个类ListViewNF,继承自 System.Windows.Forms.ListView using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace 你的名称空间 { class ListViewNF : System.Windows.Forms.ListView { public ListV

Android之ListView动态添加数据(SQLiteOpenHelper类添加数据)

一.SQLiteOpenHelper类: 这次我们通过sqlite来动态添加数据,接下来我们创建一个openHelper.java,在前面sqlite博客中我们已经详细的讲了SQLite的创建及使用等操作,我们将在onCreate 创建方法中创建一张表和插入相关的值,通过db.execSQL()完成Sqlite的运行. ①openHelper2.java文件: public class openHelper2 extends SQLiteOpenHelper { private static f

android listview滚动 edittext 数据就变了

可以明确,现在没有直接方法可以获得ListView中每一行EditText的值. 解决方案:重写BaseAdapter,然后自行获取ListView中每行输入的EditText值.     大概算法:重写BaseAdapter.getView函数,用一个数组存储EditText中的值,根据position即数组下标,在getView中动态更新EditText和动态获取EditText中的值.因为ListView中的item是复用的,如果不动态清空或动态获取EditText中值,就会出现数据紊乱,

postgresql 存储过程动态更新数据

-- 目标:动态更新表中数据 -- 老规矩上代码-----------------------------tablename 表名--feildname 字段名数组--feildvalue 字段值数组--returnvalue 返回值 create or replace function f_update ( tablename text, condition text, feildname text[], feildvalue text[], out returnvalue text ) as

Android AlertDialog 动态更新里面的ListView数据

1:和ListView的数据跟新是基本一样的. 2:Activity代码示例 public class MainActivity extends AppCompatActivity { AlertDialog alertDialog; View view; List<String> data = new ArrayList<>(); ListView listView; ArrayAdapter<String> adapter; Handler handler=new

android listView 滑动载入数据 该数据是服务端获取的

package com.sunway.works.applycash; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import com.sunway.works.R; import com.sunway.works.applycash.ApplyCashListActivity; impo

cocos2dx中android下动态更新.so文件

作者:HU 转载请注明,原文链接:http://www.cnblogs.com/xioapingguo/p/4037595.html  因为没用lua脚本写游戏,所以每次发布出去后,发现在bug,需要更新APK重新安装,严重影响体验,增加玩家流失率.如果使用直接更新.so文件的话,就可以解决这个问题. 1.下载.so文件,使用游戏本身的资源更新方法,下载下来,到文件的file/res目录 .so文件zip压缩一下会小很多,解压方法参考http://www.cnblogs.com/xioaping

Android中动态更新TextView上的文字

示例代码: 1.新线程,定时更新文字 class testThread extends Thread{ public void run() { Message message = new Message(); mHandler.sendMessage(message); } } //在handler中更新UI private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { textView.se