Android 学习笔记之SharedPreference
SharedPreference作为android常用的四种存储方式之一,在轻量级的使用中比较常见
创建、获取sharedpreference
SharedPreferences myPreference;myPreference = getSharedPreferences("myPreference", Context.MODE_PRIVATE);
写入数据
SharedPreferences.Editor editor = myPreferences.edit();String userIfo = "abc";editor.putString("userIfo", userIfo);editor.apply();//editor.commit()
可放入的数据类型有如下所示
读数据
myPreference = getSharedPreferences("myPreference", Context.MODE_PRIVATE);String userIfo = myPreference.getStringSet("userIfo", " ");//第二个参数为读取不成功时默认值
但是这样对对象的存储并不方便,我在网上又get到可以使用Gson框架将对象数据转换为String进行存储
需要在build.gradle配置文件中添加如下代码
dependencies { implementation 'com.google.code.gson:gson:2.8.5'}
Gson 进行 转换
User user = new User();Gson gson = new Gson();String jsonStr = gson.toJson(user); // User对象转换为StringUser user_1 = gson.fromJson(jisonStr, User.class) //String转换为User
所以也能够在SharedPreference中借助putStringSet存储多个对象数据
但是并不建议这样做,SharedPreference只适用于存储体量较小的数据,否则极易造成运行卡顿掉帧等
存储
private SharedPreferences myPreference;user = new User();user1 = new User("abc","123",true);myPreferences = getSharedPreferences("myPreference", Context.MODE_PRIVATE);SharedPreferences.Editor editor = myPreferences.edit();Gson gson = new Gson();String jsonStr = gson.toJson(user);String jsonStr1 = gson.toJson(user1);SetuserSet = new HashSet ();userSet.add(jsonStr);userSet.add(jsonStr1);editor.putStringSet("userIfo", userSet);editor.apply();
读取
private SharedPreferences myPreference;myPreference = getSharedPreferences("myPreference", Context.MODE_PRIVATE);Setset = new HashSet ();Set userSet = myPreference.getStringSet("userIfo",set);if(userSet.size() == 0){ System.out.println("用户未登陆过"); user = new User();}else{ String[] data = (String[]) userSet.toArray(new String[userSet.size()]); for(String uu : data){ Gson gson = new Gson(); user = gson.fromJson(uu, User.class); System.out.println(user.getUserName()); }}