Android共享首选项示例教程
在本教程中,我们将使用Android应用程序中的Shared Preferences来以键值对的形式存储数据。
Android共享首选项概述
共享首选项允许活动和应用程序保留偏好设置,以键值对的形式存储,类似于 Map,即使用户关闭应用程序,这些偏好设置也会持久化。Android将共享首选项设置存储为 XML 文件,位于DATA/data/{应用程序包}目录下的shared_prefs文件夹中。通过调用Environment.getDataDirectory()可以获取DATA文件夹。SharedPreferences是应用程序特定的,即在执行以下选项之一时数据会丢失:
- on uninstalling the application
- on clearing the application data (through Settings)
正如其名,主要目的是存储用户指定的配置细节,例如用户特定的设置,使用户保持登录状态。为了访问偏好设置,我们有三个可供选择的API。
- getPreferences() : used from within your Activity, to access activity-specific preferences
- getSharedPreferences() : used from within your Activity (or other application Context), to access application-level preferences
- getDefaultSharedPreferences() : used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
在本教程中,我们将使用getSharedPreferences()方法。该方法的定义如下:getSharedPreferences (String PREFS_NAME, int mode) PREFS_NAME是文件的名称,mode是操作模式。以下是可适用的操作模式:
- MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application
- MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applications
- MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications
- MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
- MODE_APPEND: This will append the new preferences with the already existing preferences
- MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write ahead logging by default
初始化
我们需要一个编辑器来编辑并保存共享偏好设置中的更改。可以使用以下代码来获取共享偏好设置。
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
项目结构
安卓共享偏好设置项目的代码
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.Olivia.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;
}
}
我的偏好是存储共享偏好键值对的文件名。下图显示了我们项目的最终输出:这结束了本教程。您可以从下方链接下载Android共享偏好项目。
下载一个Android Shared Preferences示例项目。