储存bean
1.添加
代码:
/**
* 储存
*/
Gson gson=new Gson();
SharedPreferences sharedPreferences=getSharedPreferences(ConstantsUtils.SP_WISH_NAME,MODE_PRIVATE);//初始化储存
SharedPreferences.Editor edit = sharedPreferences.edit();//编辑器
String spStringJson = sharedPreferences.getString(ConstantsUtils.SP_WISH_KEY_LIST_BEAN_NAME, "");//取值,设置默认值
if (TextUtils.isEmpty(spStringJson)) {
WishBean wishBean=new WishBean();//创建bean对象
//设置值
wishBean.setName(name);
wishBean.setAuthor(author);
wishBean.setSetWishEndTime(endtime);
wishBean.setBackground(Integer.parseInt(bg));
wishBean.setWishType(Integer.parseInt(type));
listBean.add(wishBean);
Log.d("WishSettingActivity","hello ,i love you "+listBean.toString());
//储存起来
String toJson = gson.toJson(listBean);//BeanList转JSon
edit.putString(ConstantsUtils.SP_WISH_KEY_LIST_BEAN_NAME,toJson);
// wishBeanList.
edit.commit();//提交
Log.d("TAG", "onViewClicked: 为空");
}else {
Log.d("TAG", "onViewClicked: 不为空");
List<WishBean> listWishBean=gson.fromJson(spStringJson,new TypeToken<List<WishBean>>(){}.getType());
// String s = listWishBean.toString();
// 加入值
WishBean wishBean2=new WishBean();
wishBean2.setName(name);
wishBean2.setAuthor(author);
wishBean2.setSetWishEndTime(endtime);
wishBean2.setWishType(Integer.parseInt(type));
wishBean2.setBackground(Integer.parseInt(bg));
listWishBean.add(wishBean2);//加到listWishBean
//转换
String toJson2 = gson.toJson(listWishBean);
//储存
edit.putString(ConstantsUtils.SP_WISH_KEY_LIST_BEAN_NAME,toJson2);
//提交
edit.commit();
Log.d("TAG", "onViewClicked: "+listWishBean.toString());
}
思路
sharePreferences只能储存基本类型,不能储存bean
Gson储存转为json
gson.toJson(listWishBean);
再提交
edit.commit();//记得提交
添加
判断是否存在数据,如果存在就添加
取出,转List
List<WishBean> listWishBean=gson.fromJson(spStringJson,new TypeToken<List<WishBean>>(){}.getType());
添加bean
WishBean wishBean2=new WishBean();
wishBean2.setName(name);
wishBean2.setAuthor(author);
wishBean2.setSetWishEndTime(endtime);
wishBean2.setWishType(Integer.parseInt(type));
wishBean2.setBackground(Integer.parseInt(bg));
listWishBean.add(wishBean2);//加到listWishBean
储存与提交
//储存
edit.putString(ConstantsUtils.SP_WISH_KEY_LIST_BEAN_NAME,toJson2);
//提交
edit.commit();