編輯:關於 Android 程式設計
對於大量、重複且具固定結構的資料,SQLite 是最合適的儲存方案。本文以一個聯絡人管理的 Demo 為例,說明 Contract 類別、SQLiteOpenHelper 的使用,以及增刪改查四種操作。
1. 使用 SQL Helper 建立資料庫。
2. 資料的增刪改查(Put、Read、Delete、Update)。
Contract Class 又叫 Companion Class,是集中定義 URI、表名與欄位名的容器。Android 官方文件的說法是:它讓你在同一個套件下的所有類別都能共用同一組常數,因此只要改一處欄位名,整份程式碼就都跟著改變,不必擔心某個字串寫錯造成不一致。
package com.example.sqlitetest;
// Contract 類別
public class Contact {
int _id;
String _name;
String _phone_number;
public Contact() { }
public Contact(int id, String name, String _phone_number) {
this._id = id;
this._name = name;
this._phone_number = _phone_number;
}
public Contact(String name, String _phone_number) {
this._name = name;
this._phone_number = _phone_number;
}
public int getID() { return this._id; }
public void setID(int id) { this._id = id; }
public String getName() { return this._name; }
public void setName(String name) { this._name = name; }
public String getPhoneNumber() { return this._phone_number; }
public void setPhoneNumber(String phone_number) { this._phone_number = phone_number; }
}
和內部儲存一樣,Android 會把資料庫放在 App 的私有空間,其他應用無法存取。實際路徑是:
/data/data/<package_name>/databases

做法是先繼承 SQLiteOpenHelper,並覆寫 onCreate()、onUpgrade() 等回呼。onCreate() 在資料庫首次被建立時呼叫,用來建表;onUpgrade() 在版本號變大時呼叫,用來處理結構變更。
增:把 ContentValues 傳進 insert()。
SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); values.put(KEY_PH_NO, contact.getPhoneNumber()); db.insert(TABLE_CONTACTS, null, values); db.close();
刪:delete(),第三個參數用「?」當佔位符,避免 SQL 注入。
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
改:update(),回傳受影響的列數。
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
查:query() 回傳 Cursor,需自行移動指標並取出欄位。
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return contact;
package com.example.sqlitetest;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "contactsManager";
private static final String TABLE_CONTACTS = "contacts";
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
onCreate(db);
}
/** 新增聯絡人 **/
void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
db.insert(TABLE_CONTACTS, null, values);
db.close();
}
/** 取得單一聯絡人 **/
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
return contact;
}
/** 取得所有聯絡人 **/
public List<Contact> getAllContacts() {
List<Contact> contactList = new ArrayList<Contact>();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
contactList.add(contact);
} while (cursor.moveToNext());
}
return contactList;
}
/** 更新單一聯絡人 **/
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
/** 刪除單一聯絡人 **/
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
/** 取得聯絡人數量 **/
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
return cursor.getCount();
}
}








Cursor 一定要關。上面範例多數沒有關閉 Cursor,長時間執行會造成游標洩漏。建議用 try-with-resources 或在 finally 中呼叫 close()。
不要在主執行緒做資料庫操作。大量查詢會造成 ANR,應移到背景執行緒,或使用 Room 搭配 coroutine。
onUpgrade 直接 DROP 會清空資料。正式環境應視情況改用 ALTER TABLE 做增量遷移,並保留舊資料。
新專案建議直接用 Room。Room 是官方提供的 ORM 層,在 SQLite 之上自動產生 CRUD 程式碼並提供編譯期語法檢查,能省下大量樣板程式。
其餘未貼出的程式碼(版面配置與 Activity 的互動部分)不是本次重點,需要的話可以再補充。
Android 自訂電量顯示控件的實作
電量自訂控件的實作 這個範例實作一個可以顯示電量的自訂 View。畫面中有一個輸入框,輸入數值後點擊刷新,電池圖示會依比例顯示對應電量。 自訂 BatteryStat
Android DrawerLayout 側滑布局詳解(一):基礎用法
DrawerLayout 顧名思義,就是一個用來管理布局的容器,使用方式與其他布局類別相似。它自帶滑動功能,只要按照 DrawerLayout 規定的布局方式寫好層級,就
Android 貝塞爾曲線完全指南:原理、Path API 與三個實戰案例
本文目錄 什麼是貝塞爾曲線 貝塞爾曲線的分類與公式 Android Path 中的對應 API 實戰一:波紋晃動效果 實戰二:QQ 式膠狀連體 實戰三:彈性球 前言
圖片加載反覆 OOM?一次踩坑一週的排查記錄與最終解法
這個 OOM 問題折騰了我整整一個禮拜。一開始完全找不到方向,一直認定是自己用的 Picasso 加載框架有問題——只加載了圖片,卻沒在 Activity 銷毀時做