Android提高之SQLite分页读取实现方法
作者:shichen2014 发布时间:2022-11-28 22:44:04
标签:Android,SQLite
一般来说,Android自身就包含了常用于嵌入式系统的SQLite,这样就免去了开发者自己移植安装的功夫。SQLite 支持多数SQL92标准,很多常用的SQL命令都能在SQLite上面使用,除此之外Android还提供了一系列自定义的方法去简化对SQLite数据库的操作。不过有跨平台需求的程序还是建议使用标准的SQL语句,毕竟这样容易在多个平台之间进行移植。
先来贴出本文程序运行的结果图:
本文实例程序主要讲解了SQLite的基本用法,如:创建数据库,使用SQL命令查询数据表、插入数据,关闭数据库,以及使用GridView实现了一个分页栏(关于GridView的用法),用于把数据分页显示。
分页栏的pagebuttons.xml的源码如下:
<?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的源码如下:
<?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程序源码如下:
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项目开发起到一定的参考借鉴作用。


猜你喜欢
- ToggleButton开关状态按钮控件使用方法,具体内容如下一、简介1、2、ToggleButton类结构父类是CompoundButto
- 一、Android系统启动Android设备从按下开机键到桌面显示画面,大致过程如下图流程:开机显示桌面、从桌面点击 App 图标到 Act
- 本文实例讲述了Android实现手机壁纸改变的方法。分享给大家供大家参考。具体如下:main.xml布局文件:<?xml versio
- 注:由于工作需要, 也是第一次接触到打印机的相关内容, 凑巧, 通过找了很多资料和帮助后, 也顺利的解决了打印标签的问题(标签的表面信息[二
- 这段时间花了点时间整理了几个新手易犯的典型缺陷(专门针对C#的),但是个人的力量毕竟有限缺陷的覆盖面比较窄,有些缺陷的描述也不够准确,这里先
- 目录基于Java的guava开源库工具类1、guava的maven配置引入 2、LoadingCache3、Multimap 和
- c#异步操作,BackgroundWorker类的使用,可以在后台运行需要的代码逻辑。using System;using System.C
- 这篇文章主要介绍了SpringBoot2整合activiti6环境搭建过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定
- 一、MVC架构1、MVC是什么MVC是模型Model、视图View和控制器Controller的简称,是一种架构规范降低了业务逻辑与视图之间
- 纯Java代码模拟Hibernate一级缓存原理,简单易懂。import java.util.ArrayList;import java.u
- 上一篇文章讲解了Spring Cloud 整合 nacos 实现服务注册与发现,nacos除了有服务注册与发现的功能,还有提供动态配置服务的
- 目录背景介绍项目介绍需要知识点启动项目项目示范核心讲解核心原理功能分析分块上传秒传功能断点续传总结参考文献背景介绍 Breakpoint-
- 1.简介if判断语句是很多编程语言的重要组成部分。但是,若我们最终编写了大量嵌套的if语句,这将使得我们的代码更加复杂和难以维护。让我们看看
- 1. 抽象类关键字:abstract类:用来描述一类具体的事物抽象类:抽象的、模糊的、不具体的类在Java的普通类中是不允许多继承的,原因是
- 在android开发中,一说起线程的使用,很多人马上想到new Thread(){...}.start()这种方式。这样使用当然可以,但是多
- 1. 运行环境 Enviroment当 MyBatis 与不同的应用结合时,需要不同的事务管理机制。与 Spring 结合时,由 Sprin
- 1.OpenFileDialogprivate void btnOpen_Click(object sender, EventArgs e)
- 项目开发中对于一些数据的处理需要用到多线程,比如文件的批量上传,数据库的分批写入,大文件的分段下载等。 通常会使用spring自带的线程池处
- 微信公众平台对信息做了比较清晰的分类,最基本的包括请求(Request)和响应(Response)两大类信息,这两类信息有分为文字、语音、图
- 预加载bean在springBoot启动过程中就完成创建加载在AbstractApplicationContext的refresh方法中//