編輯:關於 Android 程式設計
Android 的資料持久化主要有四種方式:檔案、SharedPreferences、SQLite 資料庫與 ContentProvider。ContentProvider 屬於四大元件之一,留到談元件時再說,本文先處理前面三種,並補上實務上常用的 LitePal。
檔案儲存不做任何格式轉換,資料原封不動寫進檔案,因此適合存放簡單的文字或二進位資料。它又分為存到內部儲存空間與存到 SD 卡兩種。
Context 提供了 openFileOutput(name, mode)。name 不可包含路徑,因為檔案一律放在 /data/data/<套件名稱>/files/ 之下(等同 getFilesDir())。mode 常見有兩種:MODE_PRIVATE 為預設值,同名檔案內容會被覆蓋;MODE_APPEND 則是若檔案已存在就附加內容,不存在則新建。另有 MODE_WORLD_READABLE 與 MODE_WORLD_WRITEABLE 允許其他 App 讀寫,但這兩者在 Android 4.2 已被棄用。
這個方法回傳 FileOutputStream,之後就能用一般 Java 串流寫入:
public void save() {
String data = "Data to save";
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try { writer.close(); } catch (IOException e) { /* 忽略 */ }
}
}
}
讀取則用 openFileInput("data"),同樣回傳串流物件:
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data");
reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine()) != null) {
content.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try { reader.close(); } catch (IOException e) { /* 忽略 */ }
}
}
return content.toString();
}
內部儲存空間受限於 App 私有目錄,要存大檔就得用外部儲存。這裡主要靠 Environment 類別:常用常量有 MEDIA_MOUNTED(可讀可寫)與 MEDIA_MOUNTED_READ_ONLY(唯讀);常用方法有 getExternalStorageDirectory() 取得 SD 卡路徑(/mnt/sdcard)與 getExternalStorageState() 取得目前狀態。
寫入流程是:先判斷狀態、取得路徑、以串流或 RandomAccessFile 讀寫、最後別忘了在 Manifest 加上權限。
public void write2Sd() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) return;
String content = edtContent.getText().toString();
try {
File sdCardDir = Environment.getExternalStorageDirectory();
File file = new File(sdCardDir, FILE_NAME);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(file.length()); // 指標移到檔尾,等效附加
raf.write(content.getBytes());
raf.close();
} catch (Exception e) {
// 處理例外
}
}
用 RandomAccessFile 的好處是可以定位到指定位置讀寫。讀取則相對單純:
public void readFromSd() {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) return;
StringBuilder sb = new StringBuilder();
try {
File sdCardDir = Environment.getExternalStorageDirectory();
File file = new File(sdCardDir, FILE_NAME);
InputStream in = new FileInputStream(file);
int len;
byte[] buffer = new byte[1024];
while ((len = in.read(buffer)) != -1) {
sb.append(new String(buffer, 0, len));
}
tvResult.setText(sb.toString());
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
SharedPreferences 是輕量級的鍵值對儲存,特別適合保存設定參數。資料以 XML 形式存放在 /data/data/<套件名稱>/shared_prefs 目錄下。
寫入四步驟:
讀取則是先取得物件,再用 getString()、getInt()、getBoolean() 這類 getXxx() 取值,找不到對應鍵時會回傳呼叫時傳入的預設值。
SQLite 是輕量級關聯式資料庫,速度快、占用資源少,通常幾百 KB 記憶體就夠,既支援標準 SQL 語法,也遵守 ACID 交易特性。
Android 提供 SQLiteOpenHelper 這個抽象類別來簡化建立與升級,其中 onCreate() 與 onUpgrade() 兩個抽象方法分別負責建庫與升庫,另有 getReadableDatabase() 與 getWritableDatabase() 兩個方法:資料庫存在就直接開啟,不存在則建立,並回傳可讀寫的 SQLiteDatabase 物件。
public class MyDatabaseHelper extends SQLiteOpenHelper {
public static final String CREATE_BOOK = "create table book("
+ "id integer primary key autoincrement,"
+ "author text,"
+ "price real,"
+ "pages integer,"
+ "name text)";
private Context mContext;
public MyDatabaseHelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Toast.makeText(mContext, "Creates succeeded", Toast.LENGTH_SHORT).show();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }
}
把建表語句寫成常量,在 onCreate() 中用 execSQL() 執行,就能保證建庫的同時也建好表。Activity 中建立 helper 並指定庫名與版本號,第一次呼叫 getWritableDatabase() 時才會真正觸發建立:
dbHelper = new MyDatabaseHelper(this, "BookStore.db", null, 1);
Button createDatabase = (Button) findViewById(R.id.create_database);
createDatabase.setOnClickListener(v -> dbHelper.getWritableDatabase());
要新增一張 Category 表,做法是把建表語句加進 onCreate(),並在 onUpgrade() 中用 switch 依 oldVersion 逐版本處理:
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL(CREATE_CATEGORY);
case 2:
db.execSQL("alter table Book add column category_id integer");
default:
}
}
注意 case 之間刻意不加 break,讓舊版本能一路補齊所有變更。若某個版本只是漏加一欄,就再補一個 case 用 alter table 加上去——這樣升級不會弄丟既有資料。使用時把建構子的版本號改大即可觸發。
以 SQLiteDatabase 物件進行四種操作:
// Create
ContentValues values = new ContentValues();
values.put("name", "The DaVinci Code");
values.put("author", "Dan Brown");
values.put("pages", 454);
values.put("price", 16.96);
db.insert("Book", null, values);
// Retrieve:table, columns, selection, selectionArgs, groupBy, having, orderBy
Cursor cursor = db.query("Book", null, null, null, null, null, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(cursor.getColumnIndex("name"));
int pages = cursor.getInt(cursor.getColumnIndex("pages"));
} while (cursor.moveToNext());
}
cursor.close();
// Update
ContentValues v = new ContentValues();
v.put("price", 10.99);
db.update("Book", v, "name=?", new String[]{ "xiaoming" });
// Delete
db.delete("Book", "pages>?", new String[]{ "500" });
也可以直接用原生 SQL:
db.execSQL("insert into Book(name, author, pages, price) values(?, ?, ?, ?)",
new String[]{ "The DaVinci Code", "Dan Brown", "454", "16.96" });
db.execSQL("update Book set price=? where name=?", new String[]{ "10.99", "The DaVinci Code" });
db.execSQL("delete from Book where pages>?", new String[]{ "500" });
db.rawQuery("select * from Book", null);
原生 SQLiteOpenHelper 有兩個痛點:一是 SQLite 不支援刪除既有欄位(實務上多半乾脆留著),二是表之間有关联時建表語句會變得相當複雜。這時可以考慮 LitePal 這類 ORM 框架——不必操心外鍵、中介表等細節,只要在物件中宣告彼此參照關係,框架就會自動建立關聯。
不過表關聯的基本概念還是值得了解。多表設計的口訣是:一對一用外鍵;多對一也用外鍵(外鍵放在多方);多對多則用中介表。
LitePal 專案網址:https://github.com/LitePalFramework/LitePal
Android 四大組件之 Activity(一):從建立到跑起來
Activity 是 Android 四大組件裡最基礎、也最常打交道的一個。作為應用程式組件,它提供了一個與使用者互動的介面;可以說凡是需要使用者「看到並操作」的地方,背
Android Toast 五種實作:打造自訂提示訊息
Toast 是 Android 中常見的輕量提示元件。除了預設樣式,開發者也能自訂位置、加入圖片、使用自訂版面,甚至在其他執行緒中顯示。以下整理五種常見用法。 一、預設樣
深入 HttpURLConnection:從 URL 到 Socket 的完整鏈路剖析
早些年 Android 上的網絡請求基本只有兩個選擇:Apache 的 HttpClient 與 JDK 自帶的 HttpURLConnection。近幾年 OkHttp
打造順手好用的 Android 模擬器:完整設定指南
預設的模擬器有多難用 預設狀態下的 Android 模擬器,最顯眼的問題是界面醜:視窗佔掉整個螢幕的龐大空間,還莫名其妙地擺著一個實體螢幕鍵盤。 但如果你真的用過,還有