2016-12-31 22 views
1

这是一个数组列表,最初我尝试将它改为一个set,所以我可以将它放在putStringSet中。但没错..它没有字符串数据类型在putStringSet中放置一个非String数据类型SharedPreferences Android

Set<RecordData> set = new HashSet<>(dataList); 
     SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
     SharedPreferences.Editor editor = preferences.edit(); 
     editor.putStringSet("recordlists", set); 

RecordData是我创建的类。

我吮吸。

+1

重复 - HTTP://计算器.com/questions/7057845/save-arraylist-to-sharedpreferences –

+0

你对将它转换为一个集合是正确的,但是你以错误的方式存储它。检查上面提到的链接。 –

+0

你也可以使用Gson库来存储和检索自定义对象 - 这里解释 - http://stackoverflow.com/a/36184406/3225001 –

回答

0

可以使用GSON库.. 尝试这对于保存和加载共享偏好数据:

public static void saveSharedPreferencesLogList(Set<RecordData> record) { 
      SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
      SharedPreferences.Editor prefsEditor = preferences.edit(); 
      Gson gson = new Gson(); 
      String json = gson.toJson(record); 
      prefsEditor.putString("myJson", json); 
      prefsEditor.commit(); 
     } 


     public static Set<RecordData> loadSharedPreferencesLogList() { 
      Set<RecordData> record = new HashSet<>(dataList); 

      SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); 
      Gson gson = new Gson(); 
      String json = preferences.getString("myJson", ""); 
      if (json.isEmpty()) { 
       record = new Set<RecordData>(); 
      } else { 
       Type type = new TypeToken<Set<RecordData>>() { 
       }.getType(); 
       record = gson.fromJson(json, type); 
      } 
      return record; 
     } 

而且把这个在您的摇篮文件:

compile 'com.google.code.gson:gson:2.6.2' 
相关问题