Android实现简单的分批加载ListView

Android实现简单的分批加载ListView,第1张

概述每次滑动至底端,从数据库中获取10条数据,并加载于ListView中数据库packagecom.example.listviewbatchloading;

每次滑动至底端,从数据库中获取10条数据,并加载于ListVIEw中

数据库

package com.example.ListvIEwbatchloading;  import androID.content.Context; import androID.database.sqlite.sqliteDatabase; import androID.database.sqlite.sqliteDatabase.CursorFactory; import androID.database.sqlite.sqliteOpenHelper;  public class PersonDb extends sqliteOpenHelper {    public PersonDb(Context context) {     super(context,"creature",null,1);     // Todo auto-generated constructor stub   }    @OverrIDe   public voID onCreate(sqliteDatabase db) {     // Todo auto-generated method stub     db.execsql("create table people(_ID integer primary key autoincrement,name char,number char)");   }    @OverrIDe   public voID onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {     // Todo auto-generated method stub     db.execsql("drop table people");     onCreate(db);   }  } 

数据库的业务封装,其中获取更多数据的是核心代码

package com.example.ListvIEwbatchloading;  /**  * 数据库的业务封装类  */  import java.util.ArrayList; import java.util.List;  import androID.content.ContentValues; import androID.content.Context; import androID.database.Cursor; import androID.database.sqlite.sqliteDatabase;  public class PersonList {      PersonDb personDb;      public PersonList(Context context){     this.personDb = new PersonDb(context);   }      /**    *   获取一定条目的数据    * @param startIndex    *   开始取数据的位置    * @param num    *   取多少条数据    */   public List<Person> getMoreDatas(int startIndex,int num){          List<Person> List = new ArrayList<Person>();     sqliteDatabase db = personDb.getWritableDatabase();     Cursor cursor = db.rawquery("select name,number from people order by _ID desc limit ?,?",new String[]{startIndex + "",num + ""});          while(cursor.movetoNext()){       Person person = new Person();       person.setname(cursor.getString(cursor.getColumnIndex("name")));       person.setNumber(cursor.getString(cursor.getColumnIndex("number")));       List.add(person);     }          cursor.close();     db.close();               return List;        }      /**    *   添加数据库条目    * @param name    * @param number    */   public voID add(String name,String number){          sqliteDatabase db = personDb.getWritableDatabase();          ContentValues cv = new ContentValues();     cv.put("name",name);     cv.put("number",number);          db.insert("people",cv);     db.close();   }    } 

功能实现

package com.example.ListvIEwbatchloading;  import java.util.ArrayList; import java.util.List;  import androID.app.Activity; import androID.os.Bundle; import androID.os.Handler; import androID.os.Message; 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 ListVIEw lv ;   private List<Person> datas = new ArrayList<Person>();   private static int PERPAGE = 10; //每页加载数目   private static final int FINISH = 0;//数据加载完成   private List<Person> moreDatas;//每次加载的数据   private MyAdapter adapter;   private PersonList personList ;      //若数据较多,耗时较长,数据加载完成时,发送FINISH至handler,并通知ListVIEw更新数据   private Handler handler = new Handler(){     public voID handleMessage(androID.os.Message msg) {              switch (msg.what) {       case FINISH:         if (moreDatas.size() != 0) {           System.out.println(moreDatas.toString());           adapter.notifyDataSetChanged();         }else {           Toast.makeText(MainActivity.this,"没有更多数据",Toast.LENGTH_SHORT).show();         }         break;        default:         break;       }                   };   };      @OverrIDe   protected voID onCreate(Bundle savedInstanceState) {     super.onCreate(savedInstanceState);     setContentVIEw(R.layout.activity_main);     initVIEw();     initData();     initEvent();   }   /**    *   为ListVIEw添加滚动监听事件,但滚动至最后一行时,加载更多数据    */   private voID initEvent() {     lv.setonScrollListener(new OnScrollListener() {              @OverrIDe       public voID onScrollStateChanged(AbsListVIEw vIEw,int scrollState) {         // Todo auto-generated method stub         if (scrollState == OnScrollListener.SCRolL_STATE_IDLE) {           int lastVisibleposition = lv.getLastVisibleposition();           if (lastVisibleposition == datas.size() - 1) {             initData();             System.out.println("加载更多数据");           }         }       }              @OverrIDe       public voID onScroll(AbsListVIEw vIEw,int firstVisibleItem,int visibleItemCount,int totalitemCount) {         // Todo auto-generated method stub                }     });   }    private voID initVIEw() {          setContentVIEw(R.layout.activity_main);          lv = (ListVIEw) findVIEwByID(R.ID.lv);     personList = new PersonList(getApplicationContext());     adapter = new MyAdapter();     lv.setAdapter(adapter);   }      /**    * 在子线程中加载数据,避免主线程阻塞    */   private voID initData() {     new Thread() {        public voID run() {          // 加载更多数据         moreDatas = personList.getMoreDatas(datas.size(),PERPAGE);          datas.addAll(moreDatas);// 把一个容器的所有数据加进来         // 取数据完成,发消息通知取数据完成         handler.obtainMessage(FINISH).sendToTarget();        };     }.start();   }      private class ItemVIEw{     private TextVIEw tv_name;     private TextVIEw tv_num;   }      /**    *   ListVIEw的适配器    * @author lian    *    */   private class MyAdapter extends BaseAdapter{      @OverrIDe     public int getCount() {       // Todo auto-generated method stub       return datas.size();     }      @OverrIDe     public Object getItem(int position) {       // Todo auto-generated method stub       return null;     }      @OverrIDe     public long getItemID(int position) {       // Todo auto-generated method stub       return 0;     }      @OverrIDe     public VIEw getVIEw(int position,VIEw convertVIEw,VIEwGroup parent) {              ItemVIEw itemVIEw = null;       if (convertVIEw == null) {         itemVIEw = new ItemVIEw();         convertVIEw = VIEw.inflate(getApplicationContext(),R.layout.item_lv,null);         itemVIEw.tv_name = (TextVIEw) convertVIEw.findVIEwByID(R.ID.tv_name);         itemVIEw.tv_num = (TextVIEw) convertVIEw.findVIEwByID(R.ID.tv_num);         convertVIEw.setTag(itemVIEw);       }else {         itemVIEw = (ItemVIEw) convertVIEw.getTag();       }              Person person = datas.get(position);       itemVIEw.tv_name.setText(person.getname());       itemVIEw.tv_num.setText(person.getNumber());              return convertVIEw;     }        }    } 

其他Person的JavaBean,以及布局文件,不在赘述

以上就是本文的全部内容,希望对大家的学习有所帮助。

总结

以上是内存溢出为你收集整理的Android实现简单的分批加载ListView全部内容,希望文章能够帮你解决Android实现简单的分批加载ListView所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1149508.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存