Android Development - send data between activities

Posted by stunna671 on Wed, 19 Feb 2020 05:17:20 +0100

Preface

In the process of Activity interaction, data must be transferred between two activities. You can start a new Activity by using the startActivity() or startActivityForResult() method, depending on whether your Activity wants to get the return result from the new Activity that is about to start. Both methods need to pass in an Intent object.
The Intent object specifies the Activity you want to start, or describes the type of operation you want to perform (the system selects the corresponding Activity for you, which can even come from different applications). The Intent object can also carry a small amount of data used by the started Activity.
So there are three situations in the process of Activity interaction:

  • A starts B, does not need to transfer data, and directly jumps from a to B;
  • When A starts B, it needs to transfer data, jump from A with data to B, and receive data from B;
  • A starts B, optional to transfer data, jumps from a (with or without data) to B, receives data from B, and returns data from B to a;
    Next, according to the three situations I have worked out here, I will talk about them briefly and implement them in Code:

1 jump directly to B

In fact, this situation has been implemented before, that is, calling the startActivity() method directly to start it.
It is to create another Activity and corresponding xml file, and then register the Activity in the Mainfest configuration file. Then add a button in the xml file of the main Activity, and add a jump event for this button. The code of this button is shown below:

btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
	    Intent intent = new Intent();
	    intent.setClass(MainActivity.this, OtherActivity.class);
	    MainActivity.this.startActivity(intent);
	}
});

2 jump and transfer data to B

When an application creates an intent object to be used in startActivity(android.content.Intent) to start a new Activity, the application can use the putExtra(java.lang.String, java.lang.String) method to pass in parameters.
It's not hard to find that putExtra passes strings in the form of key value. That is, the simple type. If we need to transfer complex types, such as an object or a data list, how should we implement it?
As you may soon think, it is implemented with JSON, that is, putExtra is not to pass strings, directly change objects into JSON strings, and then parse them after getting them, which is OK indeed.
However, this is not what we need here. The original words in the official documents are as follows:

We recommend that you use the Bundle class to set the primitives known to the operating system for the Intent object.
In some cases, you may need a mechanism to send composite or complex objects across activities. In this case, the custom class should implement Parcelable and provide the corresponding writeToParcel(android.os.Parcel, int) method. It must also provide a non empty field CREATOR that implements the Parcelable.Creator interface, whose createFromParcel() method is used to turn parcel back to the current object.

In other words, we need to use Bundle to encapsulate data and create Intent objects. In Bundle, we provide such a method:

// Inserts the Parcelable value into the mapping for this Bundle, replacing any existing values for the given key.
putParcelable(String key, Parcelable value)

After checking on the Internet, in Bundle, you can also use the serialization method to pass objects:

// Inserts a serializable value into the mapping for this Bundle, replacing any existing value for the given key.
putSerializable(String key, Serializable value)

There are four ways to transfer data:

  • Directly use the putExtra(java.lang.String, java.lang.String) method of intent;
  • Copy the toString() method of the object to be passed and splice it into JSON string, and then directly use the putExtra(java.lang.String, java.lang.String) method of intent;
  • The intention object intent is constructed by using Bundle, in which putParcelable(String key, Parcelable value) method is used to encapsulate an object that implements the Parcelable interface.
  • The intention object intent is constructed by using Bundle, in which putSerializable(String key, Serializable value) method is used to encapsulate an object that implements the Serializable interface.

Let's implement them respectively:

2.1 passing simple strings using putExtra

Or two activities. The main Activity is a button, and the receiving Activity is a text component. As before, write the corresponding xml file and register to receive the Activity information in the configuration file.
First, add a listening event for the button in the main Activity:

btn = (Button)findViewById(R.id.btn);
 btn.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
		   Intent intent = new Intent();
		   intent.putExtra("name", "Boundless bright moon");
		   intent.setClass(MainActivity.this, OtherActivity.class);
	    MainActivity.this.startActivity(intent);
	}
});

Then, I process and receive data in the receive Activity. My code here is implemented as follows:
Written in onCreate() cycle function in Activity to be received

setContentView(R.layout.activity_other);
// Receive data start     
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
TextView textView = (TextView)findViewById(R.id.textview);
textView.setText(bundle.getString("name"));

Effect:

2.2 passing JSON strings using putExtra

The routine is the same as the previous one, but there is more processing here. First, create a new student class, then add a construction method, and copy the toString() method. I have defined three fields here. Its toString() method is as follows:

