数据库分页加载

来源:互联网 发布:福州清标软件 编辑:程序博客网 时间:2024/04/29 19:44

1、OpenHelper代码:

package com.example.sqlitedbdemo;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


public class MyDbOpenHelper extends SQLiteOpenHelper {


public MyDbOpenHelper(Context context) {
super(context, "demo.db", null, 1);
}


@Override
public void onCreate(SQLiteDatabase db) {
int[] images = { R.drawable.pic1, R.drawable.pic2, R.drawable.pic3,
R.drawable.pic4, R.drawable.pic5, R.drawable.pic6,
R.drawable.pic7, R.drawable.pic8, R.drawable.pic9,
R.drawable.pic10, R.drawable.pic11, R.drawable.pic12,
R.drawable.pic13, R.drawable.pic14, R.drawable.pic15,
R.drawable.pic16, R.drawable.pic17, R.drawable.pic18,
R.drawable.pic19, R.drawable.pic20, R.drawable.pic21,
R.drawable.pic22, R.drawable.pic23, R.drawable.pic24,
R.drawable.pic25, R.drawable.pic26, R.drawable.pic27,
R.drawable.pic28, R.drawable.pic29, R.drawable.pic30,
R.drawable.pic31, R.drawable.pic32, R.drawable.pic33,
R.drawable.pic34, R.drawable.pic35, R.drawable.pic36,
R.drawable.pic37, R.drawable.pic38, R.drawable.pic39,
R.drawable.pic40, R.drawable.pic41, R.drawable.pic42,
R.drawable.pic43, R.drawable.pic44, R.drawable.pic45,
R.drawable.pic46, R.drawable.pic47, R.drawable.pic48,
R.drawable.pic49, R.drawable.pic50, R.drawable.pic51,
R.drawable.pic52, R.drawable.pic53, R.drawable.pic54,
R.drawable.pic55, R.drawable.pic56, R.drawable.pic57,
R.drawable.pic58, R.drawable.pic59, R.drawable.pic60,
R.drawable.pic61, R.drawable.pic62, R.drawable.pic63,
R.drawable.pic64, R.drawable.pic65, R.drawable.pic66,
R.drawable.pic67, R.drawable.pic68, R.drawable.pic69,
R.drawable.pic70, R.drawable.pic71, R.drawable.pic72,
R.drawable.pic73, R.drawable.pic74, R.drawable.pic75,
R.drawable.pic76, R.drawable.pic77, };


String[] names = { "美图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"};
String sql = "create table pics(_id integer primary key autoincrement,name text,pic integer)";
db.execSQL(sql);


for (int i = 0; i < names.length; i++) {
String sql2 = "insert into pics (name,pic) values ('" + names[i]
+ "','" + images[i] + "')";
// ('"+image[x]+"','"+title[x]+"','"+content[x]+"')
db.execSQL(sql2);
}
}


@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {


}

}


2、Dao代码:

public class DbDao {


private MyDbOpenHelper helper;
private final int PAGESIZE = 10;
private SQLiteDatabase db;


public List<News> ObtainDB(Context context, int currentPage) {
int offset = 0;
offset = (currentPage - 1) * PAGESIZE;
helper = new MyDbOpenHelper(context);
db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("select pic,name from pics limit ?,?",
new String[] { offset + "", PAGESIZE + "" });
List<News> list = new ArrayList<News>();
while (cursor.moveToNext()) {
int pic = cursor.getInt(0);
String name = cursor.getString(1);
list.add(new News(pic, name));
}
return list;
}


public int MaxPage() {
Cursor cursor = db.rawQuery("select count(*) from pics", null);
int maxItem = 0;
while (cursor.moveToNext()) {
maxItem = cursor.getInt(0);
}
int max = maxItem % PAGESIZE == 0 ? maxItem / PAGESIZE : maxItem
/ PAGESIZE + 1;
return max;
}
}


3、实体类代码:

public class News {


@SerializedName("image")
int image;


@SerializedName("name")
String name;


public News(int image, String name) {
super();
this.image = image;
this.name = name;
}
}


4、Adapter代码:

