Droidster
Droidster

Reputation: 127

Change true false in preferences in java

I'm attempting to use a Button from view class to turn off sound from app. (ie: mute) When user pushes box i want code to check if value is already true or flase and then set to opposite using ID called 'mute'. I think i have the IF part setup, just need easy change SharedPreferences from true to flase and vice versa...

Here is code framework I'm testing(BEFORE):

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

}
if (cmute == false){

}

I have tried various findings for the solution but most are too complex for this simple need I think..

Here is my rework AFTER posted suggestion:

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

                }

Upvotes: 3

Views: 312

Answers (2)

weston
weston

Reputation: 54801

Comment on your AFTER suggestion version: There is no need to create an editor2, you don't even use it, you're referencing editor on subsequent lines. Also no need to call commit twice. And by using the not operator ! as platzhirsch already suggested, you remove the need for if(cmute...

Editor editor = getPrefs.edit(); 
editor.putBoolean("mute", !cmute);
editor.putBoolean("notice", !cmute); 
editor.commit(); 

Upvotes: 0

Konrad Reiche
Konrad Reiche

Reputation: 29513

This can be achieved with the Editor 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()

That should work for you:

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

Upvotes: 4

Related Questions