Reputation: 17
I have set up shared preferences to store the values of an ArrayList after a save data button is clicked within my app. This part is working fine.
The trouble I am having is that I have a recyclerview adapter which populates a recyclerview with rows. Each row contains a check box which turns the text in that row green when checked to indicate it has been completed.
My question is how can I add the checkbox state to my shared preferences and save that state so when I re-open the app the checkbox is saved.
Save button in oncreate in main activity
//Functionality for save button
final Button saveButton =findViewById(R.id.saveButtonGame);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
saveData();
}
});
Here is my code for my shared preferences in Main Activity (outside oncreate) to save arraylist. How can I implement my checkbox state into this?
//Save data when save button is clicked
private void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(gameList);
editor.putString("game list", json);
editor.apply();
}
//Load data on app start up
private void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("game list", null);
Type type = new TypeToken<ArrayList<String>>() {}.getType();
gameList = gson.fromJson(json, type);
if(gameList == null){
gameList = new ArrayList<>();
}
}
Upvotes: 2
Views: 236
Reputation: 506
You could create three integers for "On" and "Off" states and one to hold the switch value either on or off. This is how I did mine.
int reminderState;
int REMINDER_ON = 1;
int REMINDER_OFF = 0;
switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if (isChecked) {
reminderState = REMINDER_ON;
} else {
reminderState = REMINDER_OFF;
}
}
});
So in your saveData()
method, you store the reminderSate
value in your shared preferences.
And in loadData()
you check if the reminderState
is on or off then set your switch according to the switch state.
Upvotes: 2