SharedPreferences共享参数类

一、作用

    主要用于存放软件的配置参数等信息。sharedPreferences用于存取和修改软件配置参数数据的接口,由getSharedPreferences(String, int)函数返回。任何具体的参数,都有一个单独的该类实例向所有客户端共享。修改参数必须通过SharedPreferences.Editor 对象,以确保这些参数在被提交到外存的时候它们的值处于一致的状态和控制之下。该类暂不支持多进程操作,但是以后将提供该功能。

原文:

Interface for accessing and modifying preference data returned by getSharedPreferences(String, int). For any particular set of preferences, there is a single instance of this class that all clients share. Modifications to the preferences must go through an SharedPreferences.Editor object to ensure the preference values remain in a consistent state and control when they are committed to storage.

Note: currently this class does not support use across multiple processes. This will be added later.

 

二、SharedPreferences.Editor 类简介

public abstract SharedPreferences.Editor edit ()

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

Note that you must call commit() to have any changes you perform in the Editor actually show up in the SharedPreferences.

 

三、存放参数实例源码:

            @Override
public void onClick(View v)
{
String name = nameText.getText().toString();
String age = ageText.getText().toString();
SharedPreferences preferences = getSharedPreferences("itcast",
Context.MODE_WORLD_READABLE);
Editor editor = preferences.edit();
editor.putString("name", name);
editor.putInt("age", new Integer(age));
editor.commit();
Toast.makeText(MainActivity.this, R.string.success, 1).show();
}

四、读取参数实例源码:

            @Override
public void onClick(View v)
{
SharedPreferences preferences = getSharedPreferences("itcast", Context.MODE_PRIVATE);
String name = preferences.getString("name", "");
int age = preferences.getInt("age", 20);
nameText.setText(name);
ageText.setText(String.valueOf(age));
}

五、归纳

通过以上类的介绍和实例源码分析,可以总结出一般步骤:

存放:

1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;

2.获得Editor 的实例对象,通过SharedPreferences 的实例对象的edit()方法;

3.存入数据,利用Editor 对象的putXXX()方法;

4.提交修改的数据,利用Editor 对象的commit()方法。

 

读取:

1.获得SharedPreferences 的实例对象,通过getSharedPreferences()传递文件名和模式;

2.读取数据,通过SharedPreferences 的实例对象的getXXX()方法。

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值