Android提高第八篇之SQLite分页读取

news/2023/12/9 16:06:08

http://blog.csdn.net/hellogv/archive/2010/11/16/6011934.aspx

 

 

本文来自http://blog.csdn.net/hellogv/ ,引用必须注明出处!

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

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

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

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

view plain copy to clipboard print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_height="wrap_content" android:paddingBottom="4dip"  
  4.     android:layout_width="fill_parent">  
  5.     <TextView android:layout_width="wrap_content"  
  6.         android:layout_below="@+id/ItemImage" android:layout_height="wrap_content"  
  7.         android:text="TextView01" android:layout_centerHorizontal="true"  
  8.         android:id="@+id/ItemText">  
  9.     </TextView>  
  10. </RelativeLayout>    

 

main.xml的源码如下:

 

view plain copy to clipboard print ?
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical" android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent">  
  5.     <Button android:layout_height="wrap_content"  
  6.         android:layout_width="fill_parent" android:id="@+id/btnCreateDB"  
  7.         android:text="创建数据库"></Button>  
  8.     <Button android:layout_height="wrap_content"  
  9.         android:layout_width="fill_parent" android:text="插入一串实验数据" android:id="@+id/btnInsertRec"></Button>  
  10.     <Button android:layout_height="wrap_content" android:id="@+id/btnClose"  
  11.         android:text="关闭数据库" android:layout_width="fill_parent"></Button>  
  12.     <EditText android:text="@+id/EditText01" android:id="@+id/EditText01"  
  13.         android:layout_width="fill_parent" android:layout_height="256dip"></EditText>  
  14.     <GridView android:id="@+id/gridview" android:layout_width="fill_parent"  
  15.         android:layout_height="32dip" android:numColumns="auto_fit"  
  16.         android:columnWidth="40dip"></GridView>  
  17. </LinearLayout>  

 

本文程序源码如下:

