Android Shared Preferences示例教程

在本教程中,我们将在我们的安卓应用程序中使用Shared Preferences键-值对的形式存储数据。

安卓 Shared Preferences 概述

Shared Preferences 允许活动和应用程序保持首选项,以键-值对的形式类似于 Map 来持久化,即使用户关闭了应用程序也会保持。安卓将 Shared Preferences 设置存储为 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