Several ways for Intent to pass values between Activities

This blog mainly talks about several methods of how to pass values ​​in Intent in Android:

1: Basic data types, including eight basic Java data types and CharSequece text
2: New corresponding arrays of eight data types and CharSequece text arrays

3: Bundle pass value

4: ArrayList collection 

5: Serializable pass object

6: Parcelable pass object

Add six Button controls in the main.xml layout file, which are six ways of passing values.

The Activity code is as follows:

package com.example.transmittingdata;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

/***
 *
 * Intent pass value contains
 * 1: Basic data types, including eight basic data types in Java and CharSequence text
 * 2: New corresponding arrays for eight data classes and CharSequence text arrays
 * 3:Bundle
 *4: ArrayList collection 5: Serializable pass object
 * 6: Parcelable pass object
 *
 * @author zq
 *
 */
public class MainActivity extends Activity implements OnClickListener {

	private String[] str = new String[] { "Eight new corresponding arrays of data classes and CharSequence text array", "123" };
	private ArrayList<String> list;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate (savedInstanceState);
		setContentView(R.layout.main);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		findViewById(R.id.button1).setOnClickListener(this);
		findViewById(R.id.button2).setOnClickListener(this);
		findViewById(R.id.button3).setOnClickListener(this);
		findViewById(R.id.button4).setOnClickListener(this);
		findViewById(R.id.button5).setOnClickListener(this);
		findViewById(R.id.button6).setOnClickListener(this);
		list = new ArrayList<String>();
		list.add("List集合");
		list.add("Value");

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		Intent intent = new Intent(MainActivity.this, IntentData.class);
		switch (v.getId()) {
		case R.id.button1:
			intent.putExtra("i", 1);
			intent.putExtra("key", "Basic data types, including eight basic Java data types and CharSequence text");
			break;
		case R.id.button2:
			intent.putExtra("i", 2);
			intent.putExtra("key", str);
			break;
		case R.id.button3:
			Bundle bundle = new Bundle();
			bundle.putString("key", "Bundle传值");
			intent.putExtra("i", 3);
			intent.putExtra("bundle", bundle);
			break;
		case R.id.button4:
			intent.putExtra("i", 4);
			intent.putStringArrayListExtra("key", list);
			break;
		case R.id.button5:
			UserInfo user = new UserInfo();
			user.setSex("男");
			user.setUserName("Bai Zihua");
			intent.putExtra("i", 5);
			intent.putExtra("key", user);
			break;

		case R.id.button6:
			intent.putExtra("i", 6);
			UserBean userBean = new UserBean();
			userBean.setSex("女");
			userBean.setUserName("Hua Qiangu");
			intent.putExtra("key", userBean);
			break;

		default:
			break;
		}
		startActivity(intent);
	}

}

 The Activity class that receives the value:

 

public class IntentData extends Activity{

	private TextView text1, text2;
	private int position = 1;
	private String data = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate (savedInstanceState);
		setContentView(R.layout.data);
		initView();
		initData ();

	}

	@SuppressLint("NewApi")
	private void initData() {
		// TODO Auto-generated method stub
		if (getIntent() != null) {
			position = getIntent().getIntExtra("i", 1);
			if (position == 1) {
				data = getIntent().getStringExtra("key");
				text1.setText("Basic data type");
				text2.setText(data);
				return;
			}
			if (position == 2) {
				String[] data1 = getIntent().getStringArrayExtra("key");
				text1.setText("array");
				text2.setText(data1[0] + "----" + data1[1]);
				return;
			}
			if (position == 3) {
				Bundle bundle = getIntent().getBundleExtra("bundle");
				text1.setText("Bundle");
				text2.setText(bundle.getString("key", "default is empty value"));
				return;
			}
			if (position == 4) {
				ArrayList<String> array;
				text1.setText("List<object> 集合");
				array = getIntent().getStringArrayListExtra("key");
				text2.setText(array.get(0));
				return;
			}
			if (position == 5) {
				UserInfo user;
				text1.setText("Serializable transfer object");
				user = (UserInfo) getIntent().getSerializableExtra("key");
				text2.setText(user.getUserName() + "---" + user.getSex());
				return;
			}
			if (position == 6) {
				UserBean userBean;
				text1.setText("Parcelable pass object");
				userBean = (UserBean) getIntent().getParcelableExtra("key");
				text2.setText(userBean.getUserName() + "---"
						+ userBean.getSex());
				return;
			}

		}
	}

	private void initView() {
		// TODO Auto-generated method stub
		text1 = (TextView) findViewById(R.id.textView1);
		text2 = (TextView) findViewById(R.id.textView2);

	}

}
 

 

Serializable passing object

Serializable : It means serialization, which means converting an object into a storable or transferable state. After the object is Serializable, it can be transferred between activities through Intent.

public class UserInfo implements Serializable{
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private String sex;
	private String userName;
	
	publicUserInfo(){
		// TODO Auto-generated constructor stub
	}
	
	public String getSex(){
		return sex;
	}
	publicvoidsetSex(String sex){
		this.sex = sex;
	}
	public String getUserName(){
		return userName;
	}
	publicvoidsetUserName(String userName){
		this.userName = userName;
	}


}

 

The serialVersionUID here needs attention. Its function is to maintain version compatibility during serialization and deserialization. If you do not specify it, it will also be generated by default at runtime. When deserializing, only the serialVersionUID of the data and the current class is performed. The same is to be able to deserialize normally. If you don't specify serialVersionUID, there will be no problem in general, but if the current class changes, such as deleting a member variable, the serialVersionUID of the current class will also change, and then you An error will occur when the data is deserialized, here I specify 1L, and L is the Long data type.

 

Parcelable pass object

The serialization principle of Parcelable is to decompose an object, and each part after decomposing is a data type supported by Intent, so it realizes the function of passing objects.

public class UserBean implements Parcelable {

	private String sex;
	private String userName;

	public UserBean() {
		// TODO Auto-generated constructor stub
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub

		dest.writeString(userName);
		dest.writeString(sex);
	}

	protected UserBean(Parcel in) {
		userName = in.readString();
		sex = in.readString();
	}

	public static final Creator<UserBean> CREATOR = new Creator<UserBean>() {

		@Override
		public UserBean createFromParcel(Parcel in) {
			return new UserBean(in);
		}

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

	};

}

 

It can be seen that the implementation of Parcelable is much more complicated. After implementing the Parcelable interface, you need to rewrite the writeToParcel and describeContents methods. The describeContents method can directly return 0. In the writeToParcel method, we need to call the Parcel object to write data, such as dest .writeString(name), note that if name is a string type, writeString is called, if it is an Int type, writeInt is called and so on.

 

Source code click to download

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326264591&siteId=291194637