0

I am using SharedPreferences to save and load data saved as a string. I want to be able to save the data as a list, how do I do this and add to the list, instead of replacing the data?

This is how I save the data:

public void saveButton(View v) throws JSONException {
    String data = ((TextView) findViewById(R.id.randomJokeSetup)).getText().toString();
    String data2 = ((TextView) findViewById(R.id.randomJoke)).getText().toString();
    SharedPreferences datafile = getSharedPreferences("my_data_file", MODE_PRIVATE);
    SharedPreferences.Editor editor = datafile.edit();
    editor.putString("setup", data);
    editor.putString("punchline", data2);
    editor.commit();

    Snackbar.make(findViewById(R.id.save), "Joke saved!", Snackbar.LENGTH_SHORT).show();
}

This is how I load the data:

public void loadButton(View v){
    SharedPreferences datafile = getSharedPreferences("my_data_file", MODE_PRIVATE);
    String setup = datafile.getString("setup","");
    String punchline = datafile.getString("punchline","");
    ((TextView) findViewById(R.id.loadJokeSetup)).setText(setup);
    ((TextView) findViewById(R.id.loadJoke)).setText(punchline);
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • Does this answer your question? [Save ArrayList in shared preferences](https://stackoverflow.com/questions/17895888/save-arraylist-in-shared-preferences) – Vaibhav Goyal Nov 24 '21 at 13:32
  • @VaibhavGoyal Hi, not really, I'm a beginner so i dont really understand how to use that with my code – First Last Dec 04 '21 at 13:25

1 Answers1

0

You can turn your list to JSON with Gson or whatever you like and save it on SharedPreferences and when you wanna get data from it, get elements you need from that JSON string.

for more information look at this tutorial