編輯:Android 開發實例
Android 內建 SQLite,省下自行移植資料庫的功夫。SQLite 支援大部分 SQL92 標準,常用的指令都能直接用;除此之外 Android 也包裝了一批便利方法簡化操作。不過如果你有跨平台需求,建議還是寫標準 SQL——移植時會省事很多。
本文示範 SQLite 的基本操作(建立資料庫、建表、插入、查詢、關閉),並用 GridView 做一個分頁列,把大量資料分頁顯示。
執行結果:

整篇文章最重要的就這一句:
select * from stu Limit 10 Offset 20;
意思是「從 stu 表取資料,跳過前 20 筆,取 10 筆」。Limit 決定每頁筆數,Offset 決定起點。分頁本質上就是這兩個數字的排列組合,沒有更多魔法。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://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>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://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>
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; // 插入時的 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();
}
}
}
/**
* 讀取指定分頁的資料
* 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());
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();
}
}
這份範例把重點放在分頁語法,但有幾處在真實專案中會出問題,值得逐一說明。
SQL 字串拼接是 SQL Injection 的溫床。程式中把 id 直接用字串併進 SQL,只要有一個欄位是使用者輸入,就有被攻擊的風險。正確做法是改用 db.query() 搭配 selectionArgs,或 SQLiteStatement 的 bindString(),讓參數走綁定而非拼接。
大偏移量的效能問題。Offset 100000 這類寫法,SQLite 仍須掃過前面十萬筆才能丟掉,越後面的頁越慢。資料量很大時應改為「鍵集分頁」(keyset pagination):select * from stu where id > ? order by id limit 10,用上一頁最後一個 id 當游標,速度與頁碼無關。
id 欄位型別不當。範例把 id 定義成 text,這會讓排序變成字典序("10" 排在 "9" 前面)。主鍵應使用 INTEGER PRIMARY KEY AUTOINCREMENT。
沒有索引。分頁查詢若沒在排序欄位上建索引,每次都要全表排序。記得 CREATE INDEX。
Cursor 與 db 未妥善關閉。範例在 Activity 銷毀時沒有關閉 db,長時間運行會累積洩漏。應在 onDestroy 中處理。
AsyncTask 是必要的。所有資料庫操作都應該離開主執行緒,否則資料量大時會直接 ANR。範例同步執行只因為是 demo。
最後談架構:現在的 Android 早已不建議直接操作 SQLiteDatabase。官方方案是 Room persistence library——你只要定義 Entity 與 DAO 介面,它會在編譯期產生實作碼並做 SQL 驗證,還原生支援 LiveData / Flow 的非同步查詢與分頁。搭配 Paging 3 函式庫,本文手刻的「Limit / Offset + GridView 分頁列」整套邏輯都能自動化,還能處理資料持續變動的情況。
Android 五大布局完整指南:FrameLayout、LinearLayout、AbsoluteLayout、RelativeLayout、TableLayout
Android 常見五大布局包括 FrameLayout、LinearLayout、AbsoluteLayout、RelativeLayout 與 TableLayout
Android 本地化指南:讓應用適應不同語言環境
Android 應用可能在不同語言環境的裝置上執行。若要讓應用更貼近使用者,應將文字、數字與其他資源本地化。最常見的做法是把字串放入不同 values 資料夾。 建立本地
Android 登錄實例:建立登入介面並管理錯誤嘗試
登入應用程式的畫面會要求使用者輸入憑證,才能登入某個特定的應用,例如 Facebook、微博等服務。 本章介紹如何建立一個登入介面,以及如何管理安全問題與錯誤嘗試次數。
Android 登入介面設計與安全性防呆
登入畫面看似只是兩個輸入框加一顆按鈕,但它同時承担了使用者體驗與安全防線兩個角色。做得好,使用者一眼就知道怎麼填;做得馬虎,帳號被暴力破解也只是時間問題。 本文會把版面