Java – Change true false in preferences in java

Change true false in preferences in java… here is a solution to the problem.

Change true false in preferences in java

I’m trying to use a button in the View class to turn off the sound of an application. (i.e. mute)
When the user presses the box, I want the code to check if the value is already true or flase, and then set it to the opposite with an ID named “mute”. I guess I have the IF section setting, just need to simply change SharedPreferences from true to flase and vice versa….

This is the code framework I was testing (before):

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
if (cmute == true){                     

}
if (cmute == false){

}

I’ve tried various solutions for discovery, but I think most are too complicated for this simple need…

This is my rework after posting the proposal :

if (cmute == false){

Editor editor = getPrefs.edit();
                    editor.putBoolean("mute", true);
                    editor.commit();
                    Editor editor2 = getPrefs.edit();
                    editor.putBoolean("notice", true);
                    editor.commit();

}
                if (cmute == true){

Editor editor = getPrefs.edit();
                    editor.putBoolean("mute", false);
                    editor.commit();
                    Editor editor2 = getPrefs.edit();
                    editor.putBoolean("notice", false);
                    editor.commit();

}

Solution

This can be done by Editor to implement the interface:

Interface used for modifying values in a SharedPreferences object. All
changes you make in an editor are batched, and not copied back to the
original SharedPreferences until you call commit() or apply()

This should suit you :

SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
boolean cmute = getPrefs.getBoolean("mute", defValue);
Editor editor = getPrefs.edit();
editor.putBoolean("mute", !cmute);
editor.commit();

Related Problems and Solutions