首页 > 系统 > Android > 正文

Android实现简单的分批加载ListView

2020-01-02 06:59:32
字体:
来源:转载
供稿:网友

每次滑动至底端,从数据库中获取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", null, 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,以及布局文件,不在赘述

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表