服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android提高之SQLite分页读取实现方法

Android提高之SQLite分页读取实现方法

2021-03-06 23:30Android开发网 Android

这篇文章主要介绍了Android的SQLite分页读取实现方法,在Android项目开发中非常实用,需要的朋友可以参考下

一般来说,android自身就包含了常用于嵌入式系统的sqlite,这样就免去了开发者自己移植安装的功夫。sqlite 支持多数sql92标准,很多常用的sql命令都能在sqlite上面使用,除此之外android还提供了一系列自定义的方法去简化对sqlite数据库的操作。不过有跨平台需求的程序还是建议使用标准的sql语句,毕竟这样容易在多个平台之间进行移植。

先来贴出本文程序运行的结果图:

Android提高之SQLite分页读取实现方法

本文实例程序主要讲解了sqlite的基本用法,如:创建数据库,使用sql命令查询数据表、插入数据,关闭数据库,以及使用gridview实现了一个分页栏(关于gridview的用法),用于把数据分页显示。

分页栏的pagebuttons.xml的源码如下:

?
1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="wrap_content" android:paddingbottom="4dip"
 android:layout_width="fill_parent">
 <textview android:layout_width="wrap_content"
 android:layout_below="@+id/itemimage" android:layout_height="wrap_content"
 android:text="textview01" android:layout_centerhorizontal="true"
 android:id="@+id/itemtext">
 </textview>
</relativelayout>

main.xml的源码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical" android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <button android:layout_height="wrap_content"
 android:layout_width="fill_parent" android:id="@+id/btncreatedb"
 android:text="创建数据库"></button>
 <button android:layout_height="wrap_content"
 android:layout_width="fill_parent" android:text="插入一串实验数据" android:id="@+id/btninsertrec"></button>
 <button android:layout_height="wrap_content" android:id="@+id/btnclose"
 android:text="关闭数据库" android:layout_width="fill_parent"></button>
 <edittext android:text="@+id/edittext01" android:id="@+id/edittext01"
 android:layout_width="fill_parent" android:layout_height="256dip"></edittext>
 <gridview android:id="@+id/gridview" android:layout_width="fill_parent"
 android:layout_height="32dip" android:numcolumns="auto_fit"
 android:columnwidth="40dip"></gridview>
</linearlayout>

java程序源码如下:

