java-SharedPreference中的Android列表

我正在尝试从SharedPreferences中的List编辑值,但某些地方出了问题.

我的SharedPreference是:

public class StepsData {
    static SharedPreferences data;
    static SharedPreferences.Editor editor;
    static final int VALUE_KEY = 0;
    static final List<String> LIST_KEY= new Vector<String>();
}

我通过以下方式使用SharedPref:

StepsData.data = getApplicationContext().getSharedPreferences("userData", MODE_PRIVATE);
StepsData.editor = StepsData.data.edit();

如果我想编辑或从VALUE_KEY中获取价值,则可以使用以下方法

int step = StepsData.data.getInt(String.valueOf(VALUE_KEY), 0);
editor.putInt(String.valueOf(VALUE_KEY), 0).apply();

但是我在使用List时遇到问题,我获取值的代码是:

List<String> myList = (List<String>) data.getStringSet(String.valueOf(LIST_KEY),null);

删除

List<String> clearList = new Vector<String>();
editor.putStringSet(String.valueOf(LIST_KEY), (Set<String>) clearList).apply();

但是有一个NullPointerException.在SharedPreference的List上使用诸如“ .clear()”之类的最佳方法是什么?如何从此List和size中获取值?

解决方法:

如果要将List对象存储在SharedPreference中,请使用gson库.
它将用于将列表对象转换为json格式,并将该json字符串存储到sharedPref中.
首先将此行包含在gradle文件中(应用级别)

compile ‘com.google.code.gson:gson:2.4’

下面的代码是将类型设置为列表

Type listType = new Typetoken<List<String>>(){}.getType();

Gson gson = new Gson();

现在创建列表对象并使用gson对象转换为json字符串格式并输入

List<String> myList = new ArrayList<>();
//add elements in myList object

String jsonFormat = gson.toJson(myList,listType);  
//adding to sharedPref  
editor.put("list",jsonFormat).apply();

现在从sharedPref获取值,并将json字符串转换回List对象.

//this line will get the json string from sharedPref and will converted into object of type list(specified in listType object) 
List<String> list = gson.fromJson(sharedPref.get("list",""),listType);  
//Now modify the list object as par your requirement and again do the same step of converting that list object into jsonFormat.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...