Android---Intent pass parameters

Source: Internet
Author: User

Intent is a medium for transferring parameters between activity and service, using intent and bundles to pass data between components, both of which typically implement Java basic object types and string delivery. In the actual project, the transfer of values between pages, in addition to the above, there are often the need to pass object objects, List type, list<object> type and global variables and so on.
First, pass list<string> and list<integer> below to pass list<string> for example, send list<string> syntax is: Intent.putstringarraylistextra (key, list); The syntax for receiving list<string> is: List = (arraylist<string>) getintent (). Getstringarraylistextra (key); Here is an example of using:

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); Receive arraylist<string> stringlist = (arraylist<string>) getintent (). Getstringarraylistextra ("ListString") ;

List<integer> similar to the operation call the following method can also be implemented to send and receive: Intent.putintegerarraylistextra (key, list); List = (arraylist<integer>) getintent (). Getintegerarraylistextra (key);

Second, the use of serializable and parcelable two ways to pass object Android Intent between two methods of passing objects, one is bundle.putserializable (key,object); The other is bundle.putparcelable (Key,object). The object in the method satisfies certain conditions, the former realizes the serializable interface, and the latter implements the Parcelable interface. The following is the user class that implements the Serializable interface, named Serializableuser, which is simply the user class that implements the Parcelable interface from the class name:

public class Serializableuser implements Serializable {      private String username;   & nbsp;  Private String password;      public serializableuser () {     }& nbsp     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;     } } 

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

public class Parcelableuser implements parcelable {      private String username;       Private String password;      public parcelableuser () {     }  & nbsp;   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 &nbsP         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);     }  } 

The syntax that is passed in two ways is: bundle.putserializable (key,object); Bundle.putparcelable (Key,object); The syntax that is received in two ways is: object= (object) getintent (). Getserializableextra (key); object= (Object) getintent (). Getparcelableextra (key);

Use Serializable and parcelable respectively 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");

The

Implementation of the serializable interface is to serialize the object, and then transfer, and Java's common programming is no obvious difference, and the user does not need to change significantly, relatively simple. However, the latter class of implementing the Parcelable interface is more complex than Android provides a new type: Parcel, which is used as a container for encapsulating data, and the encapsulated data can be passed through intent or IPC. Except for the base type, only classes that implement the Parcelable interface can be placed in parcel. Implementing the Parcelable interface requires the implementation of three methods:) the Writetoparcel method. This method writes the data of the class to an externally supplied parcel. Declaration: Writetoparcel (Parcel dest, int flags). ) Describecontents method. return directly to 0. ) Static parcelable.creator<t> interface, this interface has two methods:

The

Createfromparcel (Parcel in) implements the ability to create an instance of a class from in. NewArray (int size) creates an array of type T, length of size, returnnew t[size]; This method is used by the outer class to deserialize the array of this class. The log test output shows the operation of the program, in Bundle.putparcelable ("Parcelableuser", Parcelableuser), when the Parcelableuser class is called publicvoid Writetoparcel (Parcel dest, int flags) method, and writes data to Dest, in parcelableuserparcelableuser= (Parcelableuser) getintent (). Getparcelableextra ("Parcelableuser"), when the public parcelableusercreatefromparcel in the Parcelableuser class is called (Parcel source ) method, create a Parcelableuser object and assign a value to the property of the object, where parcel source and parcel dest are the same, and then return the Parcelableuser object. Finally, you can print out the Parcelableuser attribute information.
Third, pass list<object> if we are going to pass a list of objects, that is, LIST<OBJECT>, first you need to implement the object serializable interface, The list coercion type is then converted to the Serializable type, and finally by: Intent.putextra (Key, (Serializable) objectList); Such a syntax to pass, the receiver in the receiving time also need to force the type conversion to LIST<OBJECT>, the syntax to receive list<object> is: objectlist= (list<object>) Getintent (). Getserializableextra (key); The following is an example of an application where the Serializableuser class is given in the previous step and is not repeated here.

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 "); 

Iv. Global Variables if some special application-level parameters are not convenient for passing parameters using intent, it is easy to think of whether there are global variables or static variables that can be used? Static variables in Java are appropriate here, but their values are lost after the activity calls System.exit (0) or finish (). And there's a more elegant way to use ApplicationContext in Android. This global variable method is more secure than a static class, and is not released until all of the app's activity is destory out. As the Android SDK says, application is used to hold global variables, and it exists when the package is created. So when we need to create global variables, we do not need to create the static variables of public permissions as J2SE, but directly in the application. You can set or read the value of a global variable simply by invoking the context's Getapplicationcontext or activity's Getapplication method to get a Application object. When application is started, a PID, the process ID, is created, and all activity is run on this process. Then we initialize the global variables when the application is created, all the activity of the same application can fetch the values of these global variables, in other words, we change the values of these global variables in one activity, Then the value of the other activity in the same application will change. Usage: .        Create a subclass of your own android.app.Application, adding setter and getter methods to the private global variables you want to share.

public class MYAPP extends application{private String globalvariable;      Public String getglobalvariable () {return globalvariable;      } public void Setglobalvariable (String globalvariable) {this.globalvariable = globalvariable; }  }
. Declare this class in manifest, when Android builds a globally available instance of this. In fact, in the original only one application label for application to develop a name for this global instance.

<application android:name= ".        MyApp "android:icon=" @drawable/icon "android:label=" @string/app_name "></span>. You can use the Context.getapplicationcontext () method anywhere else to get the instance and get the state (variable) in it.

Use a global variable to pass the parameter MyApp MyApp = (MyApp) getapplicationcontext ());//Get our application MyApp myapp.setglobalvariable ("global variable");  Intent Intent = new Intent ();  Intent.setclass (Listdemoactivity.this, Globalactivity.class);  StartActivity (Intent);  The parameter that receives the global variable MyApp MyApp = (MyApp) getapplicationcontext ()); String globalvariable = myapp.getglobalvariable ();

Original source: http://www.cnblogs.com/zlja/archive/2012/04/13/2446579.html

Android---Intent pass parameters

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.