Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 學習筆記:用 SQLite 保存結構化資料

編輯:關於 Android 程式設計

對於大量、重複且具固定結構的資料,SQLite 是最合適的儲存方案。本文以一個聯絡人管理的 Demo 為例,說明 Contract 類別、SQLiteOpenHelper 的使用,以及增刪改查四種操作。

知識點

1. 使用 SQL Helper 建立資料庫。

2. 資料的增刪改查(Put、Read、Delete、Update)。

一、什麼是 Contract 類別

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

二、用 SQLiteOpenHelper 建立資料庫

和內部儲存一樣,Android 會把資料庫放在 App 的私有空間,其他應用無法存取。實際路徑是:

/data/data/<package_name>/databases

做法是先繼承 SQLiteOpenHelper,並覆寫 onCreate()、onUpgrade() 等回呼。onCreate() 在資料庫首次被建立時呼叫,用來建表;onUpgrade() 在版本號變大時呼叫,用來處理結構變更。

三、增刪改查的 API

增:把 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;

四、完整的 DatabaseHelper

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

Demo 執行結果

幾個實務上的補充

Cursor 一定要關。上面範例多數沒有關閉 Cursor,長時間執行會造成游標洩漏。建議用 try-with-resources 或在 finally 中呼叫 close()。

不要在主執行緒做資料庫操作。大量查詢會造成 ANR,應移到背景執行緒,或使用 Room 搭配 coroutine。

onUpgrade 直接 DROP 會清空資料。正式環境應視情況改用 ALTER TABLE 做增量遷移,並保留舊資料。

新專案建議直接用 Room。Room 是官方提供的 ORM 層,在 SQLite 之上自動產生 CRUD 程式碼並提供編譯期語法檢查,能省下大量樣板程式。

其餘未貼出的程式碼(版面配置與 Activity 的互動部分)不是本次重點,需要的話可以再補充。

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