I am new to Android development and am having a question about multiple switch buttons, how to retrieve values smartly, and make this data available for other activities?
Currently, I am implemented the save of the button state and retrieval of the information found in the current activity as followed:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
switchButtonOne = findViewById(R.id.switchButtonOne);
switchButtonOne.setChecked(true);
switchButtonTwo = findViewById(R.id.switchButtonTwo);
switchButtonTwo.setChecked(false);
//...... (In total there are 5 switch buttons)
//switchButtonOne
switchButtonOne.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if(isChecked){
stringArrayList.add("1");
}else {
stringArrayList.remove("1");
}
getArray(stringArrayList);
//SAVE
sharedPreferences[0] = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences[0].edit();
editor.putBoolean("1", switchButtonOne.isChecked());
editor.commit();
});
switchButtonOne.setChecked(sharedPreferences[0].getBoolean("1", false));
//switchButtonTwo
switchButtonTwo.setOnCheckedChangeListener((compoundButton, isChecked) -> {
if(isChecked){
stringArrayList.add("2");
}else {
stringArrayList.remove("2");
}
getArray(stringArrayList);
//SAVE
sharedPreferences[0] = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences[0].edit();
editor.putBoolean("2", switchButtonTwo.isChecked());
editor.commit();
});
//.......
}
I am sure there is a more efficient way to implement this and I would gladly appreciate effective resources to learn the best practices of making information and Activity state available between Activities.
Big thanks in advance