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<>();
}
}
Aucun commentaire:
Enregistrer un commentaire