public class MyAdapter extends BaseAdapter {


private List<News> list;
private Context context;


public MyAdapter(List<News> list, Context context) {
this.list = list;
this.context = context;
}


@Override
public int getCount() {
return list == null ? 0 : list.size();
}


@Override
public Object getItem(int position) {
return null;
}


@Override
public long getItemId(int position) {
return 0;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if (convertView == null) {
view = View.inflate(context, R.layout.item, null);
holder = new ViewHolder();
holder.image = (ImageView) view.findViewById(R.id.iv);
holder.name = (TextView) view.findViewById(R.id.tv);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
holder.image.setImageResource(list.get(position).image);
holder.name.setText(list.get(position).name);
return view;
}


class ViewHolder {
private ImageView image;
private TextView name;
}


public void setData(List<News> list2) {
this.list = list2;
notifyDataSetChanged();
}


}


5、MainActivity代码:

public class MainActivity extends Activity implements OnClickListener {


private ListView listView;
private SQLiteDatabase db;
private MyDbOpenHelper openHelper;
private ProgressDialog dialog;
private List<News> list = new ArrayList<News>();
private MyAdapter adapter;
private static final String TAG = "MainActivity";
private int i = 0;
private int currentPage = 1;
private int maxPage = 0;
private DbDao dao;
private Button nextPage;
private Button prePage;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
// 建立连接
openHelper = new MyDbOpenHelper(this);
// 当下面这个语句调用的时候才会创建数据库
db = openHelper.getWritableDatabase();
dao = new DbDao();
List<News> list2 = dao.ObtainDB(this, currentPage);
maxPage = dao.MaxPage();
adapter = new MyAdapter(list2, this);
listView.setAdapter(adapter);
}


private void initView() {
listView = (ListView) findViewById(R.id.listview);
nextPage = (Button) findViewById(R.id.btn_next);
prePage = (Button) findViewById(R.id.btn_pre);
nextPage.setOnClickListener(this);
prePage.setEnabled(false);
prePage.setOnClickListener(this);
dialog = new ProgressDialog(this);
}


private void initData() {
Cursor cursor = db.query("pics", new String[] { "pic", "name" }, null,
null, null, null, null);
while (cursor.moveToNext()) {
int pic = cursor.getInt(0);
String name = cursor.getString(1);
list.add(new News(pic, name));
}
listView.setAdapter(adapter);
}


public void AddOneData(View view) {
SQLiteDatabase db = openHelper.getWritableDatabase();
i++;
db.execSQL("insert into pics (pic,name) values ("
+ R.drawable.ic_launcher + ",'5" + i + "')");
db.close();
}


public void DeleteOneData(View view) {
SQLiteDatabase db = openHelper.getWritableDatabase();
db.execSQL("delete from pics where _id = 76");
db.close();
}


public void UpdateOnData(View view) {
SQLiteDatabase db = openHelper.getWritableDatabase();
db.execSQL("update pics set name = '测试' where _id = 77");
db.close();
}


public void QueryAllData(View view) {
list.clear();
adapter.setData(list);
Log.i(TAG, list.toString());
if (dialog != null) {
dialog.setMessage("查询中----");
dialog.show();
}
SQLiteDatabase db = openHelper.getReadableDatabase();
Cursor cursor = db.query("pics", new String[] { "pic", "name" }, null,
null, null, null, null);
while (cursor.moveToNext()) {
int pic = cursor.getInt(0);
String name = cursor.getString(1);
list.add(0, new News(pic, name));
}
adapter.setData(list);
dialog.dismiss();
cursor.close();
db.close();
}


@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_pre:
currentPage--;
nextPage.setEnabled(true);
if (currentPage < 2) {
prePage.setEnabled(false);
currentPage = 1;
}


break;
case R.id.btn_next:
currentPage++;
prePage.setEnabled(true);
if (currentPage > maxPage - 1) {
nextPage.setEnabled(false);
currentPage = maxPage;
}
break;


default:
break;
}
List<News> list2 = dao.ObtainDB(MainActivity.this, currentPage);
// 上面这个list不要写成了list,不然就是上面那个list,尽量写一个新名字
// 这里拿到数据之后,要给适配器,但是不能new一个,不然就有事一个新的适配器。
// 所以要用到实体类的set方法,来讲数据传给适配器,在适配器层增加一个set方法
adapter.setData(list2);
// 之后就必须刷新适配器
}
}


6、MainActivity xml代码:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >


    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:orientation="horizontal" >


            <Button
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="AddOneData"
                android:text="增"
                android:textSize="20sp" />


            <Button
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="DeleteOneData"
                android:text="删"
                android:textSize="20sp" />


            <Button
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="UpdateOnData"
                android:text="改"
                android:textSize="20sp" />


            <Button
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="QueryAllData"
                android:text="查"
                android:textSize="20sp" />
        </LinearLayout>


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal"
            android:paddingBottom="5dp" >


            <Button
                android:id="@+id/btn_pre"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:text="上一页"
                android:textSize="20sp" />


            <Button
                android:id="@+id/btn_next"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:onClick="NextPage"
                android:text="下一页"
                android:textSize="20sp" />
        </LinearLayout>
    </RelativeLayout>


</FrameLayout>



7、Item xml 代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView
        android:layout_width="match_parent"
        android:layout_height="80dp"
        android:src="@drawable/ic_launcher"
        android:scaleType="centerInside"
        android:id="@+id/iv"/>
    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="图片名称"
        android:id="@+id/tv"/>


</LinearLayout>

0 0
原创粉丝点击