如何从共享首选项

时间:2016-01-07 15:52:38

标签: android

如何在共享首选项中保存和检索布尔标志。我试过下面的东西,但似乎没有工作

保存:

SharedPreferences prefs = activity.getSharedPreferences(PREFERENCES_EULA, Activity.MODE_PRIVATE);
Boolean lock = prefs.edit().putBoolean("locked", true).commit();

检索:

SharedPreferences prefes = PreferenceManager.getDefaultSharedPreferences(context);
Boolean yourLocked = prefes.getBoolean("locked", false); 

在这里应该变为“true”,因为我在保存时传递“true”

2 个答案:

答案 0 :(得分:1)

我认为你得到了SharedPreferences的两个不同实例。

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("locked", true);
editor.commit();

然后

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean value = sharedPref.getBoolean("locked", false);

答案 1 :(得分:1)

/******* Create SharedPreferences *******/

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


/**************** Storing data as KEY/VALUE pair *******************/

    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


/**************** Get SharedPreferences data *******************/

// If value for key not exist then return second param value - In this case 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




/************ Deleting Key value from 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

/************ Clear all data from SharedPreferences *****************/   

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