Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android sharedpreferences set value

I have preferences page. It has field 'Show info screen' (as checkbox).

I have also info page which also should have checkbox 'Show me again'.

As I've understand, I can get value from preferences page via PreferencesManager.getDefaultPreferences(context) ...

But how I should set preferences value for the checkbox on info page?

I tried to use context.getSharedPreferences(PREF_NAME, 0).edit(), to set value but it doesn't correlate with PreferencesManager's corresponding value.

What should I do??? F1

like image 243
davs Avatar asked Jul 25 '10 08:07

davs


People also ask

How do you use SharedPreferences in Android to store fetch and edit values?

Shared Preferences allow you to save and retrieve data in the form of key,value pair. In order to use shared preferences, you have to call a method getSharedPreferences() that returns a SharedPreference instance pointing to the file that contains the values of preferences.

How can I get SharedPreferences value?

getBoolean(String key, boolean defValue): This method is used to retrieve a boolean value from the preferences. getFloat(String key, float defValue): This method is used to retrieve a float value from the preferences. getInt(String key, int defValue): This method is used to retrieve an int value from the preferences.

How do I edit SharedPreferences?

Public methods. Commit your preferences changes back from this Editor to the SharedPreferences object it is editing. Mark in the editor to remove all values from the preferences. Commit your preferences changes back from this Editor to the SharedPreferences object it is editing.

How do I save key-value data?

If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences APIs. A SharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them.


1 Answers

It depends on whether you are after one set of preferences for your application, or one set per activity.

I've used code like this:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); Editor editor = prefs.edit(); editor.putBoolean(PREF_NAME, false); editor.commit(); 

and

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); if (prefs.getBoolean(PREF_NAME, true)) {     // etc } 
like image 129
Stephen Denne Avatar answered Oct 14 '22 12:10

Stephen Denne