How to pass data between Activity jumps in Android Studio

You can use Intent operations to complete the jump between two activities. Sometimes it is also necessary to transfer data between the two jump activities. This article will introduce in detail some basic activity transfers in Android development. data methods

Call the PutExtra() method

Since there are many different types of data transfer between Activities, multiple overloaded putExtra() methods are provided in the Inten class.

The specific usage is as follows:

Store the passed data in the Intent through the putExtra() method

//创建一个意图并构造跳转对象
Intent intent=new Intent(this,SecondActivity.class);
//调用putExtra()方法
intent.putExtra("name","李华");//姓名
intent.putExtra("age",18);//性别
//启动SecondActivity活动
startActivity(intent);

 Get the passed data through the getXxxExtra() method

//获取意图对象
Intent intent=getIntent();
//获取姓名
String name=intent.getStringExtra("name");
//获取年龄
String name=intent.getIntExtra("age",0);

This completes the first method of data transfer between Activities~ 

Here is an explanation of the third line of code (skip it~):

//获取年龄
String name=intent.getIntExtra("age",0);

The second parameter is set to 0, why? Here you can take a look at the parameter definition of the getIntExtra() method

getIntExtra(String name,int defaultValue){
        //
}

The first parameter is the key value, and the second parameter represents the default value, indicating that the value of age will be assigned only when no value of age is passed in putExtra().

Use Bundle class to pass data

Similar to the map interface, data is saved in the form of key-value pairs.

Examples are as follows:

//创建一个意图
Intent intent=new Intent();

//设置要跳转的Activity
intent.setClass(this,SecondActivity.class);

//创建一个Bundle对象
Bundle bundle=new Bundle();

//调用Bundle类中的putString()方法封装信息
bundle.putString("name","李华");//将姓名信息封装到Bundle中
bundle.putString("age","18");//将年龄信息封装到Bundle中

//将Bundle对象封装到Intent对象中
intent.putExtras(bundle);

//启动Avtivity活动
startActivity(intent);

The code to obtain data in SecondActivity is as follows

//获取Bundle对象
Bundle bundle=getIntent().getExtras();

//获取数据
String name=bundle.getString("name");
String age=bundle.getString("age");//注意此时age的类型不是int型,需要自行转换

This completes the second method of data transfer between two Activity jumps~

If you find it useful, please leave a like and leave~

Guess you like

Origin blog.csdn.net/Lic_Ac/article/details/127254373