共享preferences在Android的存储数组列表 [英] Shared Preferences for storing arraylist in android

查看:186
本文介绍了共享preferences在Android的存储数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有3个的ArrayList 的对象,我想它存储在Android应用程序,我想应用程序运行时获取它们。

I have 3 ArrayList objects, I want to store it in the android application and I want to fetch them when application is running.

另外,我想元素的顺序相同它们在的ArrayList
我应该去与共享preferences 或者是他们其他的方式来实现它。

Also, I want the same order of elements as their in the ArrayList Should I go with SharedPreferences or is their any other approach to achieve it.

当我使用共享preferences ,它使用 HashSet的尝试,并在该命令的的ArrayList 在不同获取它的时间。

When I am trying it using SharedPreferences, It uses HashSet, and in that the order of the ArrayList differs at the time of fetching it.

告诉我,我该如何实现这一目标而不破坏秩序?

Tell me how do I achieve this without disturbing the order?

推荐答案

如果您已经使用GSON在你的项目,那么你可以在字符串列表转换成JSON对象,并把它共享preference作为普通的字符串时您提取preference该字符串转换回成ArrayList中。这似乎很容易给我。

If you are already using gson in you project then you can convert that string list to json object and put it in sharedpreference as normal string and when you extract that string from preference convert it back into ArrayList. This seems very easy to me.

private List<String> searchHistoryList;
 Type listType = new TypeToken<ArrayList<String>>() { // object can be String here
            }.getType();
String previousHistory = sp.getString("KEY");
            searchHistoryList = new Gson().fromJson(previousHistory, listType);

我已经成功地在我的项目之一,用这个和它似乎是做工精细,即使有一个对象。确保在需要时添加任何空检查。

i have successfully used this in one of my project and it seems to be working fine even if there is an Object. MAke sure to add any null check if required.

这篇关于共享preferences在Android的存储数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