将不同的数据类型存储在同一共享首选项

时间:2018-02-01 04:14:01

标签: android sharedpreferences

我是android的新手,我想知道可以在相同的共享首选项中存储布尔值和整数值。

2 个答案:

答案 0 :(得分:2)

是的,可以将所有数据类型存储在共享首选项中:

/ *******创建SharedPreferences ******* /

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE); 
Editor editor = pref.edit();

/ ****************将数据存储为KEY / VALUE对******************* /

editor.putBoolean("key_name1", true);           // Saving boolean - true/false
editor.putInt("key_name2", "int value");        // Saving integer
editor.putFloat("key_name3", "float value");    // Saving float
editor.putLong("key_name4", "long value");      // Saving long
editor.putString("key_name5", "string value");  // Saving string

// Save the changes in SharedPreferences
editor.commit(); // commit changes

/ ****************获取SharedPreferences数据******************* /

//如果key的值不存在则返回第二个参数值 - 在这种情况下为null

pref.getBoolean("key_name1", null);         // getting boolean
pref.getInt("key_name2", null);             // getting Integer
pref.getFloat("key_name3", null);           // getting Float
pref.getLong("key_name4", null);            // getting Long
pref.getString("key_name5", null);          // getting String

/ ************从SharedPreferences中删除键值***************** /

editor.remove("key_name3"); // will delete key key_name3
editor.remove("key_name4"); // will delete key key_name4

// Save the changes in SharedPreferences
editor.commit(); // commit changes

/ ************清除SharedPreferences中的所有数据***************** /

 editor.clear();
 editor.commit(); // commit changes

答案 1 :(得分:0)

/**
     * Save value to shared preference.
     *
     * @param key     On which key you want to save the value.
     * @param value   The value which needs to be saved.
     * @param context the context
     * @description To save the value to a preference file on the specified key.
     */
    public synchronized void saveValue(String key, long value, Context context) {

        SharedPreferences prefs =PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor saveValue = prefs.edit();
        saveValue.putLong(key, value);
        saveValue.apply();
    }

    /**
     * Gets value from shared preference.
     *
     * @param key          The key from you want to get the value.
     * @param defaultValue Default value, if nothing is found on that key.
     * @param context      the context
     * @return the value from shared preference
     * @description To get the value from a preference file on the specified
     * key.
     */
    public synchronized String getValue(String key, String defaultValue, Context context) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getString(key, defaultValue);
    }

虽然如果您想在共享首选项中保存POJO,请转到GSON