編輯:關於 Android 程式設計
在 Android 平台上實作資料儲存有很多選項:SharedPreferences、檔案、SQLiteDatabase、網路儲存。選擇取決於資料的型別與結構。如果你要存的是結構化資料,SQLite 是最合適的答案——它能安全而有效率地處理這類問題。
什麼是 SQLite
SQLite 是開源的、支援標準 SQL 語法的關聯式資料庫,支援交易,運行時只需極小的記憶體(約 250KB)。支援的資料型別只有 Text、INTEGER、REAL(類似 Java 的 double),其他所有型別都必須轉換成這三者之一才能存入。
SQLite 已內嵌在每一台 Android 裝置中,所以使用它不需要安裝或管理資料庫伺服器,你只要定義 SQL 語句來建立與管理資料表即可。
由於存取資料庫會觸及檔案系統,建議把資料庫操作放在非同步執行緒。建立後的資料庫預設存放在 DATA/APP_NAME/databases/FILENAME 之下。
相關的套件
SDK 中 android.database 套件含資料庫所需的通用操作類,android.database.sqlite 則包含所有 SQLite 專屬的操作。
建立持久化資料庫的做法是繼承 SQLiteOpenHelper,並在建構子中呼叫:
super(context, DATABASE_NAME, null, VERSION); // 傳入定義好的資料庫名與版本
接著必須覆寫兩個方法:
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
// 建立資料表
sqLiteDatabase.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
// 更新:先移除舊表再重建
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
這兩個方法都接受一個 SQLiteDatabase 物件。SQLiteOpenHelper 另外提供了 getWritableDatabase() 與 getReadableDatabase() 用來取得 SQLiteDatabase 實例——這兩個方法會自動判斷資料庫是否存在,不存在就觸發 onCreate()。
SQLiteDatabase 是基本的資料庫類別,提供 insert()、update()、delete() 等基礎操作;另外也有 execSQL() 可直接執行任意 SQL 語句。
插入或更新資料時需要使用 ContentValues。它讓你定義鍵值對:key 指向資料表的欄位名稱,value 指向該筆記錄的內容。
查詢的三種方式
Cursor cursor = getReadableDatabase().rawQuery(
"SELECT * FROM TABLE WHERE id=?", new String[]{ id });
Cursor cursor = getReadableDatabase().query(
DATABASE_TABLE,
new String[]{ KEY_ROWID, KEY_ID, KEY_NAME, KEY_HH },
null, null, null, null, null);
一條查詢會回傳一個 Cursor 物件。Cursor 主要指向查詢結果的某一列,這樣 Android 就能緩衝查詢結果,而不必一次把所有資料載入記憶體。
getCount():取得結果筆數。moveToFirst()、moveToNext():在結果集上移動。isAfterLast():回傳是否已到達結果末尾。getLong(columnIndex)、getString(columnIndex):取得該列的資料。getColumnIndexOrThrow(String name):取得某欄位名稱對應的索引。用完記得 close()。Cursor 背後是一個資料庫游標,不關閉會造成游標洩漏,資料量大的 App 甚至會直接拋出 CursorWindowAllocationException 或 close() was never explicitly called 的警告。
public class Contact {
private int id;
private String name;
private String number;
// 提供 getter / setter
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getNumber() { return number; }
public void setNumber(String number) { this.number = number; }
// 提供建構子
public Contact(int id, String name, String number) {
this.id = id;
this.name = name;
this.number = number;
}
}
private static final String DATABASE_NAME = "Contact";
private static final String TABLE_NAME = "contact";
private static final int VERSION = 1;
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_NUMBER = "number";
private static final String CREATE_TABLE = "create table " + TABLE_NAME + "("
+ KEY_ID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_NUMBER + " text not null);";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
// 新增
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
// 使用 ContentValues 添加資料
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_NUMBER, contact.getNumber());
db.insert(TABLE_NAME, null, values);
db.close();
}
// 單筆查詢
public Contact getContact(String name) {
SQLiteDatabase db = this.getWritableDatabase();
// Cursor 物件回傳查詢結果
Cursor cursor = db.query(TABLE_NAME,
new String[]{ KEY_ID, KEY_NAME, KEY_NUMBER },
KEY_NAME + "=?",
new String[]{ name },
null, null, null, null);
Contact contact = null;
// 注意:回傳結果有可能為空
if (cursor.moveToFirst()) {
contact = new Contact(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
}
cursor.close();
db.close();
return contact;
}
// 取得全部
public List<Contact> getAllContact() {
List<Contact> contactList = new ArrayList<Contact>();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
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.setNumber(cursor.getString(2));
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contactList;
}
// 更新
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_NUMBER, contact.getNumber());
return db.update(TABLE_NAME, values,
KEY_ID + "=?", new String[]{ String.valueOf(contact.getId()) });
}
// 刪除
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + "=?", new String[]{ String.valueOf(contact.getId()) });
db.close();
}
在對應的事件方法中呼叫 DatabaseHandler 的 CRUD 方法,再把結果綁到 adapter 上顯示即可。
用 Room 取代手寫的這些程式碼。上面這一套 CRUD 有九成是樣板程式碼,而且容易出錯(Cursor 忘記關、SQL 字串拼接有 injection 風險)。Android Jetpack 的 Room 在 SQLite 之上提供了一層註解式 ORM,編譯期就會檢查你的 SQL 是否正確,並自動處理 Cursor 生命週期。
無論用哪種方式,資料庫操作都應該放在背景執行緒。在主執行緒上做 insert 或 query,資料量大時會直接觸發 ANR。
MVP 模式在 Android 開發中的實際應用全解析
隨著 UI 系統能力越來越強,View 層肩負的責任也不斷膨脹。為了把「畫面呈現」與「資料處理」徹底分工,業界從 MVC 演化出了 MVP(Model-View-Pres
Android 自定義 UI 打造九宮格手勢密碼(完整實戰版)
此前寫過幾篇手勢密碼的 demo,但都沒真正集成進企業項目。這幾天正好接到一個手勢密碼的活,昨天剛收尾,今天抽空整理出來。目前還算不上完善,有些地方仍需打磨,但基本流程已
《Android Studio 實用指南》4.27 使用演示模式
本書目前已上傳至百度閱讀,在百度中搜索「Android Studio 實用指南」即可找到本書。 什麼是演示模式? 顧名思義,當你想向他人演示自己的代碼時,就會用到這個演示
Android Activity 四種 launchMode 啟動模式完整解析
Activity 的啟動模式決定了實例創建、任務棧管理與頁面復用方式。Android 中常見的 launchMode 有四種:standard、singleTop、sin