一.基本介绍
1.简单介绍
SharedPreferences是一种轻型的存储方式,它的原理是基于xml存储key-value键值对数据,通常用来存储一些简单的配置信息。
存储位置:/data/data/{包名}/shared_prefs目录下。
SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。
2.优缺点分析
优点:
SharedPreferences对象与SQLite数据库相比,更加的轻量级,不需要创建数据库,创建表,写SQL语句等一系列的操作。
缺点:
①SharedPreferences只支持这几种类型的数据:boolean、 int 、float、 long、String
②它不支持条件查询等,所以尽管SharedPreferences操作起来非常方便,但它也只能作为存储方式的一种补充,而无法完全替代SQLite数据库等其他数据存储方式。
3.获取SharedPreferences对象
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0gTMx81dsQWZ4lmZf1GLlpXazVmcvwFciV2dsQXYtJ3bm9CX9s2RkBnVHFmb1clWvB3MaVnRtp1XlBXe0xCMy81dvRWYoNHLwEzX5xCMx8FesU2cfdGLwMzX0xiRGZkRGZ0Xy9GbvNGLpZTY1EmMZVDUSFTU4VFRR9Fd4VGdsYTMfVmepNHLrJXYtJXZ0F2dvwVZnFWbp1zczV2YvJHctM3cv1Ce-cmbw5SM2QzNygzNzczNhdzNyUDNzYzX0ETMyYTMxEzLcBTMyIDMy8CXn9Gbi9CXzV2Zh1WavwVbvNmLvR3YxUjLyM3Lc9CX6MHc0RHaiojIsJye.png)
由源码可知SharedPreferences本身是一个接口,程序无法直接创建它的实例,但是可以通过Context提供的方法来获取实例。方法有两个
@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
return mBase.getSharedPreferences(name, mode);
}
/** @removed */
@Override
public SharedPreferences getSharedPreferences(File file, int mode) {
return mBase.getSharedPreferences(file, mode);
}
一般我们是用第一个,即
getSharedPreferences(String name, int mode)
来获取它的实例,该方法的第二个参数支持如下几个值:
Context.MODE_PRIVATE :只被本地程序读写。
Context.MODE_WORLD_READABLE :能被其他程序读。
Context.MODE_WORLD_WRITEABLE :能被其他程序读、写。
关于这部分的源码(部分略去)
public abstract class Context {
/** @hide */
@IntDef(flag = true, prefix = { "MODE_" }, value = {
MODE_PRIVATE,
MODE_WORLD_READABLE,
MODE_WORLD_WRITEABLE,
MODE_APPEND,
})
@Retention(RetentionPolicy.SOURCE)
public @interface FileMode {}
/** @hide */
@IntDef(flag = true, prefix = { "MODE_" }, value = {
MODE_PRIVATE,
MODE_WORLD_READABLE,
MODE_WORLD_WRITEABLE,
MODE_MULTI_PROCESS,
})
@Retention(RetentionPolicy.SOURCE)
public @interface PreferencesMode {}
/** @hide */
@IntDef(flag = true, prefix = { "MODE_" }, value = {
MODE_PRIVATE,
MODE_WORLD_READABLE,
MODE_WORLD_WRITEABLE,
MODE_ENABLE_WRITE_AHEAD_LOGGING,
MODE_NO_LOCALIZED_COLLATORS,
})
@Retention(RetentionPolicy.SOURCE)
public @interface DatabaseMode {}
public static final int MODE_PRIVATE = 0x0000;
@Deprecated
public static final int MODE_WORLD_READABLE = 0x0001;
@Deprecated
public static final int MODE_WORLD_WRITEABLE = 0x0002;
public static final int MODE_APPEND = 0x8000;
@Deprecated
public static final int MODE_MULTI_PROCESS = 0x0004;
public static final int MODE_ENABLE_WRITE_AHEAD_LOGGING = 0x0008;
public static final int MODE_NO_LOCALIZED_COLLATORS = 0x0010;
4.SharedPreferences的常用方法
①boolean contans(String key) :判断SharedPreferences中是否包含特定key的数据。
/**
* Checks whether the preferences contains a preference.
*
* @param key The name of the preference to check.
* @return Returns true if the preference exists in the preferences,
* otherwise false.
*/
boolean contains(String key);
②abstract Map getAll() :获取全部的key-value键值对。
/**
* Retrieve all values from the preferences.
*
* <p>Note that you <em>must not</em> modify the collection returned
* by this method, or alter any of its contents. The consistency of your
* stored data is not guaranteed if you do.
*
* @return Returns a map containing a list of pairs key/value representing
* the preferences.
*
* @throws NullPointerException
*/
Map<String, ?> getAll();
③Xxx getXxx(String key, Xxx default) : 获取指定key对应的值,如果该key不存在,返回default值。
比如
/**
* Retrieve a String value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defValue Value to return if this preference does not exist.
*
* @return Returns the preference value if it exists, or defValue. Throws
* ClassCastException if there is a preference with this name that is not
* a String.
*
* @throws ClassCastException
*/
@Nullable
String getString(String key, @Nullable String defValue);
二.Editor
最开始讲过,SharedPreferences本身没有提供写入数据的方法,而是通过SharedPreferences的对象调用editor方法获取Editor对象来写入数据。Editor的常用方法如下:
Editor常用方法
clear() :清空SharedPreferences里所有数据。
putXxx(String key, Xxx value) :向SharedPreferences中写入数据。
remove(String key) :删除SharedPreferences中指定key的值。
commit() :当Editor编辑完,该方法提交修改。
三.详细使用示例
具体代码
在xml里面,只有四个控件,整体是LinearLayout。如下
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:layout_marginTop="100dp"
android:id="@+id/et_data"
android:layout_width="match_parent"
android:layout_height="100dp"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/btn_read"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="读取" />
<Button
android:id="@+id/btn_write"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="写入" />
<Button
android:id="@+id/btn_clear"
android:layout_width="match_parent"
android:layout_height="100dp"
android:text="清除" />
</LinearLayout>
剩余代码都在MainActivity里面了。如下
public class MainActivity extends AppCompatActivity {
//首先创建SharedPreferences和Editor对象
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
//然后获取自己定义的四个控件对象
EditText et_data;
Button btn_read;
Button btn_write;
Button btn_clear;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//给preferences和editor对象赋值
preferences = getSharedPreferences("config", Activity.MODE_PRIVATE);
editor = preferences.edit();
//给自己定义的四个控件赋值
et_data = (EditText)findViewById(R.id.et_data);
btn_read = (Button) findViewById(R.id.btn_read);
btn_write = (Button) findViewById(R.id.btn_write);
btn_clear = (Button) findViewById(R.id.btn_clear);
//分别给三个按钮控件添加点击事件
btn_read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str = preferences.getString("key","没有该数据");
Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
}
});
btn_write.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.putString("key",et_data.getText().toString());
if(editor.commit()){
Toast.makeText(getApplicationContext(),"写入成功",Toast.LENGTH_LONG).show();
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
editor.clear();
if(editor.commit()){
Toast.makeText(getApplicationContext(),"清除成功",Toast.LENGTH_LONG).show();
}
}
});
}
}
效果如下
它具体是存在