When saving an ArrayList on Android, if it's as simple as using SQLite, It is convenient to convert it to JSON and save it in Preference.
Also, I think it will be easier to use GSON (Google library) when converting to JSON. https://github.com/google/gson
This time, convert the ʻArrayList
Introduced gson library with gradle in Android Studio.
dependencies{
...
...
compile 'com.google.code.gson:gson:2.7' //May be a little old
}
private ArrayList<String> arrayList;
SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
arrayList = gson.fromJson(pref.getString(SAVE_KEY, ""), new TypeToken<ArrayList<String>>(){}.getType());
If you want to branch the processing of the unsaved state to preference, like this
private ArrayList<String> arrayList;
SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
String json = pref.getString(SAVE_KEY, "");
if(json.equals("[]"))
{
arrayList = new ArrayList<>();
}
else
{
arrayList = gson.fromJson(json, new TypeToken<ArrayList<String>>(){}.getType());
}
SharedPreferences pref = getSharedPreferences("pref", MODE_PRIVATE);
Gson gson = new Gson();
pref.edit().putString(SAVE_KEY, gson.toJson(arrayList)).apply();
Recommended Posts