Android Getting Started tutorial | introduction to SharedPreferences

Sometimes we want to store some data in the application. For example, some configuration information. For example, it stores data such as int, float, boolean and string.

Writing files can be cumbersome. You need to read and write files and define the data storage structure. For these simple data, we can use shared preferences (hereinafter referred to as sp) for storage.

sp uses a key value data structure. The json format I touched earlier is also of type key value.

Save data

The first step is to get a SharedPreferences object. In the Activity, you can call the getSharedPreferences(String name, int mode) method. The name of this sp needs to be passed in.

private static final String SP_1 = "sp_1";

getSharedPreferences(SP_1, Context.MODE_PRIVATE)

Store various data. int has a corresponding putInt method. Similarly, boolean, float, long, String and StringSet all have corresponding put methods. Also abbreviated as putXxx method.

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

Finally, we call the apply() method to write the data. Note the apply() method, which does not guarantee that data is written immediately. It is an asynchronous method.

commit() is a synchronization method. It will execute immediately on the current thread.

The official recommendation is to use apply() to save information.

Run on the machine. If the data is saved successfully, we can find the file / data / data / com.rustfisher.tutorial2020/shared in the Device File Explorer panel of as_ prefs/sp_ 1.xml.

Using sp, the shared in the application will be displayed_ Create an xml file from the prefs directory.

Run the sample project, and we can see the shared_ The prefs directory has sp files created by other libraries. For example, BuglySdkInfos.xml or x5_proxy_setting.xml and so on.

<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>

It can be seen that it stores and uses xml files, and the peripheral label is < Map >.

Read data

After storing the data, we can read it out. Similar to the putXxx method, sp provides the getXxx method.

For example, int getInt(String key, int defValue); method. The following defValue is the default value. If the key has no corresponding int, the default value defValue is returned.

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

The following code reads out the data and displays it.

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 zero foundation tutorial video reference

Keywords: Android

Added by Leonardo Dantas on Thu, 18 Nov 2021 13:04:20 +0200