Android 数据存储与访问之——SharedPreferences保存用户偏好参数
来源:互联网 发布:批量查询淘宝小号 编辑:程序博客网 时间:2024/05/19 02:39
Android 数据存储与访问之——SharedPreferences保存用户偏好参数
本节介绍的是使用SharedPreferences(保存用户偏好参数)保存数据,当我们的应用想要保存用户的一些偏好参数,比如是否自动登陆,是否记住账号密码,是否在Wifi下才能联网等相关信息,如果使用数据库的话,显得有点大材小用了!我们把上面这些配置信息称为用户的偏好设置,就是用户偏好的设置,而这些配置信息通常是保存在特定的文件中!
1、SharedPreferences使用示例:
工具类:
public class SharedHelper { private Context mContext; public SharedHelper() { } public SharedHelper(Context mContext) { this.mContext = mContext; } //定义一个保存数据的方法 public void save(String username, String passwd) { SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE); SharedPreferences.Editor editor = sp.edit(); editor.putString("username", username); editor.putString("passwd", passwd); editor.commit(); Toast.makeText(mContext, "信息已写入SharedPreference中", Toast.LENGTH_SHORT).show(); } //定义一个读取SP文件的方法 public Map<String, String> read() { Map<String, String> data = new HashMap<String, String>(); SharedPreferences sp = mContext.getSharedPreferences("mysp", Context.MODE_PRIVATE); data.put("username", sp.getString("username", "")); data.put("passwd", sp.getString("passwd", "")); return data; }}
2.读取其他应用的SharedPreferences
获得其他app的Context,而这个Context代表访问该app的全局信息的接口,而决定应用的唯一标识是应用的包名,所以我们可以通过应用包名获得对应app的Context另外有一点要注意的是:其他应用的SP文件是否能被读写的前提就是SP文件是否指定了可读或者可写的权限,我们上面创建的是MODE_PRIVATE的就不可以了
public Map<String, String> read() {Context othercontext ;try { othercontext = createPackageContext("com.jay.sharedpreferencedemo", Context.CONTEXT_IGNORE_SECURITY); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } //根据Context取得对应的SharedPreferences sp = othercontext.getSharedPreferences("mysp", Context.MODE_WORLD_READABLE);Map<String, String> data = new HashMap<String, String>();data.put("username", sp.getString("username", "")); data.put("passwd", sp.getString("passwd", "")); return data;}
0 0
- Android 数据存储与访问之——SharedPreferences保存用户偏好参数
- Android基础入门教程——6.2 数据存储与访问之——SharedPreferences保存用户偏好参数
- 数据存储与访问之SharedPreferences(偏好参数保存)
- Android学习 —— 数据的存储与访问方式二: SharedPreferences(偏好参数保存)
- SharedPreferences(保存用户偏好参数)保存数据
- 数据类操作之SharedPreferences(保存用户偏好参数)
- 数据类操作之SharedPreferences(保存用户偏好参数)
- Android数据存储方式(二)SharedPreferences(偏好参数保存)
- Android数据存储方式(二)SharedPreferences(偏好参数保存)
- Android数据存储方式(二)SharedPreferences(偏好参数保存)
- Android文件存储--采用SharedPreferences保存用户偏好设置参数和读取设置参数
- Android文件存储--采用SharedPreferences保存用户偏好设置
- Android采用SharedPreferences保存用户偏好设置参数
- Android采用SharedPreferences保存用户偏好设置参数
- Android开发入门之采用SharedPreferences保存用户偏好设置参数
- SharedPreferences(保存用户偏好参数)
- 采用SharedPreferences保存用户偏好设置参数
- 采用SharedPreferences保存用户偏好设置参数
- 如何调试Windows的stackdump文件
- 机器学习中的相似性度量 (多种几何距离定义)
- P1307 数字反转 luogu
- SSM框架(二)--Spring、SpringMVC和MyBatis整合(详细教程)
- 【动态规划·经典例题】滑雪
- Android 数据存储与访问之——SharedPreferences保存用户偏好参数
- OpenCV2.0.0移植到ARM9(五)(JZ2440----S3c2440)
- PAT-甲级-1003
- 树莓派3B开启串口输出
- Spark2.1.0的Standalone模式部署
- DP动态规划
- redis 数据备份、数据恢复、安全
- javaweb常用监听器
- Web基础学习笔记——html基础