listview mysql查询_Sqlite 数据库分页查询(ListView分页显示数据)
下面介紹一下我的這個(gè)demo。
流程簡(jiǎn)述:
我在raw文件夾下面放了名稱為city的數(shù)據(jù)庫(kù),里面包含全國(guó)2330個(gè)城市,以及所屬省,拼音簡(jiǎn)寫等信息。
首先 在進(jìn)入MainActivity的時(shí)候,創(chuàng)建數(shù)據(jù)庫(kù)并讀入sd卡文件中data/data/databases/city。
然后 我再開啟子線程去讀取前50條數(shù)據(jù),顯示在ListView中。
當(dāng)用戶瀏覽數(shù)據(jù), 前50條不夠時(shí),他會(huì)滑動(dòng)ListView以查看更多數(shù)據(jù),此時(shí),listview的數(shù)據(jù)源會(huì)遞增,50 ,100,150,。。。。
以50為增量不斷增加.....
這樣避免了因一次性加載數(shù)據(jù)造成ANR,也給用戶比較好的體驗(yàn)。
工程目錄結(jié)構(gòu):
cls_city是城市信息類,Common是工具類,ViewHolder是ListView緩存機(jī)制幫助類,DataBaseHelper ?數(shù)據(jù)庫(kù)操作工具類/.....
package com.example.sqlitepagetest;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.util.Log;/**
*
*
* 下午9:12:42
*
* @auther dalvikCoder*/
public classcls_city {public String _id = "";public String province = "";public String name = "";/**
*
* select _id,province ,name from city order by _id limit perItemNum Offset
* currentPage*perItemNum ;--currentPage 從零開始
*
* 根據(jù)條目數(shù)量查詢
*
*
* @param dbh
* @param num
* num[1]-->每一頁(yè)顯示的條目數(shù)量 num[0]--->從第幾條開始
* @return List*/
public static List getCityList(DatabaseHelper dbh, intnum[]) {
String sql= "select _id,province ,name from city order by _id limit"
+ num[0] + "," + num[1];
Log.e("select city's sql --------------", sql);
Cursor cursor=dbh.rawQuery(sql);
List list = new ArrayList();
cls_city cls= null;while(cursor.moveToNext()) {
cls= newcls_city();
setClassValueBycursor(cls, cursor);
list.add(cls);
}returnlist;
}/**
*
* 利用反射機(jī)制給對(duì)象賦值
*
* @param obj
* @param cursor void*/
public static voidsetClassValueBycursor(Object obj, Cursor cursor) {int ColCount =cursor.getColumnCount();int i = 0;for (i = 0; i < ColCount; i++) {
String ColName=cursor.getColumnName(i);try{
Field f=obj.getClass().getField(ColName);
String ret=cursor.getString(i);if (f == null)continue;if (ret == null)
ret= "";
f.set(obj, ret);
}catch(SecurityException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchFieldException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalArgumentException e) {//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
package com.example.sqlitepagetest;
import android.util.SparseArray;
import android.view.View;/**
*
* ListView緩存的寫法比較多種,下面也是其中一中,
*
* 下午9:45:29
*
* @auther dalvikCoder*/
public classViewHolder {//I added a generic return type to reduce the casting noise in client code
@SuppressWarnings("unchecked")public static T get(View view, intid) {
SparseArray viewHolder = (SparseArray) view.getTag();if (viewHolder == null) {
viewHolder= new SparseArray();
view.setTag(viewHolder);
}
View childView= viewHolder.get(id);if (childView == null) {
childView=view.findViewById(id);
viewHolder.put(id, childView);
}return(T) childView;
}
}
在使用了ViewHolder之后,自定義適配器里面的代碼看起來好多了。
@Overridepublic View getView(intposition, View convertView, ViewGroup parent) {if (convertView == null) {
convertView= inflater.inflate(R.layout.city_lv_item, null);
}
TextView cityId= ViewHolder.get(convertView, R.id.cityidtxt);
TextView provincetxt= ViewHolder.get(convertView, R.id.provincetxt);
TextView cityName= ViewHolder.get(convertView, R.id.nametxt);
cls_city city= cityList.get(position);
cityId.setText(city._id);
provincetxt.setText(city.province);
cityName.setText(city.name);returnconvertView;
}
下面是總的MainActivity類,里面的注釋比較詳細(xì),也比較簡(jiǎn)單。
當(dāng)然如果有興趣你可以給ListView添加尾部視圖,比如加個(gè)狀態(tài)文字或者加個(gè)加個(gè)進(jìn)度條,不過像本地?cái)?shù)據(jù),好像用不了多少時(shí)間
package com.example.sqlitepagetest;
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.Menu;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;public classMainActivity extends Activity {privateListView cityListView;private ListcityList;privateCityAdapter cityAdapter;private MyThread thread = null;/**
* 每頁(yè)有數(shù)據(jù)條數(shù) 這個(gè)數(shù)量可以根據(jù)需要更改,而不需在程序中更改具體數(shù)值
* **/
private int perPageItemNum = 100;/** 當(dāng)前是第幾頁(yè) 0表示第一頁(yè) **/
private int currentPage = 0;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpView();
}private voidsetUpView() {
cityList= new ArrayList();try{
Common.loadCityDatabase(this);
}catch(Exception e) {
e.printStackTrace();
}
Common.dbh= new DatabaseHelper(this, "city");
cityListView=(ListView) findViewById(R.id.citylistview);
cityAdapter= new CityAdapter(this, cityList);
cityListView.setAdapter(cityAdapter);
cityListView.setOnScrollListener(newOnScrollListener() {
@Overridepublic void onScrollStateChanged(AbsListView view, intscrollState) {if (view.getLastVisiblePosition() == view.getCount() - 1
&& scrollState ==OnScrollListener.SCROLL_STATE_IDLE) {if (thread != null && !thread.isInterrupted()) {
thread.interrupt();
thread= null;
}
currentPage++;
cityListView.setSelection(view.getLastVisiblePosition());//設(shè)置顯示位置,這句只是讓Listview停留在最后末尾的顯示而已,加不加影響不大
thread = newMyThread();
thread.start();
}
}
@Overridepublic void onScroll(AbsListView view, intfirstVisibleItem,int visibleItemCount, inttotalItemCount) {
}
});if (thread == null) {
thread= newMyThread();
thread.start();
}
}
@Overridepublicboolean onCreateOptionsMenu(Menu menu) {//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);return true;
}classMyThread extends Thread {
@Overridepublic voidrun() {int num[] = new int[2];
num[0] = currentPage * perPageItemNum;//0*50 1*50 2*50
num[1] =perPageItemNum;
List dataList =cls_city.getCityList(Common.dbh, num);//try {//Thread.sleep(1000);//} catch (InterruptedException e) {//e.printStackTrace();//}
Message msg = newMessage();
msg.what= 1;
msg.obj=dataList;
mHandler.sendMessage(msg);
}
}private Handler mHandler = newHandler() {
@Overridepublic voidhandleMessage(Message msg) {
super.handleMessage(msg);
List dataList = (List) msg.obj;if (!dataList.isEmpty()) {
cityAdapter.refresh(dataList);
}
}
};
}
Common類
package com.example.sqlitepagetest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import android.content.Context;/**
*
*
* 下午9:02:19
*
* @auther dalvikCoder*/
public classCommon {public static DatabaseHelper dbh = null;public static voidloadCityDatabase(Context context) throws Exception {//------------創(chuàng)建路徑
String path = "/data/data/" + context.getPackageName() + "/databases";
File file= newFile(path);if (!file.exists()) {
file.mkdirs();
}//--------------該路徑下創(chuàng)建數(shù)據(jù)庫(kù)文件
File f = new File(path, "city");if (!f.exists()) {
InputStreamis =context.getResources().openRawResource(R.raw.city);
FileOutputStreamout = new FileOutputStream(path + "/city");byte buffer[] = new byte[2 * 1024];int len = 0;while ((len = is.read(buffer)) > 0) {out.write(buffer, 0, len);
}out.close();is.close();
}
}
}
貼上效果圖:
總結(jié)
以上是生活随笔為你收集整理的listview mysql查询_Sqlite 数据库分页查询(ListView分页显示数据)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux shell文件锁,shell
- 下一篇: python web后端和vue哪个难_