Android 如何保存實體類

//保存實體類
sharedPreferences = getSharedPreferences("housingItem",MODE_PRIVATE);
SharedPreferences.Editor edit = sharedPreferences.edit();
edit.putString("housingItem",new Gson().toJson(housingItem));
edit.commit();

//獲取實體類

SharedPreferences housingItem1 = getSharedPreferences("housingItem", 0);
String housingItem2 = housingItem1.getString("housingItem", "");
Gson gson=new Gson();
Housing housingItem = gson.fromJson(housingItem2, new TypeToken<Housing>(){}.getType());
housingList.add(housingItem);

 

Housing是集合的類型,如下圖

housingList是集合 

List<Housing> housingList = new ArrayList<>();

 

重點是藉助Gson。通過這件事我發現要活學活用。

sharedPreferences  這個好像只能保存一條數據,如果保存的不是賬號密碼這樣的只有一條的東西,還是換數據庫吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章