使用putExtra()方法传递数据
我们在从一个Activity向另一个Activity传递数据时,经常引用putExtra()方法将数据存储到Intent对象中,当数据量比较大的时候,一般是先将所要传输的数据封装到Bundle对象中,然后再使用putExtra()方法进行传输数据。putExtra()方法是采用键值对的方式传递所需要的数据的,并且我们还得注意两点:一、所用的键必须指定为String类型,值可以是具体的数据类型,二、在Intent之间传值的对象必须是可序列化的。
下面我们看一个实例:
Intent intent = new Intent(this,SignInActivity.class);
intent.putExtra(“Hai”,”你好”);
intent.putExtra(“value”,1314);
stratActivity(intent);
上面我们已经了解putExtra()方法的数据传输,下面我们来了解数据的接收。
geXXtExtra()方法接收数据,XX表示传输的数据类型,例如:当传输的数据是String类型的,就用getStringExtra()方法,
下面我们先看一个实例:
Intent intent = getIntent();//获取意图对象
int myInt=Intent.getIntExtra("myInt",9);//第一个参数是键key,第二个参数是键key的具体数值
float f=Intent.getFloatExtra("myFloat",1.0f);
使用Bundle对象封装数据进行传输数据
当我们传输的数据量比较大的时候,可以将数据封装打包到Bundle对象中。Bundle类是一个Android中的容器,它跟java中的Map<String,Obect>相似,以一个键值对类型存储数据,但它的键只能是String类型,而value则没有数据类型限制。
在Bundle对象被创建后,调用putxx()方法以键值对的方式存储数据(xx表示具体的数据类型),然后调用Intent对象的putExtras()方法存储Bundle对象。
Intent intent =new Intent(this,signInActivity.class);
Bundle bundle =new Bundle();
bundle.putString("str","字符串");
bundle.putInt("Value",1314);
intent.putExtras(bundle);
startActivity(intent);
获取Bundle传输的数据
用getIntent()方法获取Intent对象,调用getExtras()方法获取传值的Bundle对象,再使用Bundle中的getxx()方法(xx是数据类型),根据键值获取具体的数据。
(注意:通过Intent传值过来的Bundle对象,我们在获取传值的时候也是获取Bundle对象,如:Bundle bundle =intent.getExtras();中可以看出在Intent获取的传值为Bundle)
下面我们看一个实例:
Intent intent =getIntent();//获取Intent对象
Bundle bundle =intent.getExtras();//在Intent中获取的是Bundle对象
String s=bundle.getString("str");
int i=bundle.getInt("mInt");