Transmission of complex parameters between Android intent

Source: Internet
Author: User

In the course Lecture03 _ application framework and key components _ 1, the instructor introduced that Intent is the medium for passing parameters between Activity and Service, the usage and example of using Intent and Bundle to transmit data between components are also provided. These two methods usually implement the transfer of Basic Java object types and strings.

In actual projects, in addition to the above several types of values, there are also requirements for passing Object objects, List types, List <Object> types, and global variables. This article describes how to pass these types of parameters.

 

1. pass List <String> and List <Integer>

The following uses the pass List <String> as an example. The send List <String> syntax is:

Intent. putStringArrayListExtra (key, list );

The syntax for receiving List <String> is:

List = (ArrayList <String>) getIntent (). getStringArrayListExtra (key );

The following is an example:

 


[Java] <span style = "font-size: 16px; "> // ================== send List <String >====================
ArrayList <String> stringList = new ArrayList <String> ();
StringList. add ("string1 ");
StringList. add ("string2 ");
StringList. add ("string3 ");
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, StringListActivity. class );
Intent. putStringArrayListExtra ("ListString", stringList );
StartActivity (intent );
// ================================== Receiving List <String >================== ==========
ArrayList <String> stringList = (ArrayList <String>) getIntent (). getStringArrayListExtra ("ListString ");
</Span>
<Span style = "font-size: 16px; "> // ================== send List <String >====================
ArrayList <String> stringList = new ArrayList <String> ();
StringList. add ("string1 ");
StringList. add ("string2 ");
StringList. add ("string3 ");
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, StringListActivity. class );
Intent. putStringArrayListExtra ("ListString", stringList );
StartActivity (intent );
// ================================== Receiving List <String >================== ==========
ArrayList <String> stringList = (ArrayList <String>) getIntent (). getStringArrayListExtra ("ListString ");
</Span>

 


List <Integer> the following methods can be called for sending and receiving similar operations:

Intent. putIntegerArrayListExtra (key, list );

List = (ArrayList <Integer>) getIntent (). getIntegerArrayListExtra (key );

 

 

 

1. Use Serializable and Parcelable to pass the Object

Android Intent provides two methods to transmit objects between them: Bundle. putSerializable (Key, Object) and Bundle. putParcelable (Key, Object ). Objects in the method must meet certain conditions. The former implements the Serializable interface, while the latter implements the Parcelable interface.

The following is the User class that implements the Serializable interface. The name "SerializableUser" is purely the User class that implements the Parcelable interface according to the class name. We do not recommend this name in actual development:

 