view plain copy to clipboard print ?
  1. package com.testSQLite;    
  2.     
  3. import java.util.ArrayList;    
  4. import java.util.HashMap;    
  5. import android.app.Activity;    
  6. import android.database.Cursor;    
  7. import android.database.SQLException;    
  8. import android.database.sqlite.SQLiteDatabase;    
  9. import android.os.Bundle;    
  10. import android.util.Log;    
  11. import android.view.View;    
  12. import android.widget.AdapterView;    
  13. import android.widget.AdapterView.OnItemClickListener;    
  14. import android.widget.Button;    
  15. import android.widget.EditText;    
  16. import android.widget.GridView;    
  17. import android.widget.SimpleAdapter;    
  18.     
  19. public class testSQLite extends Activity {    
  20.     /** Called when the activity is first created. */    
  21.     Button btnCreateDB, btnInsert, btnClose;    
  22.     EditText edtSQL;//显示分页数据    
  23.     SQLiteDatabase db;    
  24.     int id;//添加记录时的id累加标记,必须全局    
  25.     static final int PageSize=10;//分页时,每页的数据总数    
  26.     private static final String TABLE_NAME = "stu";    
  27.     private static final String ID = "id";    
  28.     private static final String NAME = "name";    
  29.         
  30.     SimpleAdapter saPageID;// 分页栏适配器    
  31.     ArrayList<HashMap<String, String>> lstPageID;// 分页栏的数据源,与PageSize和数据总数相关    
  32.     
  33.     @Override    
  34.     public void onCreate(Bundle savedInstanceState) {    
  35.         super.onCreate(savedInstanceState);    
  36.         setContentView(R.layout.main);    
  37.         btnCreateDB = (Button) this.findViewById(R.id.btnCreateDB);    
  38.         btnCreateDB.setOnClickListener(new ClickEvent());    
  39.     
  40.         btnInsert = (Button) this.findViewById(R.id.btnInsertRec);    
  41.         btnInsert.setOnClickListener(new ClickEvent());    
  42.     
  43.         btnClose = (Button) this.findViewById(R.id.btnClose);    
  44.         btnClose.setOnClickListener(new ClickEvent());    
  45.             
  46.         edtSQL=(EditText)this.findViewById(R.id.EditText01);    
  47.             
  48.         GridView gridview = (GridView) findViewById(R.id.gridview);//分页栏控件    
  49.         // 生成动态数组,并且转入数据    
  50.         lstPageID = new ArrayList<HashMap<String, String>>();    
  51.     
  52.         // 生成适配器的ImageItem <====> 动态数组的元素,两者一一对应    
  53.         saPageID = new SimpleAdapter(testSQLite.this// 没什么解释    
  54.                 lstPageID,// 数据来源    
  55.                 R.layout.pagebuttons,//XML实现    
  56.                 new String[] { "ItemText" },    
  57.                 new int[] { R.id.ItemText });    
  58.     
  59.         // 添加并且显示    
  60.         gridview.setAdapter(saPageID);    
  61.         // 添加消息处理    
  62.         gridview.setOnItemClickListener(new OnItemClickListener(){    
  63.     
  64.             @Override    
  65.             public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,    
  66.                     long arg3) {    
  67.                 LoadPage(arg2);//根据所选分页读取对应的数据    
  68.             }    
  69.         });    
  70.     
  71.     }    
  72.     
  73.         
  74.     class ClickEvent implements View.OnClickListener {    
  75.     
  76.         @Override    
  77.         public void onClick(View v) {    
  78.             if (v == btnCreateDB) {    
  79.                 CreateDB();    
  80.             } else if (v == btnInsert) {    
  81.                 InsertRecord(16);//插入16条记录    
  82.                 RefreshPage();    
  83.             }else if (v == btnClose) {    
  84.                 db.close();    
  85.             }    
  86.         }    
  87.     
  88.     }    
  89.         
  90.     
  91.     /*  
  92.      * 读取指定ID的分页数据  
  93.      * SQL:Select * From TABLE_NAME Limit 9 Offset 10;  
  94.      * 表示从TABLE_NAME表获取数据,跳过10行,取9行  
  95.      */    
  96.     void LoadPage(int pageID)    
  97.     {    
  98.         String sql= "select * from " + TABLE_NAME +     
  99.         " Limit "+String.valueOf(PageSize)+ " Offset " +String.valueOf(pageID*PageSize);    
  100.         Cursor rec = db.rawQuery(sql, null);    
  101.     
  102.         setTitle("当前分页的数据总数:"+String.valueOf(rec.getCount()));    
  103.             
  104.         // 取得字段名称    
  105.         String title = "";    
  106.         int colCount = rec.getColumnCount();    
  107.         for (int i = 0; i < colCount; i++)    
  108.             title = title + rec.getColumnName(i) + "     ";    
  109.     
  110.             
  111.         // 列举出所有数据    
  112.         String content="";    
  113.         int recCount=rec.getCount();    
  114.         for (int i = 0; i < recCount; i++) {//定位到一条数据    
  115.             rec.moveToPosition(i);    
  116.             for(int ii=0;ii<colCount;ii++)//定位到一条数据中的每个字段    
  117.             {    
  118.                 content=content+rec.getString(ii)+"     ";    
  119.             }    
  120.             content=content+"/r/n";    
  121.         }    
  122.             
  123.         edtSQL.setText(title+"/r/n"+content);//显示出来    
  124.         rec.close();    
  125.     }    
  126.         
  127.     /*  
  128.      * 在内存创建数据库和数据表  
  129.      */    
  130.     void CreateDB() {    
  131.         // 在内存创建数据库    
  132.         db = SQLiteDatabase.create(null);    
  133.         Log.e("DB Path", db.getPath());    
  134.         String amount = String.valueOf(databaseList().length);    
  135.         Log.e("DB amount", amount);    
  136.         // 创建数据表    
  137.         String sql = "CREATE TABLE " + TABLE_NAME + " (" + ID    
  138.                 + " text not null, " + NAME + " text not null " + ");";    
  139.         try {    
  140.             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);    
  141.             db.execSQL(sql);    
  142.         } catch (SQLException e) {}    
  143.     }    
  144.     
  145.     /*  
  146.      * 插入N条数据  
  147.      */    
  148.     void InsertRecord(int n) {    
  149.         int total = id + n;    
  150.         for (; id < total; id++) {    
  151.             String sql = "insert into " + TABLE_NAME + " (" + ID + ", " + NAME    
  152.                     + ") values('" + String.valueOf(id) + "', 'test');";    
  153.             try {    
  154.                 db.execSQL(sql);    
  155.             } catch (SQLException e) {    
  156.             }    
  157.         }    
  158.     }    
  159.     
  160.     /*  
  161.      * 插入之后刷新分页  
  162.      */    
  163.     void RefreshPage()    
  164.     {    
  165.         String sql = "select count(*) from " + TABLE_NAME;    
  166.         Cursor rec = db.rawQuery(sql, null);    
  167.         rec.moveToLast();    
  168.         long recSize=rec.getLong(0);//取得总数    
  169.         rec.close();    
  170.         int pageNum=(int)(recSize/PageSize) + 1;//取得分页数    
  171.             
  172.         lstPageID.clear();    
  173.         for (int i = 0; i < pageNum; i++) {    
  174.             HashMap<String, String> map = new HashMap<String, String>();    
  175.             map.put("ItemText""No." + String.valueOf(i));  
  176.     
  177.             lstPageID.add(map);    
  178.         }    
  179.         saPageID.notifyDataSetChanged();    
  180.     }    
  181. }    

 


