有时候我们想在应用中存储一些数据。比如一些配置信息。 例如存储int,float,boolean,字符串这类的数据。
写文件可能会比较繁琐。需要自己实现文件读写操作,定义数据存放结构。 对于这些简单的数据,我们可以用 SharedPreferences (下文或简称sp)来进行存储。
sp 使用的是 key-value 类型的数据结构。之前接触到的 json格式也是 key-value 类型的。
第一步是获取到一个 SharedPreferences 对象。在Activity中,可以调用
getSharedPreferences(String name, int mode)方法。需要传入这个sp的名字。
private static final String SP_1 = "sp_1";getSharedPreferences(SP_1, Context.MODE_PRIVATE)
存入各项数据。int有对应的
putInt方法。同理,boolean、float、long、String、StringSet都有对应的put方法。 也简写为
putXxx方法。
private void saveParams() {
Set<String> set = new HashSet<>(); set.add("R"); set.add("u"); set.add("s"); set.add("t");
getSharedPreferences(SP_1, Context.MODE_PRIVATE).edit()
.putInt(K_1, 1000)
.putBoolean(K_2, true)
.putFloat(K_3, 3.14159f)
.putLong(K_4, System.currentTimeMillis())
.putString(K_5, "RustFisher")
.putStringSet(K_6, set)
.apply();
}
最后调用
apply() 方法,把数据写入。 注意
apply()方法,它并不保证立刻把数据写入。它是一个异步的方法。
而
commit()是一个同步方法。它会在当前线程立刻执行。
官方推荐使用
apply()来保存信息。
运行到机器上。如果数据保存成功,在as的Device File Explorer面板中,我们可以找到文件
/data/data/com.rustfisher.tutorial2020/shared_prefs/sp_1.xml。
使用sp,会在应用内部的
shared_prefs目录创建xml文件。
运行示例工程,我们可以看到
shared_prefs目录有别的库创建的sp文件。 例如
BuglySdkInfos.xml或
x5_proxy_setting.xml等等。
<pre id="__code_2" style="box-sizing: inherit; color: var(--md-code-fg-color); font-feature-settings: "kern"; font-family: "Roboto Mono", SFMono-Regular, Consolas, Menlo, monospace; direction: ltr; position: relative; margin: 1em 0px; line-height: 1.4;">`<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map> <int name="k1" value="1000" /> <boolean name="k2" value="true" /> <float name="k3" value="3.14159" /> <long name="k4" value="1605628186953" /> <string name="k5">RustFisher</string> <set name="k6"> <string>R</string> <string>s</string> <string>t</string> <string>u</string> </set></map>
可看出它存储使用的是xml文件,外围标签是
<map>。
存入数据后,我们可以把数据读出来。和
putXxx方法类似,sp提供了
getXxx方法。
例如
int getInt(String key, int defValue);方法。 后面的defValue是默认值。如果这个key没有对应的int,则返回默认值defValue。
下面代码是把数据读出,并且显示出来。
private void readParams() {
SharedPreferences sp = getSharedPreferences(SP_1, Context.MODE_PRIVATE);
StringBuilder sb = new StringBuilder();
sb.append(K_1).append(": ").append(sp.getInt(K_1, -1));
sb.append("\n").append(K_2).append(": ").append(sp.getBoolean(K_2, false));
sb.append("\n").append(K_3).append(": ").append(sp.getFloat(K_3, -1));
sb.append("\n").append(K_4).append(": ").append(sp.getLong(K_4, -1));
sb.append("\n").append(K_5).append(": ").append(sp.getString(K_5, "none"));
sb.append("\n").append(K_6).append(": ").append(sp.getStringSet(K_6, null));
mTv1.setText(sb.toString());
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70008155/viewspace-2847755/ ,如需转载,请注明出处,否则将追究法律责任。