[Java] <span style = "font-size: 16px;"> public class SerializableUser implements Serializable {
Private String userName;
Private String password;
Public SerializableUser (){
}
Public SerializableUser (String userName, String password ){
This. userName = userName;
This. password = password;
}
Public String getUserName (){
Return userName;
}
Public void setUserName (String userName ){
This. userName = userName;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
}
</Span>
<Span style = "font-size: 16px;"> public class SerializableUser implements Serializable {
Private String userName;
Private String password;
Public SerializableUser (){
}
Public SerializableUser (String userName, String password ){
This. userName = userName;
This. password = password;
}
Public String getUserName (){
Return userName;
}
Public void setUserName (String userName ){
This. userName = userName;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
}
</Span>


The following is the User class that implements the Parcelable interface:

 


[Java] <span style = "font-size: 16px;"> public class ParcelableUser implements Parcelable {
Private String userName;
Private String password;
Public ParcelableUser (){
}
Public ParcelableUser (String userName, String password ){
This. userName = userName;
This. password = password;
}
Public String getUserName (){
Return userName;
}
Public void setUserName (String userName ){
This. userName = userName;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
Public static final Parcelable. Creator <ParcelableUser> CREATOR = new Creator <ParcelableUser> (){
@ Override
Public ParcelableUser createFromParcel (Parcel source ){
ParcelableUser parcelableUser = new ParcelableUser ();
ParcelableUser. userName = source. readString ();
ParcelableUser. password = source. readString ();
Return parcelableUser;
}
@ Override
Public ParcelableUser [] newArray (int size ){
Return new ParcelableUser [size];
}
};
@ 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 (password );
}
}
</Span>
<Span style = "font-size: 16px;"> public class ParcelableUser implements Parcelable {
Private String userName;
Private String password;
Public ParcelableUser (){
}
Public ParcelableUser (String userName, String password ){
This. userName = userName;
This. password = password;
}
Public String getUserName (){
Return userName;
}
Public void setUserName (String userName ){
This. userName = userName;
}
Public String getPassword (){
Return password;
}
Public void setPassword (String password ){
This. password = password;
}
Public static final Parcelable. Creator <ParcelableUser> CREATOR = new Creator <ParcelableUser> (){
@ Override
Public ParcelableUser createFromParcel (Parcel source ){
ParcelableUser parcelableUser = new ParcelableUser ();
ParcelableUser. userName = source. readString ();
ParcelableUser. password = source. readString ();
Return parcelableUser;
}
@ Override
Public ParcelableUser [] newArray (int size ){
Return new ParcelableUser [size];
}
};
@ 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 (password );
}
}
</Span>


The syntax passed in two ways is:

Bundle. putSerializable (key, object );

Bundle. putParcelable (key, object );

The syntax for receiving in two ways is:

Object = (Object) getIntent (). getSerializableExtra (key );

Object = (Object) getIntent (). getParcelableExtra (key );

 


[Java] <span style = "font-size: 16px; "> // =============use Serializable and Parcelable to send Object ====================
SerializableUser serializableUser = new SerializableUser ("user1", "123456 ");
ParcelableUser parcelableUser = new ParcelableUser ("user2", "654321 ");
Intent intent = new Intent ();
Bundle bundle = new Bundle ();
Bundle. putSerializable ("serializableUser", serializableUser );
Bundle. putParcelable ("parcelableUser", parcelableUser );
Intent. setClass (ListDemoActivity. this, ObjectActivity. class );
Intent. putExtras (bundle );
StartActivity (intent );
// ================================== Receive Object ====================== ======
SerializableUser serializableUser = (SerializableUser) getIntent (). getSerializableExtra ("serializableUser ");
ParcelableUser parcelableUser = (ParcelableUser) getIntent (). getParcelableExtra ("parcelableUser ");
</Span>
<Span style = "font-size: 16px; "> // =============use Serializable and Parcelable to send Object ====================
SerializableUser serializableUser = new SerializableUser ("user1", "123456 ");
ParcelableUser parcelableUser = new ParcelableUser ("user2", "654321 ");
Intent intent = new Intent ();
Bundle bundle = new Bundle ();
Bundle. putSerializable ("serializableUser", serializableUser );
Bundle. putParcelable ("parcelableUser", parcelableUser );
Intent. setClass (ListDemoActivity. this, ObjectActivity. class );
Intent. putExtras (bundle );
StartActivity (intent );
// ================================== Receive Object ====================== ======
SerializableUser serializableUser = (SerializableUser) getIntent (). getSerializableExtra ("serializableUser ");
ParcelableUser parcelableUser = (ParcelableUser) getIntent (). getParcelableExtra ("parcelableUser ");
</Span>


Some people may note that the implementation of the Serializable interface is to serialize the object and then transmit it. It is no different from the common programming in Java, and the User does not need to be significantly changed, which is relatively simple. I also recommend this method. Www.2cto.com

However, the next class that implements the Parcelable interface is complicated. What is Parcelable?

Android provides a new type: Parcel, which is used as a container to encapsulate data. encapsulated data can be transmitted through Intent or IPC. Except for the basic type, only classes that implement the Parcelable interface can be put into Parcel.

Three methods are required to implement the Parcelable interface:

1) writeToParcel method. This method writes the data of the class to the external provided Parcel.

Declaration: writeToParcel (Parcel dest, int flags ).

2) describeContents method. Return 0 directly.

3) Static Parcelable. Creator <T> interface. This interface has two methods:

CreateFromParcel (Parcel in) is used to create a class instance from in.

NewArray (int size) creates an array of T type and size, returnnew T [size. This method is used for external class deserialization of this class array.

The log Test output shows the program running status in bundle. putParcelable ("parcelableUser", parcelableUser); The publicvoid writeToParcel (Parcel dest, int flags) method in the ParcelableUser class is called, and data is written to the dest, where ParcelableUser) getIntent (). when getParcelableExtra ("parcelableUser"); is used, the public ParcelableUsercreateFromParcel (Parcel source) method in the ParcelableUser class is called, a ParcelableUser object is created, and the attributes of this object are assigned a value, here, the Parcel source and Parcel dest are the same. And return the ParcelableUser object. Finally, you can print the parcelableUser attributes.

 

1. pass List <Object>

What if we want to pass a List composed of objects, that is, List <Object>? First, you need to implement the Serializable interface of the Object, and then convert the list type to the Serializable type forcibly. Finally, you can use:

Intent. putExtra (key, (Serializable) objectList );

When receiving the List, the receiver needs to forcibly convert the type to List <Object>. The syntax used to receive the List <Object> is:

ObjectList = (List <Object>) getIntent (). getSerializableExtra (key );

The following is an application instance. The SerializableUser class used here is provided in the previous step.

 


