Android中的SharedPreference存储(附源码)

SharedPreference存储

1、SharedPreferences

        是一种轻型的数据存储方式。本质是基于XML文件存储的键值对数据。通常用来存储一些简单的配置信息。

提供了一些基础的信息保存功能,所有的信息都是按照“key-value”的形式保存的,所保存的只能是些基本类型。

        sharedPreference对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现的。

        保存文件的步骤:

        1、得到SharedPreferences对象

        2、调用SharedPreferences 对象的edit()方法来获取一个SharedPreferences.Editor 对象, 使SharedPreferences可读写。

        3、向SharedPreferences.Editor 对象中添加数据。

        4、调用commit()方法将添加的数据提交,从而完成数据存储操作。

保存文件:

<span style="font-size:14px;">public class MainActivity extends Activity {
	private static final String NAME="file";
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		//1、获得SharedPreferences对象
		SharedPreferences file=getSharedPreferences(NAME, Activity.MODE_PRIVATE);
		//2、使对象处于可编辑状态
		SharedPreferences.Editor ed=file.edit();
		//3、添加数据
		ed.putString("name", "zh");
		ed.putInt("age",23);
		//4、提交
		ed.commit();
	</span>}
}

读取文件:只需调用一系列的get方法即可。

<span style="font-size:14px;">public class MainActivity extends Activity {
	private static final String NAME="file";
	private TextView text1,text2;
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		text1=(TextView) findViewById(R.id.text1);
		text2=(TextView) findViewById(R.id.text2);		
		//找到.xml文件
		SharedPreferences getShared=getSharedPreferences("file",Activity.MODE_PRIVATE);
		//使用get方法得到数据
		String name=getShared.getString("name","没找到数据");
		Integer age=getShared.getInt("age", 0);
		String ages=age.toString();
		text1.setText(name);
		text2.setText(ages);
	}
}</span>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值