Android 数据存储与访问之——SharedPreferences保存用户偏好参数
2016-12-31 10:26
387 查看
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;}
相关文章推荐
- Android基础入门教程——6.2 数据存储与访问之——SharedPreferences保存用户偏好参数
- Android数据存储和访问--用户登录记住密码
- Android学习 —— 数据的存储与访问方式二: SharedPreferences(偏好参数保存)
- Android--第二天(项目安装启动,电话拨号器,用户通知,短信发送器,数据存储与访问)
- (九)android 中数据存储与访问——保存文件到手机内存
- (十)android 中数据存储与访问——使用SharedPreferences保存数据
- Android--数据存储方式--文件的保存和获取存储用户信息--《便签》
- Android数据存储和访问之SharedPreferences存储方式_用户登录记住密码案例
- Android数据存储和访问——用户登录记住密码
- Android学习 —— 数据的存储与访问方式二: SharedPreferences(偏好参数保存)
- 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)
- android 数据的存储和访问以及单元测试的引入
- 【Android游戏开发十二】(保存游戏数据 [上文])详解SharedPreference 与 FIleInputStream/FileOutputStream将数据存储到SD卡中!
- 【Android游戏开发十三】(保存游戏数据 [下文])详解SQLite存储方式,并把SQLite的数据库文件存储在SD卡中!!!
- android 数据存储和访问方式五:网络详解
- android 数据存储和访问方式一:文件详解
- android数据存储与访问之使用普通文件
- android 数据存储和访问方式四:ContentProvider(内容提供者、数据共享)详解
- Android数据存储与访问
- android数据存储与访问