http://www.niftyadmin.cn/n/4488238.html

相关文章

ADO.NET Entity FrameWork 学习笔记之集合运算符(转载)

Entity SQL中存在许多集合类型的数据&#xff0c;因此&#xff0c;集合操作在Entity SQL中也比较重要。本文介绍Entity SQL中常用的集合运算符。 阅读本文前注意&#xff0c;首先约定&#xff0c;这里的集合可以包含重复元素&#xff0c;而非我们平时所说的不包含重复元素的集…

手机产品交互体验评估方法

摘要: 交互设计是一个迭代过程&#xff0c;通过交互设计评估&#xff0c;可以及早发现设计中缺陷&#xff0c;进而能进一步完善交互流程。通过评价&#xff0c;也可发现交互设计中可行、友善、合理或优秀的地方&#xff0c;从而为后续产品的交互设计提供借鉴。 手机产品交互设计…

avi的index段

假如要将avi文件分成头、中、尾的话&#xff0c;RRFT开始到movi段之间应该算是头&#xff0c;movi算是中间&#xff0c;index就算是尾部了。index其实就是movi中的内容的索引&#xff0c;作用是在拖动视频进度条时&#xff0c;能让解码器迅速定位到要找的视频帧。索引以“idx1”…

NTP协议原理简介

关键字: UTT 艾泰HiPER 网关 路由器 防火墙 网络时间协议&#xff08;network time protocol&#xff0c;简称ntp&#xff09;是用来在整个网络内发布精确时间的tcp/ip 协议&#xff0c;其本身的传输基于udp。其基本原理如下&#xff1a; 上图所示的是ntp 基本工作原理&#…

(翻译)LearnVSXNow! #9 - 创建一个工具集 - 重构服务

在第6和第7部分我们创建了一个StartupToolset示例package&#xff0c;并手动添加了菜单命令和Calculate tool window。本文将重构package&#xff0c;尝试基于服务的代码结构。 重构这个package不仅适用现在这个package&#xff0c;而且能提取那些在今后的package开发中可…

Android开发经验汇总(持续补充中...)

Android 中文 API (android.widget合集-上) : http://www.cnblogs.com/over140/archive/2010/11/01/1865895.html 1. 默认情况用户按下Back键是不会销毁当前Activity的,Activity依旧存在于内存中,如果想要彻底kill掉这个程序可以在代码中做如下处理: 1Override<br> pu…

NCrawler老是出问题,头痛……

