Android数据存储-SharedPreferences(共享参数)

SharedPreferences 共享参数配置,在当前的上下文中如果要得到SharedPreferences 对象可以调用:
[color=darkblue]getSharedPreferences(String name, int mode)[/color]
[color=darkblue]getPreferences(int mode)[/color]
[color=darkred]这两个方法有何区别呢?[/color]
看参数信息,第一个方法不难理解,分别是:文件名称、文件操作模式。
第二个方法参数只需要传入文件的操作模式,文件的名称默认为当前上下文对象的简单名称(当前方法调用所在类的名称)。

[b]a. 保存共享参数配置信息,示例代码如下:[/b]

SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
// 获取表单中的属性值
String name = edtName.getText().toString();
String age = edtAge.getText().toString();
// 得到共享配置对象保存配置信息
Editor editor = pres.edit();
editor.putString("name", name);
editor.putString("age", age);
// 调用commit方法保存配置信息
editor.commit();

[b]b. 获取共享参数配置信息,示例代码如下:[/b]

SharedPreferences pres = getSharedPreferences("config", Context.MODE_PRIVATE);
edtName.setText(pres.getString("name", null));
edtAge.setText(pres.getString("age", null));

[b]c. 访问其它应用程序中的共享参数配置信息,示例代码如下:[/b]

// 构建其它应用程序的上下文对象,用于取得应用的共享配置信息,第二个参数意思是忽略安全检查
Context context = this.createPackageContext("com.jelly.pres", Context.CONTEXT_IGNORE_SECURITY);
// 得到其它应用程序的共享参数配置对象
SharedPreferences pres = context.getSharedPreferences("config", Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值