有时候咱们想在利用中存储一些数据。比方一些配置信息。 例如存储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.xmlx5_proxy_setting.xml等等。

<pre id="__code_2" style="box-sizing: inherit; color: var(--md-code-fg-color); font-feature-settings: &quot;kern&quot;; font-family: &quot;Roboto Mono&quot;, 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。

  • getInt
  • getBoolean
  • getFloat
  • getLong
  • getString
  • getStringSet

上面代码是把数据读出,并且显示进去。

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());}

Android零根底入门教程视频参考