I have an ArrayList with custom objects. Each custom object contains a variety of strings and numbers. I need the array to stick around even if the user leaves the activity and then wants to come back at a later time, however I don't need the array available after the application has been closed completely. I save a lot of other objects this way by using the SharedPreferences but I can't figure out how to save my entire array this way. Is this possible? Maybe SharedPreferences isn't the way to go about this? Is there a simpler method?
当前回答
这应该可以工作:
public void setSections (Context c, List<Section> sectionList){
this.sectionList = sectionList;
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
String sectionListString = new Gson().toJson(sectionList,sectionListType);
SharedPreferences.Editor editor = getSharedPreferences(c).edit().putString(PREFS_KEY_SECTIONS, sectionListString);
editor.apply();
}
他们,要抓住它才:
public List<Section> getSections(Context c){
if(this.sectionList == null){
String sSections = getSharedPreferences(c).getString(PREFS_KEY_SECTIONS, null);
if(sSections == null){
return new ArrayList<>();
}
Type sectionListType = new TypeToken<ArrayList<Section>>(){}.getType();
try {
this.sectionList = new Gson().fromJson(sSections, sectionListType);
if(this.sectionList == null){
return new ArrayList<>();
}
}catch (JsonSyntaxException ex){
return new ArrayList<>();
}catch (JsonParseException exc){
return new ArrayList<>();
}
}
return this.sectionList;
}
这对我很管用。
其他回答
您可以将其转换为Map Object来存储它,然后在检索SharedPreferences时将值更改回ArrayList。
Android sharedpreferences允许您将基本类型(Boolean, Float, Int, Long, String和StringSet,自API11以来可用)作为xml文件保存在内存中。
任何解决方案的关键思想都是将数据转换为这些基本类型之一。
我个人喜欢将my list转换为json格式,然后将其保存为SharedPreferences值中的字符串。
为了使用我的解决方案,你必须添加谷歌gsonlib。
在gradle中只需添加以下依赖项(请使用谷歌的最新版本):
compile 'com.google.code.gson:gson:2.6.2'
保存数据(HttpParam是你的对象):
List<HttpParam> httpParamList = "**get your list**"
String httpParamJSONList = new Gson().toJson(httpParamList);
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(**"your_prefes_key"**, httpParamJSONList);
editor.apply();
检索数据(HttpParam是你的对象):
SharedPreferences prefs = getSharedPreferences(**"your_prefes_key"**, Context.MODE_PRIVATE);
String httpParamJSONList = prefs.getString(**"your_prefes_key"**, "");
List<HttpParam> httpParamList =
new Gson().fromJson(httpParamJSONList, new TypeToken<List<HttpParam>>() {
}.getType());
嘿,朋友们,我没有使用Gson库就得到了上述问题的解决方案。我在这里发布源代码。
1.变量声明,即
SharedPreferences shared;
ArrayList<String> arrPackage;
2.变量初始化,即
shared = getSharedPreferences("App_settings", MODE_PRIVATE);
// add values for your ArrayList any where...
arrPackage = new ArrayList<>();
3.使用packagesharedPreferences()将值存储到sharedPreference:
private void packagesharedPreferences() {
SharedPreferences.Editor editor = shared.edit();
Set<String> set = new HashSet<String>();
set.addAll(arrPackage);
editor.putStringSet("DATE_LIST", set);
editor.apply();
Log.d("storesharedPreferences",""+set);
}
4.使用retriveSharedValue()检索sharedPreference的值:
private void retriveSharedValue() {
Set<String> set = shared.getStringSet("DATE_LIST", null);
arrPackage.addAll(set);
Log.d("retrivesharedPreferences",""+set);
}
我希望这对你有帮助…
public void saveUserName(Context con,String username)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
usernameEditor = usernameSharedPreferences.edit();
usernameEditor.putInt(PREFS_KEY_SIZE,(USERNAME.size()+1));
int size=USERNAME.size();//USERNAME is arrayList
usernameEditor.putString(PREFS_KEY_USERNAME+size,username);
usernameEditor.commit();
}
catch(Exception e)
{
e.printStackTrace();
}
}
public void loadUserName(Context con)
{
try
{
usernameSharedPreferences= PreferenceManager.getDefaultSharedPreferences(con);
size=usernameSharedPreferences.getInt(PREFS_KEY_SIZE,size);
USERNAME.clear();
for(int i=0;i<size;i++)
{
String username1="";
username1=usernameSharedPreferences.getString(PREFS_KEY_USERNAME+i,username1);
USERNAME.add(username1);
}
usernameArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, USERNAME);
username.setAdapter(usernameArrayAdapter);
username.setThreshold(0);
}
catch(Exception e)
{
e.printStackTrace();
}
}
从SharedPreference中保存和检索ArrayList
public static void addToPreference(String id,Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
ArrayList<String> list = getListFromPreference(context);
if (!list.contains(id)) {
list.add(id);
SharedPreferences.Editor edit = sharedPreferences.edit();
Set<String> set = new HashSet<>();
set.addAll(list);
edit.putStringSet(Constant.LIST, set);
edit.commit();
}
}
public static ArrayList<String> getListFromPreference(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences(Constants.MyPreference, Context.MODE_PRIVATE);
Set<String> set = sharedPreferences.getStringSet(Constant.LIST, null);
ArrayList<String> list = new ArrayList<>();
if (set != null) {
list = new ArrayList<>(set);
}
return list;
}
推荐文章
- 如何隐藏动作栏之前的活动被创建,然后再显示它?
- 是否有一种方法以编程方式滚动滚动视图到特定的编辑文本?
- 在Android中将字符串转换为Uri
- 如何在NestedScrollView内使用RecyclerView ?
- 移动到另一个EditText时,软键盘下一步点击Android
- Android应用中的GridView VS GridLayout
- Activity和FragmentActivity的区别
- 右对齐文本在android TextView
- 权限拒绝:start前台需要android.permission.FOREGROUND_SERVICE
- 如何更改android操作栏的标题和图标
- Android Split字符串
- 让一个链接在安卓浏览器启动我的应用程序?
- 如何在Android工作室的外部库中添加一个jar ?
- GridLayout(不是GridView)如何均匀地拉伸所有子元素
- 如何让一个片段删除自己,即它的等效完成()?