@Override
public String toString() {
	return "{'name':'"+ this.name +"','sex':'"+ this.sex +"','age':" + Integer.toString(age)+"}";
}

Then pass the JSON string in the main Activity:

btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
	    Intent intent = new Intent();
	    student student = new student("Boundless bright moon", "male", 18);
	    intent.putExtra("obj", student.toString());
	    intent.setClass(MainActivity.this, OtherActivity.class);
	    MainActivity.this.startActivity(intent);
	}
});

Finally, whether to process the string in the Activity of the data to be received or in the onCreate method:

setContentView(R.layout.activity_other);
// Start receiving and processing data
Intent intent = this.getIntent();
Bundle bundle = intent.getExtras();
String str = bundle.getString("obj");
JSONObject jsonobj = null;
try {
	jsonobj = new JSONObject(str);
	TextView textView = (TextView)findViewById(R.id.textview);
    textView.setText("Full name:" + jsonobj.getString("name") + ",Gender:" + jsonobj.getString("sex") + ",Age:" + Integer.toString(jsonobj.getInt("age")));
} catch (JSONException e) {
	e.printStackTrace();
}

Final effect:

As for the parsing of JSON strings, I refer to: java backend parsing json data , you can have a look if you are interested.

2.3 using putParcelable to pass objects

If you want to use Parcelable to transfer data, the official website says:
Send composite or complex objects across activities. In this case, the custom class should implement Parcelable and provide the corresponding writeToParcel(android.os.Parcel, int) method. It must also provide a non empty field CREATOR that implements the Parcelable.Creator interface, whose createFromParcel() method is used to turn parcel back to the current object.
It is not hard to find that one is to write the Parcel to the positive object, and the other is to create the object from the Parcel object, that is, write it back.
If you don't know about the Parcelable interface, take a look Official note . There is also a classic case:

 public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }

It's easy to understand what it's doing. Let's simulate a student class here:

package com.example.fi;

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


public class student implements Parcelable{
	private String name;
	private String sex;
	private int age;

	
	public student(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}
	
	@Override
	public String toString() {
		return "Name of resolution result:"+this.name+",Gender:"+this.sex+",Age:"+Integer.toString(this.age)+". ";
	}

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


	@Override
	public void writeToParcel(Parcel out, int flags) {
		out.writeString(this.name);
		out.writeString(this.sex);
		out.writeInt(this.age);
	}
	
	public static final Parcelable.Creator<student> CREATOR = new Parcelable.Creator<student>(){

		@Override
		public student createFromParcel(Parcel source) {
			return new student(source.readString(), source.readString(), source.readInt());
		}

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

In the main Activity, we transfer data:

btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View v) {
	    Intent intent = new Intent();
//			    In Bundle mode, Pracelable can also be placed in the putExtra of intent
//			    Bundle bundle = new Bundle();
//			    student student = new student("boundless moon", "male", 18);
//			    bundle.putParcelable("parce", student);
//			    intent.putExtras(bundle);
    student student = new student("Boundless bright moon", "male", 18);
    intent.putExtra("parce", student);
	    intent.setClass(MainActivity.this, OtherActivity.class);
	    MainActivity.this.startActivity(intent);
	}
});

There are two ways to transfer data, one is to use Bundle, the other is to directly pueExtra. Receiving data is the same. In the Activity to receive data, the code to receive data is in the onCreate cycle function. The code is as follows:

setContentView(R.layout.activity_other);

Intent intent = this.getIntent();
student student = intent.getParcelableExtra("parce");
TextView textView = (TextView)findViewById(R.id.textview);
textView.setText(student.toString());

Effect:

I think it's a bit long. I haven't finished here. I'll continue to write the next chapter.

Reference documents:
[1] Android master advanced tutorial (17) - two methods of Intent passing objects in Android (Serializable,Parcelable)!
[2] Official Android development documents - Parcelable and Bundle
[3] Official Android development document - start an Activity from another Activity
[4] java backend parsing json data

Author: Boundless bright moon

Sincerely hope this article can help you! If you think this article is helpful to you, you may as well scan the QR code below and add my wechat, and then send a red packet for a reward. Your support is my great motivation. I sincerely wish you all success in your study! Let's cheer together!!!

180 original articles published, 140 praised, 90000 visitors+
Private letter follow

Topics: Android Java JSON xml