[Java] <span style = "font-size: 16px; "> // ==================== send List <Object >================
SerializableUser user1 = new SerializableUser ("user1", "123456 ");
SerializableUser user2 = new SerializableUser ("user2", "654321 ");
List <SerializableUser> objectList = new ArrayList <SerializableUser> ();
ObjectList. add (user1 );
ObjectList. add (user2 );
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, ObjectListActivity. class );
Intent. putExtra ("ListObject", (Serializable) objectList );
StartActivity (intent );
// ================================== Receive List <Object >====================== ==========
List <SerializableUser> objectList = (List <SerializableUser>) getIntent (). getSerializableExtra ("ListObject ");
</Span>
<Span style = "font-size: 16px; "> // ==================== send List <Object >================
SerializableUser user1 = new SerializableUser ("user1", "123456 ");
SerializableUser user2 = new SerializableUser ("user2", "654321 ");
List <SerializableUser> objectList = new ArrayList <SerializableUser> ();
ObjectList. add (user1 );
ObjectList. add (user2 );
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, ObjectListActivity. class );
Intent. putExtra ("ListObject", (Serializable) objectList );
StartActivity (intent );
// ================================== Receive List <Object >====================== ==========
List <SerializableUser> objectList = (List <SerializableUser>) getIntent (). getSerializableExtra ("ListObject ");
</Span>

I. Global Variables

If some special application-level parameters are not convenient to use intent to pass parameters, it is easy to think whether global or static variables can be used? Static variables in Java are suitable here, but their values are lost after the Activity calls System. exit (0) or finish.

In android, ApplicationContext is used in a more elegant way. This global variable method is more secure than static classes, and will not be released until all the activities of the application are destory.

In the Android SDK, the Application is used to save global variables and exists when the package is created. Therefore, when we need to create global variables, we do not need to create static variables with public permissions as J2SE, but directly implement them in the application. You only need to call the getApplicationContext of Context or the getApplication method of Activity to obtain an Application object, and then you can set or read the value of the global variable.

When the Application is started, the system creates a PID, that is, the process ID, and all the activities will run on this process. Then we initialize the global variables when the Application is created. All the activities of the same Application can obtain the values of these global variables. In other words, if we change the values of these global variables in an Activity, the values of other activities in the same application will change.

Usage:

1. Create a subclass of your own android. app. Application and add the setter and getter methods to the private global variables you want to share.

 


[Java] <span style = "font-size: 16px;"> public class MyApp extends Application {
Private String globalVariable;
Public String getGlobalVariable (){
Return globalVariable;
}
Public void setGlobalVariable (String globalVariable ){
This. globalVariable = globalVariable;
}
}
</Span>
<Span style = "font-size: 16px;"> public class MyApp extends Application {
Private String globalVariable;
Public String getGlobalVariable (){
Return globalVariable;
}
Public void setGlobalVariable (String globalVariable ){
This. globalVariable = globalVariable;
}
}
</Span>


1. Declare this class in manifest, then Android creates a global available instance for this.

In fact, it is to create a global instance for the application on the only application tag.

 


[Html] <span style = "font-size: 16px;"> <application android: name = ". myApp "android: icon =" @ drawable/icon "android: label =" @ string/app_name "> </span>
<Span style = "font-size: 16px;"> <application android: name = ". myApp "android: icon =" @ drawable/icon "android: label =" @ string/app_name "> </span>

1. You can use the Context. getApplicationContext () method to obtain the instance and its status (variable) anywhere else ).

 


[Java] <span style = "font-size: 16px;">
// ================ Use global variables to PASS Parameters ====================
MyApp myApp = (MyApp) getApplicationContext (); // obtain the MyApp
MyApp. setGlobalVariable ("global variable ");
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, GlobalActivity. class );
StartActivity (intent );
// ================ Parameters for receiving global variables ==================
MyApp myApp = (MyApp) getApplicationContext ());
String globalVariable = myApp. getGlobalVariable ();
</Span>
<Span style = "font-size: 16px; "> // ================ use global variables to PASS Parameters ======================
MyApp myApp = (MyApp) getApplicationContext (); // obtain the MyApp
MyApp. setGlobalVariable ("global variable ");
Intent intent = new Intent ();
Intent. setClass (ListDemoActivity. this, GlobalActivity. class );
StartActivity (intent );
// ================ Parameters for receiving global variables ==================
MyApp myApp = (MyApp) getApplicationContext ());
String globalVariable = myApp. getGlobalVariable ();
</Span>


We hope to provide some help with the introduction of passing Object objects, List types, List <Object> types, and global variables.

 
From Peking University-Google Android lab
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.