Android共享首选项示例教程
在本教程中,我们将在Android应用程序中使用"共享首选项"以键值对的形式存储数据。
ñ
Android共享首选项概述
共享首选项允许活动和应用程序以键-值对的形式保留首选项,类似于映射,即使用户关闭应用程序,该映射也将保留。
Android将"共享首选项"设置作为XML文件存储在DATA/data/{application package}目录下的shared_prefs文件夹中。
可以通过调用ʻEnvironment.getDataDirectory()获得DATA文件夹。
SharedPreferences是特定于应用程序的,即执行以下选项之一时数据会丢失:
- 关于卸载应用程序
- 清除应用程序数据时(通过"设置")
顾名思义,其主要目的是存储用户指定的配置详细信息,例如用户特定的设置,以保持用户登录到应用程序中。
要访问首选项,我们提供三种API供您选择:
- getPreferences():从您的Activity中使用,以访问特定于活动的首选项
- getSharedPreferences():从您的Activity(或者其他应用程序上下文)内部使用,用于访问应用程序级首选项
- getDefaultSharedPreferences():用于PreferenceManager上,以获取与Android整体偏好框架一致的共享偏好
在本教程中,我们将使用" getSharedPreferences()"。
该方法定义如下:
getSharedPreferences(字符串PREFS_NAME,int模式)
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共享首选项项目代码
" activity_main.xml"布局由两个EditText视图组成,这些视图存储并显示名称和电子邮件。
这三个按钮在MainActivity中实现各自的onClicks。
<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.theitroad.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) {
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
mypreference是存储共享首选项键值对的文件的名称。

