-1

i am new to Android and i try to complete my first android app. I have an arraylist of strings(which i have adapted into a listview) and i add different strings by pressing different buttons. The problem is that when the app closes, the arraylist loses all the data, and i have read that sharedpreferences class can solve this problem.I tried that, and i retrieved the arraylist back, but not with the same order as it was when i saved it. So, how can i retrieve the arraylist with the same order? Thanks in advance!

dimitris tseggenes
  • 3,031
  • 2
  • 16
  • 23
  • you save those arraylist as what? string? map? – ZeroOne Oct 09 '17 at 16:50
  • Sqlite is (for me) a lot easier and organised. I know `SharedPreferences` is very easy to implement, but at least have a look at sqlite. – HB. Oct 09 '17 at 17:05
  • 3
    Possible duplicate of [Put and get String array from shared preferences](https://stackoverflow.com/questions/7965290/put-and-get-string-array-from-shared-preferences) – petey Oct 09 '17 at 17:21

2 Answers2

2

the EASIEST way to save arraylist in sharedpreferences is convert it into JSON and 100% in the same order when you get it

String list = new Gson().toJson(your_list);
shared.putString("KEY", list).apply();

then, to convert it back

List<Object> list = new Gson().fromJson(jsonString, new TypeToken<ArraList<Object>>(){}.getType());
ZeroOne
  • 8,996
  • 4
  • 27
  • 45
1

If you're really interested on doing that using SharedPreferences instead of a database, you could try to save the Strings using their position on the array as the key on the preferences file.

You can achieve that with the snippet below:

private String prefName = "preferences";


/**
* Save the arraylist of Strings in a preferences file.
*/
public void saveArray(Context context, ArrayList<String> myArray) {
    SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
    Editor editor = sharedPref.edit();

    for (int i = 0; i < myArray.size(); i++) {
        editor.putString(String.valueOf(i), myArray.get(i));
    }

    editor.commit();
}

/**
* Reads the saved contents in order.
*/
public ArrayList<String> readArray(Context context) {
    SharedPreferences sharedPref = context.getSharedPreferences(prefName,Context.MODE_PRIVATE);
    Editor editor = sharedPref.edit();

    int size = sharedPref.getAll().size();
    ArrayList<String> ret = new ArrayList<>();

    for (int i = 0; i < myArray.size(); i++) {
        ret.add(i,sharedPref.getString(String.valueOf(i)));
    }

    return ret;
}

The preference file should look something like this:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="0">My String</string>
    <string name="1">My second String</string>
</map>
Mauker
  • 11,237
  • 7
  • 58
  • 76