[Android notes] Use Intent to pass parameters between multiple Activities

 

1. Transfer data to the next activity

Earlier, when we introduced Intent, we said that we can use Intent to transfer data between different components. The next article is to record how to use Intent to transfer simple data between different activities, transfer data packets, transfer value objects, and Return data to the knowledge of the previous activity.

1. Pass simple data

The main method:
putExtra(String name,String value);
putExtra(String name,int value);
(putExtra() has multiple overloaded methods, which are not listed here) The
first parameter is the key (namely the name of the data to be passed); the
second parameter is the data to be passed (you can use String Type, int type, double type, etc.).
getIntent();
③The getStringExtra(String name);
getInExtra(String name);
parameter is the previous key, which is the name of the data to be passed.

Idea
① Use a series of putExtra() methods (various overload methods) provided by Intent to temporarily store the data to be transferred in the Intent.
In MainActivity,

        case R.id.button1:
             intent = new Intent(MainActivity.this,Aty1.class);
             intent.putExtra("data_aty1","这是从MainActivity传入Aty1的数据:"+data);
             startActivity(intent);
             break;

②In the next activity, use the getStringExtra() method provided by Intent to take out the passed data.
In the onCreate() method of Aty1:

        tv_aty1 = (TextView)findViewById(R.id.textView_aty1);
        Intent intent = getIntent();
        String tempData = intent.getStringExtra("data_aty1");
        tv_aty1.setText(tempData);

Effect picture:
 

2. Deliver data packets

Main methods:
①The Bundle();method of storing data packets in the method:
putString(String name,String value); //存储字符串在Bundle包中
putInt(String name,int value); //存储整型数据在Bundle包中
etc. (float type, double type, etc. are also available, not listed one by one)
②The putExtras(Bundle extras);
parameter extras is the instance of the data packet Bundle
or the
putExtra(String name,Bundle value);
name is the name of the data packet, which is convenient Pass it to other activities and take it out;
value is an instance of the data packet Bundle.
③getIntent ();
④Intent there is provided:
getExtras();a method
getBundleExtra(String name);method
name is the name of the kind of data packet ②.
⑤ Take out the specific attributes in the data packet:
getString(String name);
getInt(String name);etc.

Ideas:
①Integrate a series of data (including string, integer, boolean, etc.) in the Bundle package (using putString(), putInt(), etc.), use putExtras() or putExtra() in Intent Methods are passed to other activities.
In MainActivity,

           case R.id.button2:
                intent = new Intent(MainActivity.this,Aty2.class);
                Bundle bundle = new Bundle();
                bundle.putString("name",data);
                bundle.putInt("age",18);
                intent.putExtras(bundle);
                startActivity(intent);
                break;

②In the next activity, use the getExtras() or getBundleExtra() method to pass the Bundle package, and then use the getString() method in the Bundle to fetch the data.
In the onCreate() method of Aty2:

        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        et_aty2.setText(String.format("姓名:%s     年龄:%d",bundle.getString("name"),bundle.getInt("age") ));

Effect picture:
 

If sex does not exist in the Bundle package, it can be written as

        et_aty2.setText(String.format("姓名:%s     年龄:%d    性别:%s",bundle.getString("name"),bundle.getInt("age"),bundle.getString("sex","女") ));

Effect picture:
Write picture description here

If sex exists in the Bundle and assigned the value "male", bundle.getString("sex","女") ));what will happen if the data is still written as "male" ? You can try it out.

3. Pass value object

Value object: custom object with data type.
There are two serialized object interfaces that can be used to transfer value objects:
java.io.Serializable
②Next android.os.Parcelable
, we will introduce how these two interfaces transfer value objects.

(1) Serializable serialization interface

This is the built-in interface of the Java language for serializing objects. You only need to implement Serializable, and the rest of the system will automatically handle it, so the efficiency will be relatively low.
①Create a new java class—— User.java( implrments Serialiable)

import java.io.Serializable;

public class User implements Serializable{

    private String name;
    private int age;

    //两个参数的构造方法
    public User(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName(){
        return name;
    }

    public int getInt(){
        return age;
    }
}

② Use the putExtra()method to save the data in User in MainActivity

