//保存实体类
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 这个好像只能保存一条数据,如果保存的不是账号密码这样的只有一条的东西,还是换数据库吧
本文介绍如何利用Gson库将实体类转换为JSON字符串,并使用SharedPreferences进行存储和读取。通过实例演示了存储单个实体及实体列表的过程,强调了在处理大量数据时考虑使用数据库。
7387

被折叠的 条评论
为什么被折叠?



