Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android SharedPreferences 輕量級資料儲存完整說明與範例

編輯:Android 開發實例

幾乎每一款 App 都會有設定頁:要不要開啟通知、預設的伺服器位址、使用者上次輸入的暱稱。這類資料結構簡單、量體小、讀寫頻繁,用資料庫反而顯得笨重。Android 為此準備了 SharedPreferences。

它本質上是一個 XML 檔

SharedPreferences 是一組輕量的鍵值對儲存機制,底層其實就是一個 XML 檔,存放路徑在 /data/data/<package name>/shared_prefs/ 目錄下。

寫入的基本流程是「取得偏好物件 → 取得編輯器 → 放入鍵值 → 提交」:

SharedPreferences sp = getSharedPreferences("ljq", Context.MODE_PRIVATE);

Editor editor = sp.edit();      // 取得編輯器
editor.putString("name", "林計欽");
editor.putInt("age", 24);
editor.commit();                // 提交修改

執行後會產生 ljq.xml,內容大致如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="name">林計欽</string>
    <int name="age" value="24" />
</map>

getSharedPreferences(name, mode) 的第一個參數就是檔名,不需要自己寫副檔名,Android 會自動補上 .xml。第二個參數是檔案的操作模式。

另外,Activity 還提供了更簡便的 getPreferences(mode),它會直接用目前類別的名稱(不帶套件名)作為檔名,適合只在同一個 Activity 內使用的簡單設定。

讀取資料

SharedPreferences sp = getSharedPreferences("ljq", Context.MODE_PRIVATE);

// 第二個參數是預設值:key 不存在時就回傳它
String name = sp.getString("name", "");
int age = sp.getInt("age", 1);

跨應用讀取(歷史寫法)

早期版本可以透過 MODE_WORLD_READABLE / MODE_WORLD_WRITEABLE 開放權限,讓其他應用讀寫同一份偏好檔。做法是先建立對方套件的 Context,再透過它取得偏好物件:

Context otherCtx = createPackageContext("com.ljq.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sp = otherCtx.getSharedPreferences("ljq", Context.MODE_WORLD_READABLE);
String name = sp.getString("name", "");
int age = sp.getInt("age", 0);

也可以直接以檔案方式讀取對方的 XML:

File xmlFile = new File("/data/data/<package name>/shared_prefs/itcast.xml");

必須補充的是,這兩個 WORLD_ 系列常數從 Android 4.2(API 17)起已被標記為不建議使用,新版本系統對應用沙箱與檔案存取的限制也越來越嚴格,正式專案不該再依賴这种做法。跨應用共享設定請改用 ContentProvider 或明確的 Intent 溝通。

完整範例:設定頁的保存與回顯

版面配置(main.xml)以線性版面搭配兩組「標籤 + 輸入框」與兩個按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:id="@+id/nameLable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/name"
            android:textSize="20px" />
        <EditText android:id="@+id/name"
            android:layout_width="80px"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/nameLable"
            android:layout_alignTop="@id/nameLable"
            android:layout_marginLeft="10px" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <TextView android:id="@+id/ageLable"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/age"
            android:textSize="20px" />
        <EditText android:id="@+id/age"
            android:layout_width="80px"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/ageLable"
            android:layout_alignTop="@id/ageLable"
            android:layout_marginLeft="10px" />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button" />
        <Button android:id="@+id/showButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/button"
            android:layout_alignTop="@id/button"
            android:text="@string/showButton" />
    </RelativeLayout>

    <TextView android:id="@+id/showText"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="20px" />
</LinearLayout>

Activity 端在 onCreate 中先做一次回顯,讓使用者重開 App 時能看到上次存下的值:

package com.ljq.activity;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class SpActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private TextView resultText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        nameText = (EditText) this.findViewById(R.id.name);
        ageText = (EditText) this.findViewById(R.id.age);
        resultText = (TextView) this.findViewById(R.id.showText);

        Button button = (Button) this.findViewById(R.id.button);
        Button showButton = (Button) this.findViewById(R.id.showButton);
        button.setOnClickListener(listener);
        showButton.setOnClickListener(listener);

        // 回顯上次儲存的值
        SharedPreferences sp = getSharedPreferences("ljq123", Context.MODE_PRIVATE);
        String nameValue = sp.getString("name", "");
        int ageValue = sp.getInt("age", 1);
        nameText.setText(nameValue);
        ageText.setText(String.valueOf(ageValue));
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        public void onClick(View v) {
            Button button = (Button) v;
            SharedPreferences sp = getSharedPreferences("ljq123", Context.MODE_PRIVATE);

            switch (button.getId()) {
                case R.id.button:
                    String name = nameText.getText().toString();
                    int age = Integer.parseInt(ageText.getText().toString());
                    Editor editor = sp.edit();          // 取得編輯器
                    editor.putString("name", name);
                    editor.putInt("age", age);
                    editor.commit();                    // 提交修改
                    Toast.makeText(SpActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                    break;

                case R.id.showButton:
                    String nameValue = sp.getString("name", "");
                    int ageValue = sp.getInt("age", 1);
                    resultText.setText("姓名:" + nameValue + ",年齡:" + ageValue);
                    break;
            }
        }
    };
}

小結

SharedPreferences 適合存放數量有限、結構簡單的設定資料,API 直覺、底層可讀,除錯時直接看 XML 檔就能確認內容。但它並不適合大量資料或需要查詢條件的情境,那仍然該交給 SQLite。另外別忘了 commit() 是同步寫入,apply() 則是先在記憶體生效再背景寫檔,在需要避免卡 UI 的場合更合適。

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