           case R.id.button3:
                intent = new Intent(MainActivity.this,Aty3.class);
                User user = new User(data,19);
                intent.putExtra("user",user);
                startActivity(intent);
                break;

③Use the getSerialiableExtra()method to fetch the data in Aty3

        Intent intent = getIntent();
        User user = (User)intent.getSerializableExtra("user");
        tv_aty3.setText(String.format("名字:%s     年龄:%d",user.getName(),user.getInt()));

Effect picture:
 

(2) Parcelable serialization interface

This is an interface provided by the Android platform for serializing objects. Using this interface requires rewriting a series of data-related methods, so the efficiency is higher than the Serialiable interface.
①Create a new java class—— User2.java( implrments Parcelable)

import android.os.Parcel;
import android.os.Parcelable;

public class User2 implements Parcelable {

    private String name;
    private int age;

    //两个参数的构造方法
    public User2(String name,int age){
        this.name = name;
        this.age = age;
    }

    public String getName(){
        return name;
    }

    public int getAge(){
        return age;
    }
}

②If you just write in this way, the system will report an error.
Write picture description here
③So we have to rewrite some methods. At this time, the system will give a reminder:
Write picture description here
Therefore, we need to rewrite the describeContents()method and writeToParcel()method
a). describeContents()This method only needs to be rewritten, don't worry about it for the time being.

@Override
    public int describeContents() {
        return 0;
    }

b). writeToParcel()We need to write data to the target Parcel in this method, because the Parcelable interface does not have a fully automatic serialization mechanism, so we need to write it manually.

@Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(getName());
        parcel.writeInt(getAge());
    }

④ In addition, we also need to rewrite the following methods to read data.

public static final Creator<User2> CREATOR = new Creator<User2>() {
        @Override
        public User2 createFromParcel(Parcel in) {
            return new User2(in.readString(),in.readInt());
        }

        @Override
        public User2[] newArray(int size) {
            return new User2[size];
        }
    };

⑤ Finally, we call the getParcelableExtra()method in Aty4 to receive the data.

Intent intent = getIntent();
        User2 user2 = intent.getParcelableExtra("user2");
        tv_aty4.setText(String.format("姓名:%s     年龄:%d ",user2.getName(),user2.getAge()));

Effect picture:
 

Note: I didn't understand these two interface methods very profoundly. I just recorded my understanding. If there is an error, you can spray it a little. The most important thing is to point out the incorrect understanding.

2. Return data to the previous activity

Earlier we talked about passing data to the next activity, and then we talked about returning data to the previous activity.
Related methods:
①This startActivityForResult(Intent intent,int requestCode);
method startActivity()is the same as the method, which is also used to start the activity, but this method expects to return a result to the previous activity when the activity is destroyed.
Parameter 1 or Intent;
parameter 2 is the request code, used to determine the source of the data in the subsequent callback.
setResult(int resultCode,Intent data);
This method is specifically used to return data to the previous activity.
Parameter 1 is used to return the processing result to the previous activity. Generally, only the two values ​​of RESULT_OK or RESULT_CANCELED are used;
parameter 2 is to pass back the Intent with data.

① In MainActivity, call the startActivityForResult()method to start Aty5.

                case R.id.button5:
                intent = new Intent(MainActivity.this,Aty5.class);
                startActivityForResult(intent,1);
                break;

②Register a button in Aty5, add logic to return data in the click event and return to the main page.

                Intent intent = new Intent();
                String data = et_aty5.getText().toString();
                intent.putExtra("data_aty5",data);
                setResult(RESULT_OK,intent);
                finish();

startActivityForResult()③Since we use the method to start Aty5, the onActivityResult()method of the previous activity will be called back after Aty5 is destroyed , so we need to rewrite this method in MainActivity to get the return data.

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if(resultCode == RESULT_OK){
                    String str = data.getStringExtra("data_aty5");
                    tv_atymain.setText(str);
                }
                break;
            default:
                break;
        }
    }

Effect picture:
 

We can also rewrite the onBackPressed()method in Aty5 to return the data after pressing the Back key. You can try this yourself

Guess you like

Origin blog.csdn.net/az44yao/article/details/112638273