码迷,mamicode.com
首页 > 移动开发 > 详细

Android ListView动态更新数据

时间:2015-02-13 00:06:57      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:

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;  
          
    }  
  
}  

 

 

 

Android ListView动态更新数据

标签:

原文地址:http://www.cnblogs.com/zhujiabin/p/4289365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!