需要做一个爬虫&#xff0c;最开始看到网上对larbin评价不错&#xff0c;就想着在它的基础上改改&#xff0c;结果后来发现我这个从来没在linux上做过开发的人&#xff0c;这么一下在上手效率是在太低。 想找个基于Windows的C或者C的开源爬虫结果没发现有合适的。于是不得已只能…

FCKEditor2.6 for PHP 程序配置

一、下载 1、首先去官网下载FCKeditor2.6.6 多国语言版&#xff08;可以搜索“FCKeditor 2.6.6, released on 15 February 2010”&#xff09;。下载地址&#xff1a; http://ckeditor.com/download。 二、精简 按照如下步骤删除其中一些不需要的测试文件&#xff1a; 1.只保留…

JavaScript实现二叉树的遍历(层次,前,中,后)

JavaScript实现二叉树的遍历&#xff08;层次&#xff0c;前&#xff0c;中&#xff0c;后&#xff09;废话不多说&#xff0c;直接上代码提示废话不多说&#xff0c;直接上代码 <script>//节点 function Node(element, left, right,parents) {this.element element;th…

JavaScript实现给定两个数组,将第二个数组与第一个数组重复得元素,从第一个数组中删除。

JavaScript实现给定两个数组&#xff0c;将第二个数组与第一个数组重复得元素&#xff0c;从第一个数组中删除。首先 今天碰到一个这么个算法题&#xff0c;拿到题之后&#xff0c;脑子里就出现了关于数组的函数 splice(index,howmany,item1,…,itemX) 意思可向数组中添加或删…

新MGDN论坛(NewMGDN.com)重新上线

约两个月以前&#xff0c;MGDN论坛因未知原因突然不能访问。经查&#xff0c;原来所在服务器因备案原因被关闭&#xff0c;不能继续提供服务。这期间我一直在寻求服务器资源和托管空间。经过n长时间的反复折腾&#xff0c;MGDN终于获得新生&#xff0c;重新上线了&#xff0c; …

楼梯有n个台阶,一共有多少种上楼的方法?

楼梯有n个台阶&#xff0c;上楼可以一步上1阶&#xff0c;也可以一步上两阶。一共有多少种上楼的方法&#xff1f;一、前言 看到这么个题目时&#xff0c;一脸懵逼&#xff0c;不知道说的啥意思&#xff0c;然后就多读了两边题目发现&#xff0c;如果有一阶楼梯&#xff0c;那…

一封寫給兒子的信

一封寫給兒子的信 早上看到一个台湾的朋友发来的邮件&#xff0c;分享一个父亲写给儿子的话&#xff0c;我想这不止是一个父亲对儿子的谆谆教导&#xff0c;也是对所有人都劝慰。 人应当学会感恩&#xff0c;更应学会释怀&#xff0c;这样才会过多轻松。 &#xff5e;&#xf…

Android NDK 使用第一步,编译c文件,声明jni并调用。

版权声明&#xff1a;转载时请以超链接形式标明文章原始出处和作者信息及本声明http://eshock.blogbus.com/logs/61459223.html 我照这篇文章的方法已经成功编译并运行了程序&#xff0c;大家有问题的可以留言问我。 Android NDK学习笔记 前言 Android系统中的应用程序都是用…

JavaScript之写一个函数,检查字符是否是整数,如果是,返回其整数值。

写一个函数&#xff0c;检查字符是否是整数&#xff0c;如果是&#xff0c;返回其整数值。这里面啊&#xff0c;主要运用到isNaN() 这个js基础函数&#xff0c;它的意思就是用于检查其参数是否是非数字值 如果 m 是特殊的非数字值 NaN&#xff08;或者能被转换为这样的值&#…

Hbuliderz之npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。

项目场景&#xff1a; 今天写了个egg.js做服务端接口&#xff0c;本想着用同一个vscode打开不方便查看&#xff0c;就下载了个Hbulider来启动服务&#xff0c;谁知出毛病了&#xff0c;没法运行 问题描述&#xff1a; 就是在执行npm run dev的时候报了如下的错误 npm : 无法…
最新文章