Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change true false in preferences in java

Tags:

java

android

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

                }
like image 606
Droidster Avatar asked Aug 17 '26 04:08

Droidster


1 Answers

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();
like image 164
Konrad Reiche Avatar answered Aug 18 '26 19:08

Konrad Reiche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!