简体   繁体   中英

Save the state of a ToggleButton using SharedPreferences

I have seen other similar questions, but none are working out! I have a toggle button. I want to save the state of the ToggleButton (checked true or false) even when the app is closed/reopened.

My code looks like this below, but it will not run

public class MainActivity extends AppCompatActivity {

    ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
private void savePreference(Context context)
{
    SharedPreferences.Editor editor = context.getSharedPreferences("toggleState1", 0).edit();
    editor.putBoolean("toggleState1", toggle1.isChecked());
    editor.commit();
}

private void loadPreference (Context context)
{
    SharedPreferences prefs = context.getSharedPreferences("toggleState1", 0);
    toggle1.setChecked(prefs.getBoolean("toggleState1", false));
}};

Thanks for the help!

ToggleButton toggle1 = (ToggleButton) findViewById(R.id.toggle1);

should be INSIDE onCreate() , make it the last statement.

Also, it's easier to use

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);

Alright I have the answer for future reference. My original attempt did not use shared preferences properly. You must create a "key" and a "name" for the shared preference object. Then call it in code as follows:

public class MainActivity extends AppCompatActivity {

private static final String APP_SHARED_PREFERENCE_NAME = "AppSharedPref";
private final static String TOGGLE_STATE_KEY1 = "TB_KEY1";
ToggleButton toggle1;
SharedPreferences sharedPreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sharedPreferences = getSharedPreferences(APP_SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
    toggle1 = (ToggleButton) findViewById(R.id.toggle1);
    toggle1.setChecked(GetState());
    toggle1.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
            SaveState(isChecked);
        }
    });
}

private void SaveState(boolean isChecked) {
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(TOGGLE_STATE_KEY1, isChecked);
    editor.commit();
}

public boolean GetState() {
    return sharedPreferences.getBoolean(TOGGLE_STATE_KEY1, false);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM