服务器之家

服务器之家 > 正文

Android实现简单的分批加载ListView

时间:2021-06-30 15:42     来源/作者:C_L

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

数据库

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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);
  }
 
}

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
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();
  }
   
}

功能实现

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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,以及布局文件,不在赘述

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

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
2021德云社封箱演出完整版 2021年德云社封箱演出在线看
2021德云社封箱演出完整版 2021年德云社封箱演出在线看 2021-03-15
返回顶部