?
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
package com.testsqlite;
import java.util.arraylist;
import java.util.hashmap;
import android.app.activity;
import android.database.cursor;
import android.database.sqlexception;
import android.database.sqlite.sqlitedatabase;
import android.os.bundle;
import android.util.log;
import android.view.view;
import android.widget.adapterview;
import android.widget.adapterview.onitemclicklistener;
import android.widget.button;
import android.widget.edittext;
import android.widget.gridview;
import android.widget.simpleadapter;
public class testsqlite extends activity {
  /** called when the activity is first created. */
  button btncreatedb, btninsert, btnclose;
  edittext edtsql;//显示分页数据
  sqlitedatabase db;
  int id;//添加记录时的id累加标记,必须全局
  static final int pagesize=10;//分页时,每页的数据总数
  private static final string table_name = "stu";
  private static final string id = "id";
  private static final string name = "name";
  simpleadapter sapageid;// 分页栏适配器
  arraylist<hashmap<string, string>> lstpageid;// 分页栏的数据源,与pagesize和数据总数相关
  @override
  public void oncreate(bundle savedinstancestate) {
    super.oncreate(savedinstancestate);
    setcontentview(r.layout.main);
    btncreatedb = (button) this.findviewbyid(r.id.btncreatedb);
    btncreatedb.setonclicklistener(new clickevent());
    btninsert = (button) this.findviewbyid(r.id.btninsertrec);
    btninsert.setonclicklistener(new clickevent());
    btnclose = (button) this.findviewbyid(r.id.btnclose);
    btnclose.setonclicklistener(new clickevent());
    edtsql=(edittext)this.findviewbyid(r.id.edittext01);
    gridview gridview = (gridview) findviewbyid(r.id.gridview);//分页栏控件
    // 生成动态数组,并且转入数据
    lstpageid = new arraylist<hashmap<string, string>>();
    // 生成适配器的imageitem <====> 动态数组的元素,两者一一对应
    sapageid = new simpleadapter(testsqlite.this, // 没什么解释
        lstpageid,// 数据来源
        r.layout.pagebuttons,//xml实现
        new string[] { "itemtext" },
        new int[] { r.id.itemtext });
 
    // 添加并且显示
    gridview.setadapter(sapageid);
    // 添加消息处理
    gridview.setonitemclicklistener(new onitemclicklistener(){
      @override
      public void onitemclick(adapterview<?> arg0, view arg1, int arg2,
          long arg3) {
        loadpage(arg2);//根据所选分页读取对应的数据
      }
    });
  }
  class clickevent implements view.onclicklistener {
    @override
    public void onclick(view v) {
      if (v == btncreatedb) {
        createdb();
      } else if (v == btninsert) {
        insertrecord(16);//插入16条记录
        refreshpage();
      }else if (v == btnclose) {
        db.close();
      }
    }
  }
  /*
   * 读取指定id的分页数据
   * sql:select * from table_name limit 9 offset 10;
   * 表示从table_name表获取数据,跳过10行,取9行
   */
  void loadpage(int pageid)
  {
    string sql= "select * from " + table_name + 
    " limit "+string.valueof(pagesize)+ " offset " +string.valueof(pageid*pagesize);
    cursor rec = db.rawquery(sql, null);
    settitle("当前分页的数据总数:"+string.valueof(rec.getcount()));
    // 取得字段名称
    string title = "";
    int colcount = rec.getcolumncount();
    for (int i = 0; i < colcount; i++)
      title = title + rec.getcolumnname(i) + "   ";
    // 列举出所有数据
    string content="";
    int reccount=rec.getcount();
    for (int i = 0; i < reccount; i++) {//定位到一条数据
      rec.movetoposition(i);
      for(int ii=0;ii<colcount;ii++)//定位到一条数据中的每个字段
      {
        content=content+rec.getstring(ii)+"   ";
      }
      content=content+"/r/n";
    }
     
    edtsql.settext(title+"/r/n"+content);//显示出来
    rec.close();
  }
  /*
   * 在内存创建数据库和数据表
   */
  void createdb() {
    // 在内存创建数据库
    db = sqlitedatabase.create(null);
    log.e("db path", db.getpath());
    string amount = string.valueof(databaselist().length);
    log.e("db amount", amount);
    // 创建数据表
    string sql = "create table " + table_name + " (" + id
        + " text not null, " + name + " text not null " + ");";
    try {
      db.execsql("drop table if exists " + table_name);
      db.execsql(sql);
    } catch (sqlexception e) {}
  }
  /*
   * 插入n条数据
   */
  void insertrecord(int n) {
    int total = id + n;
    for (; id < total; id++) {
      string sql = "insert into " + table_name + " (" + id + ", " + name
          + ") values('" + string.valueof(id) + "', 'test');";
      try {
        db.execsql(sql);
      } catch (sqlexception e) {
      }
    }
  }
  /*
   * 插入之后刷新分页
   */
  void refreshpage()
  {
    string sql = "select count(*) from " + table_name;
    cursor rec = db.rawquery(sql, null);
    rec.movetolast();
    long recsize=rec.getlong(0);//取得总数
    rec.close();
    int pagenum=(int)(recsize/pagesize) + 1;//取得分页数
     
    lstpageid.clear();
    for (int i = 0; i < pagenum; i++) {
      hashmap<string, string> map = new hashmap<string, string>();
      map.put("itemtext", "no." + string.valueof(i));
      lstpageid.add(map);
    }
    sapageid.notifydatasetchanged();
  }
}

感兴趣的读者可以动手测试一下本实例代码,希望能对大家进行android项目开发起到一定的参考借鉴作用。

延伸 · 阅读

精彩推荐