【android-tips】Activity间数据传递之Bundle和SharedPreferences

(转载请注明出处:http://blog.csdn.net/buptgshengod 

1.介绍

    对于初学者android不同activity间的数据传输一直是一个难题,主要的解决方法主要有两种一种是用Bundle传输数据,一种是用SharedPreferences。两者的区别,一般来讲SharedPreferences用来存储轻型数据,保存在xml里,可以持久保存。反观Bundle可以传输很多中数据,但是不持久。

2.具体实现方法

  Bundle

    在发送方class A
 Bundle bundle = new Bundle();

  //保存输入的信息
    bundle.putString("string名", "传输的string");
    Intent intent=new Intent(A.this,B.class);
   intent.putExtras(bundle);
   在接收方class B
Bundle b=getIntent().getExtras();
  //获取Bundle的信息
  String info=b.getString("string名");

注意:string名要一样

 SharedPreferences

 

  SharedPreferences 用法很简单,如果你想要编辑SharedPreferences中的内容就需要用到editor对象。

 在发出方A中

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());	
					    Editor editor = sp.edit();
					    editor.putString("string变量名","发出的string内容");
					    editor.commit();

接收方B

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(B.this);
			string grade = sp.getString("string变量名",“默认值”);



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值