Android 共享偏好設置示例教程

在這個教程中,我們將在我們的安卓應用程序中使用共享偏好設置來以鍵值對的形式存儲數據。n

安卓共享偏好設置概述

共享偏好設置允許活動和應用程序保存偏好設置,類似於一個 Map 的鍵值對,即使用戶關閉應用程序,這些設置也會持久存在。安卓將共享偏好設置存儲為 XML 文件,存放在 DATA/data/{應用程序包名} 目錄下的 shared_prefs 文件夾中。可以通過調用 Environment.getDataDirectory() 來獲取 DATA 文件夾。 SharedPreferences 是應用程序特定的,即執行以下操作之一時數據將會丟失:

  • 卸載應用程序
  • 清除應用程序數據(通過設置)

正如其名,主要目的是存儲用戶指定的配置詳細信息,例如用戶特定的設置,保持用戶登錄應用程序。要訪問偏好設置,我們有三個 API 可供選擇:

  • getPreferences():從您的 Activity 內部使用,訪問活動特定的偏好設置
  • getSharedPreferences():從您的 Activity(或其他應用程序上下文)內部使用,訪問應用程序級別的偏好設置
  • getDefaultSharedPreferences():在PreferenceManager上使用,以與Android的整體偏好框架協同工作。

在本教程中,我們將使用getSharedPreferences()。方法定義如下:getSharedPreferences(String PREFS_NAME, int mode) PREFS_NAME是文件的名稱。mode是操作模式。以下是適用的操作模式:

  • MODE_PRIVATE:默認模式,所建立的文件只能被調用應用程序訪問。
  • MODE_WORLD_READABLE:創建可全局讀取的文件非常危險,可能導致應用程序的安全漏洞。
  • MODE_WORLD_WRITEABLE:創建可全局寫入的文件非常危險,可能導致應用程序的安全漏洞。
  • MODE_MULTI_PROCESS:即使已經加載了共享偏好實例,此方法也將檢查偏好的修改。
  • MODE_APPEND:這將將新的偏好附加到已有的偏好中。
  • MODE_ENABLE_WRITE_AHEAD_LOGGING:數據庫打開標誌。當設置時,它將啟用默認的寫入日誌記錄。

初始化

我們需要一個編輯器來編輯並保存共享偏好設置。以下代碼可用於獲取共享偏好設置。

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

存儲數據

editor.commit() 用於保存對共享偏好設置的更改。

editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
 
editor.commit(); // commit changes

檢索數據

通過調用getString() 可以從已保存的偏好設置中檢索數據,如下所示:

pref.getString("key_name", null); // getting String
pref.getInt("key_name", -1); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean

清除或刪除數據

remove(“key_name”) 用於刪除該特定值。clear() 用於刪除所有數據

editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
 
editor.commit(); // commit changes
editor.clear();
editor.commit(); // commit changes

項目結構

Android Shared Preferences 專案程式碼

activity_main.xml 佈局包含兩個 EditText 視圖,用於儲存和顯示姓名和電子郵件。三個按鈕在 MainActivity 中實現各自的 onClick 事件。

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="Save"
        android:text="Save" />

    <Button
        android:id="@+id/btnRetr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="Get"
        android:text="Retrieve" />

    <Button
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etEmail"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="clear"
        android:text="Clear" />

    <EditText
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/etName"
        android:layout_marginTop="20dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <EditText
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/etEmail"
        android:layout_alignStart="@+id/etEmail" />

</RelativeLayout>

MainActivity.java 文件用於通過鍵保存和檢索數據。

package com.journaldev.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }

    }

    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // 填充菜單;如果存在操作欄,則將項目添加到其中。
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

mypreference 是存儲共享偏好鍵值對的文件名。下圖顯示了我們專案的最終輸出: 這結束了本教程。您可以從以下鏈接下載專案 Android Shared Preferences

下載 Android Shared Preferences 示例專案

Source:
https://www.digitalocean.com/community/tutorials/android-shared-preferences-example-tutorial