zoukankan      html  css  js  c++  java
  • Android入门教程(三十一)SQLite分页读取(转)

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

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

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

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

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

    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的源码如下:

     

    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>  

    本文程序源码如下:

    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. }    
  • 相关阅读:
    Form.KeyPreview 属性
    键盘输入、鼠标输入、焦点处理
    KeyDown,KeyPress 和KeyUp
    C#反射实例应用--------获取程序集信息和通过类名创建类实例
    Attribute操作的性能优化方式
    OBjective-C:atomic和nonatomic的区别
    Objective-C:OC内部可变对象和不可变对象的深(复制)拷贝问题思考:
    Objective-C:三种文件导入的方式比较
    Objective-C:保留计数器思想的详解(对象的保留和所有权的释放)
    Objective-C:深复制(拷贝)
  • 原文地址:https://www.cnblogs.com/l_dragon/p/2134880.html
Copyright © 2011-2022 走看看