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. transfer list <string> and list <integer>. The following uses the transfer 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] view plaincopy <span style = "font-size: 16px; "> // ================== send list <string >================== arraylist <string> stringlist = new arraylist <string> (); stringlist. add ("string1"); stringlist. add (" String2 "); stringlist. add ("string3"); 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> similar The preceding operations call the following method to send and receive messages: intent. putintegerarraylistextra (Key, list); List = (arraylist <integer>) getintent (). getintegerarraylistextra (key); 2. Use serializable and parcelable to transmit objects between intent of objectandroid. One is bundle. putserializable (Key, object); 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] view plaincopy <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 St Ring 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] view plaincopy <span style = "font-size: 16px; "> public class parcelableuser implements parcelable {private string username; privat E 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;} p Ublic static final parcelable. creator <parcelableuser> creator = new creator <parcelableuser> () {@ override public parcelableuser createfromparcel (parcel source) {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> use the following two methods to pass the Syntax: bundle. putserializable (Key, object); bundle. putparcelable (Key, object); the syntax for receiving in two ways is: Object = (object) Geti Ntent (). getserializableextra (key); object = (object) getintent (). getparcelableextra (key); [Java] view plaincopy <span style = "font-size: 16px; "> // =============use serializable and parcelable to send object ========================= serializableuser = new serializableuser ("user1 ", "123456"); parcelableuser = new parcelableuser ("user2", "654321"); intent = new intent (); bundle = new Bu Ndle (); bundle. putserializable ("serializableuser", serializableuser); bundle. putparcelable ("parcelableuser", parcelableuser); intent. setclass (listdemoactivity. this, objectactivity. class); intent. putextras (bundle); startactivity (intent ); // ================================== receive object ====================== ===== serializableuser = (serializableuser) getintent (). getserializableextra ("serializableuser"); P Arcelableuser parcelableuser = (parcelableuser) getintent (). getparcelableextra ("parcelableuser"); </span> some people may note that implementing the serializable interface is to serialize the object and then transmit it. It is no different from common Java programming, in addition, the user does not need to be significantly changed, which is relatively simple. I also recommend this method. 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) 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. 3. pass list <Object> what if we want to pass a list consisting of objects, that is, list <Object>? First, you need to implement the serializable interface of the object, then convert the list type to the serializable type forcibly, and finally use: intent. putextra (Key, (serializable) objectlist); this syntax is passed, and the receiver needs to forcibly convert the type to list <Object> During receiving, the syntax used to receive 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] view plaincopy <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 = new intent (); intent. setclass (listdemoacti Invalid. this, objectlistactivity. class); intent. putextra ("listobject", (serializable) objectlist); startactivity (intent ); // ================================== receive list <object >====================== ========== list <serializableuser> objectlist = (list <serializableuser>) getintent (). getserializableextra ("listobject"); </span> 4. If global variables have special application-level parameters, intent is not convenient 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] view plaincopy <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> 2. 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] view plaincopy <span style = "font-size: 16px;"> <application Android: Name = ". myApp "Android: icon =" @ drawable/icon "Android: Label =" @ string/app_name "> </span> 3. context can be used anywhere else. the getapplicationcontext () method obtains the instance and the status (variable ). [Java] view plaincopy <span style = "font-size: 16px; "> // =============== use global variables to PASS Parameters ======================= MyApp = (( myApp) getapplicationcontext (); // obtain MyApp. setglobalvariable ("global variable"); intent = new intent (); intent. setclass (listdemoactivity. this, globalactivity. class); startactivity (intent ); // ================ parameters for receiving global variables ================== MyApp = (MyApp) getapplicationcontext (); string globalvariable = MyApp. getglobalvariable (); </span>
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.