編輯:關於 Android 程式設計
任何應用都離不開資料的讀與寫。Android 提供兩條主要路徑:資料量小、結構簡單(字串、數值)時,用 SharedPreferences 存成 key-value 即可;需要大量資料與查詢能力時,則該動用資料庫。Android 內建 SQLite,並提供了便利的 API。
遊戲積分、音效與震動的開關這類設定,最適合放在 SharedPreferences。它提供的讀取方法大致有三類:
boolean contains(String key):判斷某個 key 是否存在。Map<String, ?> getAll():一次取出全部資料。getXxx(String key, xxx defValue):依型別取值,第二參數是預設值。SharedPreferences 本身沒有寫入能力,必須先呼叫 edit() 取得 Editor:
putXxx(String key, xxx value):寫入一組 key-value。clear():清空所有資料。commit():提交修改,通常放在最後一行。它是介面而非類別,無法直接 new,必須透過 Context 的 getSharedPreferences(String name, int mode) 取得執行個體。第二參數決定可見性:
MODE_PRIVATE:僅本程式可讀寫(預設值)。MODE_WORLD_READABLE:其他程式可讀,不可寫。MODE_WORLD_WRITEABLE:其他程式可讀可寫。後兩者會讓任何應用都能存取你的設定檔,除少數特殊情境外不建議使用;較新的 Android 版本更已直接將它們標為不鼓勵或抛出例外。
public class SharedPreferencesTest extends Activity {
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);
editor = preferences.edit();
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
String time = preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);
String result = (time == null)
? "您暫時還未寫入數據"
: "寫入時間:" + time + "\n上次隨機生成的隨機數為:" + randNum;
Toast.makeText(SharedPreferencesTest.this, result, Toast.LENGTH_LONG).show();
}
});
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
editor.putString("time", sdf.format(new Date()));
editor.putInt("random", (int) (Math.random() * 100));
editor.commit();
}
});
}
}
版面檔:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_horizontal" >
<Button
android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/write" />
<Button
android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/read" />
</LinearLayout>
透過 DDMS 觀察可以確認,SharedPreferences 的實體檔案存放在 /data/data/<套件名稱>/shared_prefs/ 底下,以 .xml 形式保存。
Java 完整的 IO 體系(FileInputStream、FileOutputStream)在 Android 上一樣可用。Context 另外提供了兩個便捷方法,直接對應用程序的資料目錄操作:
FileInputStream openFileInput(String name)FileOutputStream openFileOutput(String name, int mode)順帶釐清一個常被搞混的概念:輸入流是從儲存裝置讀資料進記憶體,輸出流是從記憶體把資料寫到外部儲存。
mode 參數除了前述的 MODE_PRIVATE 與 MODE_WORLD_* 之外,還有一個實用的 MODE_APPEND,以附加方式開啟檔案,新內容會接在既有內容之後。
Context 也提供了幾個管理檔案目錄的方法:
getDir(String name, int mode):取得或建立應用資料目錄下的子資料夾。getFilesDir():取得應用資料檔案的絕對路徑。fileList():列出資料夾中的檔案。deleteFile(String name):刪除指定檔案。public class MainActivity extends Activity {
final String FILE_NAME = "Read_Write";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button read = (Button) findViewById(R.id.read);
Button write = (Button) findViewById(R.id.write);
final EditText edit1 = (EditText) findViewById(R.id.edit1);
final EditText edit2 = (EditText) findViewById(R.id.edit2);
write.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
write(edit1.getText().toString());
edit1.setText("");
}
});
read.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
edit2.setText(read());
}
});
}
private String read() {
try {
FileInputStream fis = openFileInput(FILE_NAME);
byte[] buff = new byte[1024];
int hadRead = 0;
StringBuilder sb = new StringBuilder();
while ((hadRead = fis.read(buff)) > 0) {
sb.append(new String(buff, 0, hadRead));
}
fis.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void write(String content) {
try {
FileOutputStream fos = openFileOutput(FILE_NAME, MODE_APPEND);
PrintStream ps = new PrintStream(fos);
ps.println(content);
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
版面檔:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/write"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/write" />
<EditText
android:id="@+id/edit1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="4" />
<Button
android:id="@+id/read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/read" />
<EditText
android:id="@+id/edit2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:lines="4"
android:editable="false"
android:cursorVisible="false" />
</LinearLayout>
AVD 上的執行結果:

兩種方式各有適用場景:SharedPreferences 適合少量設定,檔案IO 適合結構自由或偏大的內容;而當資料需要被查詢、排序與關聯時,就該輪到下一篇要談的 SQLite 上場了。
Android 刪除 Preference 的正確姿势與源碼解析
用 Preference 搭設置界面很省事,一個 XML 就足夠。但想在某個時機動態移除其中一項時,很多人會發現刪不掉——而且往往找不到原因。本文從源碼層面把這件事講清楚
我們為什麼要在 Android 中使用 RxJava
近來 RxJava 風生水起,不學一下都不好意思了。本人也是初學 RxJava,起初還覺得代碼好像更複雜、更難懂了,直到讀到一篇外文深有共鳴,便簡單翻譯過來分享給大家。本
Android Studio 實戰導覽:介面面板、Gradle 設定與版本控制一次上手
為了降低 Android 的開發門檻,Google 很早便決定把資源集中投注在 Android Studio 這套工具上,並逐步停止對 Eclipse 等其他 IDE 的
用系統相機實作一鍵拍照:Intent 呼叫與結果接收
拍照功能其實不必自己寫 Camera2,直接借用系統相機即可,幾行 Intent 就能搞定。 public class MainActivity extends App