2016-12-31 20 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' 
相關問題