user2677095
user2677095

Reputation: 471

Android Save Value of Switch between Different Activities

I currently am developing an app that has a menu, and one of the options on the menu is "Settings" where the user can basically decide to turn off sounds and other things like that. I currently have two switches in the Settings activity. Here is the java code for the Settings activity so far:

public class Options extends ActionBarActivity {
private  Switch ding;
private Switch countdown;
public  boolean isDingChecked;
public  boolean isCountdownChecked;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_options);
    ding = (Switch) findViewById(R.id.switch1);
    AppPreferences appPref;
    appPref = new AppPreferences(getApplicationContext(), "PREFS");
    appPref.SaveData("Value", "Tag");
    appPref.getData("state");
    if(appPref.getData("state").equals("true"))
    {
        ding.setChecked(true);
    }
    else if(appPref.getData("state").equals("false"))
    {
        ding.setChecked(false);
    }
    ding.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(ding.isChecked())
            {
                ding.setChecked(true);
            }
        }
    });
    countdown = (Switch) findViewById(R.id.switch2);
    countdown.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // do something, the isChecked will be
            // true if the switch is in the On position
            isCountdownChecked = isChecked;

        }
    });     
}
}

However, if I go back to the menu activity and then go back to the options activity, the switch's values go back to the default value. Is there a way I can save the state between different activities? Thanks!

Upvotes: 0

Views: 1331

Answers (1)

CaptainTeemo
CaptainTeemo

Reputation: 116

You can use SharedPreferences.

Store it:

SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("StringName", "StringValue");
// Commit the edits!
editor.commit();

Recover it:

SharedPreferences settings = getSharedPreferences("CoolPreferences", 0);
String silent = settings.getString("StringName", "DefaultValueIfNotExists");

You can also put and recover booleans and integers and others... http://developer.android.com/reference/android/content/SharedPreferences.html

Upvotes: 3

Related Questions