Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 資料儲存入門:SharedPreferences 用法全解

編輯:關於 Android 程式設計

對一個完整的應用程式而言,資料儲存是基本配備。Android 提供四種主要方式:SharedPreferences、File、SQLite 與 ContentProvider。由於系統中的資料預設是私有的,存放在 data/data/程式包名 底下,因此跨應用共用資料時,正確做法是使用 ContentProvider。

四種儲存方式速覽

  • SQLite:輕量級資料庫,支援基本 SQL 語法。Android 以 SQLiteDatabase 封裝了操作 API,是最常被採用的方案。
  • SharedPreferences:本質是一個 XML 檔,適合存放較簡單的參數設定。
  • File:即一般的檔案(I/O)儲存,適合大量資料,缺點是更新資料相對費事。
  • ContentProvider:唯一能讓所有應用程式共享資料的方式。每個 Provider 對外提供一個公開的 URI(包裝成 Uri 物件),其他程式透過該 URI 存取資料。音訊、視訊、圖片、通訊錄通常都走這條路。

SharedPreferences 的定位

它是一種輕量級的 key-value 儲存機制,本體是一個 XML 檔,存放位置在 data/data/程式包名/shared_prefs 目錄下。SharedPreferences 物件本身只能讀取,寫入與修改必須透過 Editor 物件。

相較於 SQLite,它省下了建立資料庫、建表、寫 SQL 一連串步驟,寫起來簡潔許多。但它也有明確的天花板:只能存 boolean、int、float、long 與 String 五種型別,也不支援條件查詢。因此無論操作多麼簡單,它始終只能作為其他儲存方式的補充,無法完全取代 SQLite。

操作四步驟

  1. 透過 Context 取得 SharedPreferences 物件。呼叫 getSharedPreferences() 取得的物件可被同一應用的其他元件共用;呼叫 Activity 的 getPreferences() 取得的物件則僅限該 Activity 使用。
  2. 呼叫 edit() 取得 Editor 物件。
  3. 透過 Editor 存入 key-value 資料。
  4. 呼叫 commit()(同步)或 apply()(非同步)提交。

四種存取模式

  • Context.MODE_PRIVATE:預設模式,檔案為私有,僅應用本身可讀;寫入會覆蓋原內容。
  • Context.MODE_APPEND:檔案存在則追加內容,不存在則新建。
  • Context.MODE_WORLD_READABLE:允許其他應用讀取。
  • Context.MODE_WORLD_WRITEABLE:允許其他應用寫入。

後兩者在 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 的「輕量」究竟輕在哪裡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved