編輯:關於 Android 程式設計
對一個完整的應用程式而言,資料儲存是基本配備。Android 提供四種主要方式:SharedPreferences、File、SQLite 與 ContentProvider。由於系統中的資料預設是私有的,存放在 data/data/程式包名 底下,因此跨應用共用資料時,正確做法是使用 ContentProvider。
SQLiteDatabase 封裝了操作 API,是最常被採用的方案。它是一種輕量級的 key-value 儲存機制,本體是一個 XML 檔,存放位置在 data/data/程式包名/shared_prefs 目錄下。SharedPreferences 物件本身只能讀取,寫入與修改必須透過 Editor 物件。
相較於 SQLite,它省下了建立資料庫、建表、寫 SQL 一連串步驟,寫起來簡潔許多。但它也有明確的天花板:只能存 boolean、int、float、long 與 String 五種型別,也不支援條件查詢。因此無論操作多麼簡單,它始終只能作為其他儲存方式的補充,無法完全取代 SQLite。
getSharedPreferences() 取得的物件可被同一應用的其他元件共用;呼叫 Activity 的 getPreferences() 取得的物件則僅限該 Activity 使用。edit() 取得 Editor 物件。commit()(同步)或 apply()(非同步)提交。後兩者在 API 17 之後已被標示為不建議使用,實務上應改用 FileProvider 對外分享檔案。
以下示範寫入資料,並在點擊 TextView 時把值讀出來顯示。
public class MainActivity extends Activity {
private TextView textView;
private SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 1. 取得 SharedPreferences 物件,參數一為檔名
sharedPreferences = getSharedPreferences("hello", MODE_PRIVATE);
// 2. 寫入多種類型的資料
Editor editor = sharedPreferences.edit();
editor.putString("string", "hello world.");
editor.putInt("int", 10);
editor.putBoolean("boolean", true);
// 3. 提交
editor.commit();
// 4. 點擊時讀回
textView = (TextView) findViewById(R.id.textView);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// key 不存在時會回傳第二個參數作為預設值
String result = sharedPreferences.getString("string", "")
+ " " + sharedPreferences.getInt("int", 0)
+ " " + sharedPreferences.getBoolean("boolean", false);
textView.setText(result);
textView.setTextSize(20);
}
});
}
}
程式執行後,資料會寫入 /data/data/com.example.sharedpreferencedemo/shared_prefs/hello.xml。在 Eclipse 中可透過 Window → Show View → Other → Android → File Explorer 找到該檔案:

點擊 File Explorer 右上角第一顆按鈕即可把 hello.xml 匯出到電腦檢視內容:

檔案內容如下:

點擊 TextView 後的執行結果:

可以清楚看到 XML 檔就是一串標準的 key-value 標籤結構,這也說明了 SharedPreferences 的「輕量」究竟輕在哪裡。
Android 拍照與相冊封裝實戰:告別崩潰、空白與圖片方向錯亂
項目下載地址:https://github.com/Aiushtha/android-PictureSelector 最早使用 Android 調用系統拍照時,我遇到了各
SurfaceView 實戰:自定義一個流暢的 Android 畫板
接觸 View 這麼久,總不能一直停留在原地。這次要認識一位新朋友:SurfaceView。它和 View 的使用方式相似,但底層原理不同——SurfaceView 為自
深入理解 Android 的 Dalvik 虛擬機:Class、DEX、位元組碼與啟動流程
從 Class 到 DEX:Android 虛擬機的輸入Dalvik 虛擬機的學習,可以從 Java 編譯後的 class 檔開始。class 檔是 JVM 規範中描述的
Android Base64 編碼解碼詳解:原理、用途與 API 參數
做過數據加密的應該都有印象:無論用哪種加密算法,最終都會對密文的二進制數據做一次 Base64 編碼。它常被當作「二次加密」,但嚴格來說 Base64 並不是加密算法,而