Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 進階第八篇:SQLite 分頁讀取入門

編輯:Android 開發實例

Android 把 SQLite 直接放進了系統裡,開發者不必自己移植、安裝資料庫引擎,一行 import 就能用。SQLite 支援大多數 SQL92 標準,常用的 CREATE、INSERT、SELECT 都能原封不動搬過來;除此之外 Android 還包了一層 API(SQLiteDatabase、SQLiteOpenHelper)讓操作更省事。

這裡有個實務上的取捨:如果產品有跨平台打算,SQL 盡量寫標準語法,不要依賴 Android 特有的包裝方法,日後移植到 iOS 或其它平台會省下大量重寫成本。

這篇要做什麼

把 SQLite 最基礎的四件事跑一遍——建庫、建表、插入、關閉——然後加上分頁:用 Limit / Offset 每次只撈一頁資料,再用 GridView 做一排頁碼按鈕,點第幾頁就顯示第幾頁。下一篇會把這套分頁邏輯連同表格呈現一起封裝成獨立控件。

分頁的 SQL 是怎麼寫的

關鍵語句是這樣:

Select * From TABLE_NAME Limit 9 Offset 10;

讀法:從 TABLE_NAME 取出資料,跳過前 10 列,取 9 列。換算成程式碼就是——第 n 頁的 Offset 等於 n × PageSize。這種寫法的好處是不必把整張表都讀進記憶體,Cursor 只承載一頁的份量。

pagebuttons.xml:頁碼按鈕的格子

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="4dip">

    <TextView
        android:id="@+id/ItemText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="TextView01" />
</RelativeLayout>

main.xml:版面配置

三個按鈕負責資料庫生命週期,一個 EditText 顯示分頁結果,最下方那條 32dip 高的 GridView 就是分頁欄。android:numColumns="auto_fit" 搭配 columnWidth="40dip",按鈕會依寬度自動換行排列。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/btnCreateDB"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="創建數據庫" />

    <Button
        android:id="@+id/btnInsertRec"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="插入一串實驗數據" />

    <Button
        android:id="@+id/btnClose"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="關閉數據庫" />

    <EditText
        android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="256dip" />

    <GridView
        android:id="@+id/gridview"
        android:layout_width="fill_parent"
        android:layout_height="32dip"
        android:columnWidth="40dip"
        android:numColumns="auto_fit"></GridView>
</LinearLayout>

程式碼:testSQLite.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 {

    Button btnCreateDB, btnInsert, btnClose;
    EditText edtSQL;                    // 顯示分頁資料
    SQLiteDatabase db;
    int 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;   // 分頁欄資料源

    @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>>();

        saPageID = new SimpleAdapter(testSQLite.this,
                lstPageID,
                R.layout.pagebuttons,
                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();
            }
        }
    }

    /**
     * 讀取指定頁的資料
     * SQL: Select * From TABLE_NAME Limit 9 Offset 10;
     * 表示跳過 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());
        Log.e("DB amount", String.valueOf(databaseList().length));

        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();
    }
}

幾個容易踩到的細節

id 必須是全域變數

InsertRecord() 用一個持續累加的 id 當主鍵,所以宣告在 Activity 層級。若放在方法內當區域變數,每次點按鈕都會從 0 重新開始,馬上撞主鍵衝突。

頁數計算記得向上取整

(int)(recSize / PageSize) + 1 在筆數剛好整除時會多算一頁(例如 16 筆、每頁 10 筆算出 2 頁,但 20 筆時會算出 3 頁,其中一頁是空的)。正式環境建議改成 (int) Math.ceil((double) recSize / PageSize)。

Cursor 用完就關

這支範例把資料攤平成字串塞進 EditText,所以讀完立刻 close()。若改成把 Cursor 直接交給 CursorAdapter,Cursor 的生命週期就要跟著 ListView 走,不能提早關閉。

在記憶體建庫只是為了示範

SQLiteDatabase.create(null) 會開一個暫 reside 的記憶體資料庫,程式結束資料就消失。真實專案請改用 SQLiteOpenHelper 管理 onCreate / onUpgrade,並把資料庫檔放在應用程式私有目錄下。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved