Android array to Sharedpreferences with Gson

流过昼夜 提交于 2019-12-06 04:21:51

First let me give you an advise - if you have 3 question create 3 topics, not one with all the questions. Based on the question title: Android array to sharedpreferences I'll give an answer just to this issue.

So from your question you want to store a List<String> myList inside SharedPreferences. To do so I advise you to use Gson because it's simple. The main idea it's to serialize your List to a String in json and then store that String:

Since you are using primitive types you don't need to specify a TypeToken so you just need to:

public static final MY_LIST = "my_list";

List<String> myList = new ArrayList<String>();
SharedPreferences.Editor editor = prefs.edit();
editor.putString(MY_LIST, new Gson().toJson(myList));
editor.commit();

And it's stored. To retrieve the list just do the opposite:

myList = new Gson().fromJson(prefs.getString(MY_LIST, null), List<String>);

And that's it!
Hope it helped.

ps: SharedPreferences it's used to store values that can be accessed in other Classes/Activities/etc.. or to persist information between app restarts. You don't need this to accomplish what you want: Create a list with 5 ordered strings.

EDIT: this lib may save you some time with the serialization ;)

Tukajo

Try using an ArrayList with a custom Comparator as seen here: Sort ArrayList of custom Objects by property

Then, sort the ArrayList accordingly.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!