編輯:關於 Android 程式設計
資料持久化是每個 Android 開發者都躲不掉的課題。這篇把四條主要路線一次講清楚:SharedPreferences、內部/外部檔案、SQLite 資料庫,以及各自的權限與取捨。
如果資料量比較小、又是需要保存的,那 SharedPreferences 就很好用。一個 SharedPreferences 物件指向一個包含 key-value 對的檔案,它提供了一些簡單的方法來讀和寫,每個檔案可以是私有的也可以是共享的。
注意:SharedPreferences 只能讀寫 key-value 對,不要跟 Preference 搞混了。
getSharedPreferences():如果希望多個 Activity 共用同一份 SharedPreferences,就呼叫這個方法。需要在第一個參數傳入一個名字作為唯一標識符(也就是 key),可以在 app 的任何一個 Context 中呼叫。
getPreferences():如果只想讓當前這個 Activity 存取,就用它。因為這樣會取得一個預設屬於該 Activity 的 SharedPreferences,所以不用傳名字。
Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(
getString(R.string.preference_file_key),
Context.MODE_PRIVATE);
命名的時候,建議用一個能唯一標識的名字,例如 "com.example.myapp.PREFERENCE_FILE_KEY"——加上包名前綴,就不會跟其他 app 撞名。
若只需在同一個 Activity 內共用:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
注意:建立 SharedPreferences 時若使用 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE,那麼任何知道標識符的 app 都能取得裡面的資料。
透過 SharedPreferences 物件呼叫 edit() 取得一個 SharedPreferences.Editor,用 putInt() 或 putString() 傳入 key 與 value,最後呼叫 commit() 提交。
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int newHighScore = getNewHighScore();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
呼叫 getInt()、getString() 等,傳入 key 取得對應的 value。若 key 不存在,就用第二個參數作為預設值。
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
如果 getString(R.string.saved_high_score) 沒找到值,就回傳 defaultValue。字串預設回傳空字串,boolean 預設回傳 false,以此類推。
Android 使用一個檔案系統,有點類似其他平台基於磁碟的檔案系統。一個 File 物件適用於讀寫較大的資料,比如圖片檔或一些跟網路交換的資料。
所有 Android 裝置都有兩個檔案儲存區域:內部與外部。
內部儲存:它永遠可用;預設只有你的應用可以存取此處的檔案;當用戶卸載你的應用時,系統會刪除內部儲存中所有屬於你的檔案;當你希望確保用戶或其他應用都無法存取你的檔案時,這裡是最佳選擇。
外部儲存:它並非始終可用,因為用戶可能把外部儲存當作 USB 儲存裝置掛載,某些情況下甚至會從裝置中移除;它是全域可讀的,此處的檔案可能被其他應用讀取;卸載時,只有當你把檔案存在 getExternalFilesDir() 目錄下,系統才會一併刪除;對於無需存取限制、或你希望與其他應用共享的檔案,這裡是最合適的位置。
雖然 app 預設安裝在內部儲存,但可以在 manifest 中指定 android:installLocation 屬性,讓 app 裝到外部儲存。當 APK 非常大而外部空間又相對充裕時,用戶通常更青睞這個選擇。
要寫入外部儲存,需在 manifest 中請求 WRITE_EXTERNAL_STORAGE 權限:
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
如果在 app 中使用 WRITE_EXTERNAL_STORAGE,那也同時擁有了讀取的權限。若只需要讀取而不寫入,則要声明 READ_EXTERNAL_STORAGE:
<manifest ...>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
...
</manifest>
官方文件對此有一段提醒:
Caution: Currently, all apps have the ability to read the external storage without a special permission. However, this will change in a future release. If your app needs to read the external storage (but not write to it), then you will need to declare the READ_EXTERNAL_STORAGE permission. To ensure that your app continues to work as expected, you should declare this permission now, before the change takes effect.
如果想保存檔案到內部儲存,則不需要請求任何權限,app 可以直接讀寫。
呼叫下列其中一個方法,取得適合的目錄:
getFilesDir():回傳一個 File,表示內部目錄。
getCacheDir():回傳一個 File,表示內部臨時緩存目錄。確保一旦緩存檔不再需要就及時刪掉,以保留足夠空間。如果系統在低記憶體下運行,可能會自動刪除緩存檔且不發出任何警告。
用 File() 構造器建立新檔案,傳入上述任一方法的回傳值作為路徑:
// 建立一個檔案
String filename = "myfile";
File file = new File(context.getFilesDir(), filename);
然後呼叫 openFileOutput() 取得 FileOutputStream,再透過它呼叫 write() 寫入:
String filename = "myfile";
String message = "Hello world!";
FileOutputStream outputStream;
try {
outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
outputStream.write(message.getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
app 的內部儲存目錄是按包名存放在 Android 檔案系統下的。如果檔案模式設為 Readable,其他 app 就能讀取——但前提是它們得知道你的包名和檔名。所以只要在內部儲存中堅持使用 MODE_PRIVATE,其他 app 就無法存取裡面的內容。
若需要建立緩存檔,用 createTempFile() 取代 File()。下面的範例從 URL 中取出檔名,存到 app 的內部緩存目錄:
public File getTempFile(Context context, String url) {
File file = null;
try {
String fileName = Uri.parse(url).getLastPathSegment();
file = File.createTempFile(fileName, null, context.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
return file;
}
因為外部儲存並非始終可用,存取前要先確認狀態。呼叫 getExternalStorageState() 查詢,回傳 MEDIA_MOUNTED 時才能讀寫。
/* 檢查外部儲存是否可以讀取和寫入 */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)
|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
雖然外部儲存的資料可能被用戶或其他 app 改動,但有兩類檔案適合放在這裡:
公共檔案:對用戶或其他 app 應該是自由可用的,卸載 app 時仍會保留。例如透過 app 拍下的照片或下載的資料。
私人檔案:屬於 app,卸載時會跟著被刪除。雖然用戶或其他 app 實際上仍能進入這個目錄,但它不對其他 app 提供資料。例如用戶透過 app 緩存的影片檔。
存放公共檔案用 getExternalStoragePublicDirectory(),它回傳一個合適的外部儲存目錄。可以傳入參數指定檔案類型,與其他公共檔案邏輯地組織在一起,例如 DIRECTORY_MUSIC 或 DIRECTORY_PICTURES:
private static final String LOG_TAG = "MyApp";
public File getAlbumStorageDir(String albumName) {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
存放私人檔案則呼叫 getExternalFilesDir(),這樣建立的每個目錄都會在用戶卸載 app 時被系統刪除:
public File getAlbumStorageDir(Context context, String albumName) {
File file = new File(context.getExternalFilesDir(
Environment.DIRECTORY_PICTURES), albumName);
if (!file.mkdirs()) {
Log.e(LOG_TAG, "Directory not created");
}
return file;
}
如果沒有事先定義好的子目錄名,直接呼叫不帶參數的 getExternalFilesDir(),會回傳外部儲存的根目錄:
File file = new File(context.getExternalFilesDir());
如果事先知道要保存多少資料,想確認有足夠空間而不拋出 IO 異常,可以呼叫 getFreeSpace() 或 getTotalSpace() 查看目前可用空間與總空間。
如果無法確定需要多少空間,就不必事先檢查。直接嘗試寫入並捕捉 IO 異常即可——例如把 PNG 轉成 JPEG 這種事先算不準大小的操作。
最直接的方式是讓該檔案呼叫 delete():
file.delete();
如果檔案在內部儲存,也可以透過 Context 呼叫 deleteFile() 並傳入檔名:
myContext.deleteFile(fileName);
注意:當用戶卸載 app 時,Android 系統會刪除:1、所有保存在內部儲存的檔案;2、所有用 getExternalFilesDir() 保存在外部儲存的檔案。
如果資料是重複的、有結構的,那存進資料庫最合適,比如手機聯絡人的資訊。
SQL 資料庫的主要原則之一就是模式(schema)——它告訴我們資料庫是怎麼組織的。這個模式體現在我們建立資料所用的 SQL 語句中。
Contract 類可以看作一個容器,裡面定義了 URI、表與相關方法。其中的每一個內部類對應一個 table,並枚舉出每一個屬性。
public final class FeedReaderContract {
// 防止有人意外地實例化這個類,所以給它一個空的構造器
public FeedReaderContract() {}
/* 內部類定義表的內容 */
public static abstract class FeedEntry implements BaseColumns {
public static final String TABLE_NAME = "entry";
public static final String COLUMN_NAME_ENTRY_ID = "entryid";
public static final String COLUMN_NAME_TITLE = "title";
public static final String COLUMN_NAME_SUBTITLE = "subtitle";
...
}
...
}
注意:透過實作 BaseColumns 介面,內部類就繼承了一個 _ID 作為主鍵。一些類(比如 Cursor)會需要資料庫中的主鍵。這不是強制要求,但卻能幫助資料庫與 Android 框架協調地工作。
就像內部儲存檔案一樣,Android 把資料庫存在一個私有的空間裡,這片區域不允許其他應用存取,資料是安全的。我們使用 SQLiteOpenHelper 類取得對資料庫的引用,需要時呼叫 getWritableDatabase() 或 getReadableDatabase()。
注意:因為這兩個方法會長時間運行,要確保它們在後台線程中呼叫,比如 AsyncTask 或 IntentService。
建立一個類別繼承 SQLiteOpenHelper,覆寫 onCreate()、onUpgrade() 與 onOpen() 這些回呼方法。還有一個 onDowngrade(),但這不是必需的。
public class FeedReaderDbHelper extends SQLiteOpenHelper {
// 如果改變了資料庫的模式,那麼必須升級資料庫版本,在版本數上加 1
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "FeedReader.db";
public FeedReaderDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public void onCreate(SQLiteDatabase db) {
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
FeedEntry._ID + " INTEGER PRIMARY KEY," +
FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
... " )";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;
db.execSQL(SQL_CREATE_ENTRIES);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 資料庫只對線上資料進行緩存,所以升級方式就是丟棄並重建
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
先實例化剛才建立的 Helper,呼叫 getWritableDatabase() 取得可寫的資料庫。用 ContentValues 以 key-value 方式裝入資料,再傳給 insert():
FeedReaderDbHelper mDbHelper = new FeedReaderDbHelper(getContext());
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);
long newRowId;
newRowId = db.insert(FeedEntry.TABLE_NAME, null, values);
insert() 的三個參數:
第一個是表名。
第二個是在 ContentValues 為空時,給某些可為空的屬性自動賦值為 NULL。這個功能一般不太用得到,直接傳 null。
第三個是 ContentValues 物件。
呼叫 query() 從資料庫讀取,結果回傳一個 Cursor 物件。
SQLiteDatabase db = mDbHelper.getReadableDatabase();
String[] projection = {
FeedEntry._ID,
FeedEntry.COLUMN_NAME_TITLE,
FeedEntry.COLUMN_NAME_UPDATED,
...
};
String selection = "where " + FeedEntry.COLUMN_NAME_TITLE + " = ?";
String selectionArgs = new String[]{"title_1"};
String sortOrder = FeedEntry.COLUMN_NAME_UPDATED + " DESC";
Cursor cursor = db.query(
FeedEntry.TABLE_NAME,
projection,
selection,
selectionArgs,
null,
null,
sortOrder);
cursor.moveToFirst();
long itemId = cursor.getLong(cursor.getColumnIndexOrThrow(FeedEntry._ID));
String title = cursor.getString(cursor.getColumnIndexOrThrow(FeedEntry.COLUMN_NAME_TITLE));
query() 的七個參數依序是:表名、要回傳的欄位、where 語句、where 語句指定的值、group by 語句、對 group by 結果的過濾(having)、以及排序方式。
回傳的 Cursor 先呼叫 moveToFirst() 定位到第一筆,然後對每一列呼叫 getString() 或 getLong() 取值,欄位位置則用 getColumnIndex() 或 getColumnIndexOrThrow() 取得。要讀下一筆就呼叫 moveToNext()。
順帶一提,selection 裡那個 where 關鍵字其實是多寫的——query() 的 selection 參數只需要條件本身(如 "title = ?"),系統會自行加上 WHERE。這是一個很常見的小筆誤。
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
db.delete(table_name, selection, selectionArgs);
update() 結合了 insert() 與 delete() 的部分參數,分別是 tableName、values、selection、selectionArgs:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// 新的值
ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
int count = db.update(
FeedReaderDbHelper.FeedEntry.TABLE_NAME,
values,
selection,
selectionArgs);
也有人更青睞直接寫 SQL 操作資料庫。
插入:
db.execSQL("insert into ComputerBook (name, author, pages, price) values(?, ?, ?, ?)",
new String[] { "Java Programing", "Dan Brown", "310", "49" });
更新:
db.execSQL("update ComputerBook set price = ? where name = ?",
new String[] { "50", "Java Programing" });
刪除:
db.execSQL("delete from ComputerBook where pages > ?",
new String[] { "300" });
查詢:
db.rawQuery("select * from ComputerBook", null);
兩種風格各有適用場景:execSQL 適合一次性的批次操作或 DDL,而 insert/update/delete/query 這組方法的好處是參數化更安全、回傳值也更有用(插入回傳 row id、更新刪除回傳受影響列數)。不論走哪一條,使用者輸入都必須用占位符綁定,切勿字串拼接。
四種方式的適用範圍其實很清晰:幾十個設定項用 SharedPreferences;圖片、音檔、匯出的備份用檔案;結構化且需要查詢條件的資料用 SQLite。
而檔案的內部/外部之別,取決於「卸載後要不要留」。要留就放公共目錄,不留就放 getExternalFilesDir() 或內部儲存。把這條判斷記牢,就不會再為存哪裡而猶豫。
Android ListView 完全詳解:四種 Adapter、常用屬性與下拉刷新上拉加載
本文目錄: 1. ListView 概述 2. ListView 的四個關鍵角色(Adapter、ViewHolder、數據集、布局) 3. ListView 常用屬性
Android 自訂 View 與自訂動畫的實作指南
Android Framework 為我們提供了豐富的介面元件,但在實際的商業開發中,這些內建元件往往無法完全滿足需求。這時候,我們就需要打造屬於自己的自訂視圖與動畫。
Android 源碼倉庫與 Repo 工具使用指南
前言 ROM Porting 這份工作瑣碎且牽涉面廣,其中「怎麼把原始碼抓下來」是入門的第一道關卡。這篇整理幾個常見名詞,以及 Repo 工具的用法。 AOSP、AOKP
Android 學習筆記:用 Data 與 Type 讓系統自動挑選合適的 App 開啟檔案
仔細想想,手機上開啟一個檔案其實只有兩條路: 一是從檔案出發——檔案管理器知道副檔名,於是去找能處理這個類型的 App;二是從 App 出發——你在 Gallery 裡