編輯:開發入門
上一篇談完偏好設定(Preferences)與 SQLite 的基本操作,本篇接著把資料庫的進階操作、內部儲存與外部儲存的完整 API 走一遍。
清空整張表其實一行就夠:
/** Wipe out the DB */
public void clearAll() {
db.delete(TABLE_NAME, null, null);
}
接著提供兩個 SELECT ALL 方法:cursorSelectAll() 回傳一個游標,listSelectAll() 則回傳一個 Friend 物件的 ArrayList。這兩個方法會在 MainActivity 從資料庫載入資訊時被呼叫。
回傳 Cursor 的版本:
/** Select All returns a cursor
* @return the cursor for the DB selection */
public Cursor cursorSelectAll() {
Cursor cursor = this.db.query(
TABLE_NAME, // Table Name
new String[] { "fid", "name" },// Columns to return
null, // SQL WHERE
null, // Selection Args
null, // SQL GROUP BY
null, // SQL HAVING
"name"); // SQL ORDER BY
return cursor;
}
回傳 ArrayList 的版本:這個方法把選到的列裝進 ArrayList 容器,讓 MainActivity 可以直接綁定到 MainScreen 的 ListView。
/** Select All that returns an ArrayList
* @return the ArrayList for the DB selection */
public ArrayList<Friend> listSelectAll() {
ArrayList<Friend> list = new ArrayList<Friend>();
Cursor cursor = this.db.query(TABLE_NAME,
new String[] { "fid", "name" }, null, null, null, null, "name");
if (cursor.moveToFirst()) {
do {
Friend f = new Friend();
f.id = cursor.getString(0);
f.name = cursor.getString(1);
list.add(f);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
如果偵測到資料庫版本變更,就會呼叫 onUpgrade():
/** Invoked if a DB upgrade (version change) has been detected */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 在此加入版本升級所需的處理步驟,
// 例如資料格式轉換、移除不再需要的舊表等
}
整個 MainActivity 裡,無論是匯出資料到資料庫、從資料庫載入,還是清空資料庫,都會用到 DBHelper。第一件事是在建立 MainActivity 時把它實例化,同時初始化各個畫面視圖:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appContext = this;
setContentView(R.layout.main);
dbHelper = new DBHelper(this);
listView = (ListView) findViewById(R.id.friendsview);
friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout, friends);
listView.setAdapter(friendsArrayAdapter);
:
}
接著是從 assets 載入好友清單,解析後插入資料庫:
String fname = prefsGetFilename();
if (fname != null && fname.length() > 0) {
buffer = getAsset(fname);
// 解析 JSON 檔
String friendslist = new String(buffer);
final JSONObject json = new JSONObject(friendslist);
JSONArray d = json.getJSONArray("data");
int l = d.length();
for (int i2 = 0; i2 < l; i2++) {
JSONObject o = d.getJSONObject(i2);
String n = o.getString("name");
String id = o.getString("id");
dbHelper.insert(id, n);
}
// 只有原始擁有者執行緒才能操作它的 view
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
friendsArrayAdapter.notifyDataSetChanged();
}
});
}
最後執行 SELECT ALL 並把資料綁定到主畫面的 ListView:
final ArrayList<Friend> dbFriends = dbHelper.listSelectAll();
if (dbFriends != null) {
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
friendsArrayAdapter = new FriendsArrayAdapter(
MainActivity.this, R.layout.rowlayout, dbFriends);
listView.setAdapter(friendsArrayAdapter);
friendsArrayAdapter.notifyDataSetChanged();
}
});
}
這裡的 runOnUiThread 是關鍵:非 UI 執行緒不得直接操作 View,所有更新都必須拋回主執行緒執行。
除了資料庫,你也可以用內部儲存來放資料。資訊可以是私有的,也可以有選擇地讓其他應用程式具備讀或寫的權限。相關 API 是 Context.openFileInput()、openFileOutput() 與 getCacheDir(),其中後者是用於高速緩存而非永久儲存。
寫入私有檔案:讓儲存空間保持私有的關鍵,是對 openFileOutput() 使用 MODE_PRIVATE。
/** Writes content to internal storage making the content private to
* the application. */
public void writeInternalStoragePrivate(String filename, byte[] content) {
try {
// MODE_PRIVATE 會建立/取代檔案,並使其私有於你的應用程式。
// 其他模式:MODE_WORLD_WRITEABLE、MODE_WORLD_READABLE、MODE_APPEND
FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
fos.write(content);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
讀取私有檔案:注意 openFileInput() 的用法。
/** Reads a file from internal storage
* @return the file content */
public byte[] readInternalStoragePrivate(String filename) {
int len = 1024;
byte[] buffer = new byte[len];
try {
FileInputStream fis = openFileInput(filename);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int nrb = fis.read(buffer, 0, len); // read up to len bytes
while (nrb != -1) {
baos.write(buffer, 0, nrb);
nrb = fis.read(buffer, 0, len);
}
buffer = baos.toByteArray();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
刪除私有檔案:
/** Delete internal private file */
public void deleteInternalStoragePrivate(String filename) {
File file = getFileStreamPath(filename);
if (file != null) {
file.delete();
}
}
外部儲存同樣可以是私有的,也可以選擇讓其他程式讀寫。這裡會用到 getExternalStorageState()、getExternalFilesDir()、getExternalStorageDirectory() 與 getExternalStoragePublicDirectory() 等 API。公共資料的路徑為 /android/data/<package_name>/files/。
動手之前,必須先確認外部儲存是否可用、是否可寫。
測試外部儲存是否可用:
/** Helper Method to Test if external Storage is Available */
public boolean isExternalStorageAvailable() {
boolean state = false;
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
state = true;
}
return state;
}
測試外部儲存是否唯讀:
/** Helper Method to Test if external Storage is read only */
public boolean isExternalStorageReadOnly() {
boolean state = false;
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
state = true;
}
return state;
}
寫入外部儲存:
/** Write to external public directory */
public void writeToExternalStoragePublic(String filename, byte[] content) {
// API Level 7 以下可用 getExternalStorageDirectory() 取得外部儲存根目錄,
// 但不建議直接寫入根目錄,應寫入應用程式專屬目錄,如下所示。
String packageName = this.getPackageName();
String path = "/android/data/" + packageName + "/files/";
if (isExternalStorageAvailable() && !isExternalStorageReadOnly()) {
try {
File file = new File(path, filename);
file.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(content);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
從外部儲存讀取:
/** Reads a file from external storage
* @return the file contents */
public byte[] readExternalStoragePublic(String filename) {
int len = 1024;
byte[] buffer = new byte[len];
String packageName = this.getPackageName();
String path = "/android/data/" + packageName + "/files/";
if (!isExternalStorageReadOnly()) {
try {
File file = new File(path, filename);
FileInputStream fis = new FileInputStream(file);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int nrb = fis.read(buffer, 0, len);
while (nrb != -1) {
baos.write(buffer, 0, nrb);
nrb = fis.read(buffer, 0, len);
}
buffer = baos.toByteArray();
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return buffer;
}
從外部儲存刪除檔案:
/** Delete external public file */
void deleteExternalStoragePublicFile(String filename) {
String packageName = this.getPackageName();
String path = "/android/data/" + packageName + "/files/" + filename;
File file = new File(path, filename);
if (file != null) {
file.delete();
}
}
處理外部儲存需要 WRITE_EXTERNAL_STORAGE 這個特殊權限,必須在 androidManifest.xml 中聲明:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
另外要留意,外部儲存 API 也支援依檔案類型(Pictures、Ringtones 等)存放到預先定義的公開目錄,本文未涵蓋這個做法,但值得你熟悉。同時請記住:外部儲存中的檔案隨時可能消失——使用者可能拔卡、掛載 USB 儲存,因此不要把唯一一份重要資料只放在外部儲存。
如果你有不需長期保存的暫存檔,可以放進高速緩存。緩存是一種特殊記憶體,適合存放中小型資料(小於 1 MB 為宜),但必須知道:取決於可用空間多寡,緩存內容隨時可能被清除。
取得內部記憶體緩存路徑:
/** Helper method to retrieve the absolute path to the application
* specific internal cache directory on the file system. */
public String getInternalCacheDirectory() {
String cacheDirPath = null;
File cacheDir = getCacheDir();
if (cacheDir != null) {
cacheDirPath = cacheDir.getPath();
}
return cacheDirPath;
}
取得外部記憶體緩存路徑:
/** Helper method to retrieve the absolute path to the application
* specific external cache directory on the file system. */
public String getExternalCacheDirectory() {
String extCacheDirPath = null;
File cacheDir = getExternalCacheDir();
if (cacheDir != null) {
extCacheDirPath = cacheDir.getPath();
}
return extCacheDirPath;
}
本文介紹了幾個 Android 儲存 API,從首選項一路談到 SQLite 以及內部與外部記憶體。透過首選項 API,你可以讓應用程式收集並保存簡單的偏好資訊;透過 SQLite API,你能存放更複雜的結構化資料;而利用內部與外部儲存,你可以保存對應用程式私有或對其他程式公開的檔案。
這些跨越多個工作階段持續保存的資料,讓你的應用程式即使在與網路斷線時仍能正常運作。掌握這幾類儲存機制,等於掌握了 Android 應用開發在資料層面的全部基礎。
對 Android 開發者有益的 40 條優化建議
Android 開發不只是把功能做出來,還需要考慮相容性、效能、記憶體、測試與使用者體驗。以下整理 40 條實用建議,適合初學者與中階開發者參考。 先尋找與需求相似的
Android 混合應用程式實作(下):Java 與 JavaScript 的雙向資料流
把 JavaScript 介面接起來 有了 WebView 之後,下一步是讓 Activity 裡的 Java 程式碼能和 WebView 中的 JavaScript 互
Android數據庫事務淺析
在Android應用開發中,數據庫操作時常出現,而數據庫事務的處理對應用的穩定性與效率提升至關重要。 首先,Android的數據庫操作——尤其是寫操作——非常慢,把所有操
Facebook SDK for Android 入門(一):從 Graph API 動手做第一個社交應用
前言:把 Facebook 的社交能力搬進你的 App 想在自己的應用裡加入社交元素?Facebook 早就把這條路鋪好了。從行動端來看,Facebook Platfor