The transfer of complex parameters between Android intent

Source: Internet
Author: User

This article is from the Linux commune website (www.linuxidc.com) Source Link: http://www.linuxidc.com/Linux/2012-04/58732.htm

I. Transmission of list<string> and list<integer>

The following is an example of passing list<string>, sending the list<string> syntax as:

Intent.putstringarraylistextra (key, list);

The syntax for receiving list<string> is:

List = (arraylist<string>) getintent (). Getstringarraylistextra (key);

Here is an example of using:

============= 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");
List<integer> Similar operations call the following methods can also be implemented for sending and receiving:

Intent.putintegerarraylistextra (key, list);

List = (arraylist<integer>) getintent (). Getintegerarraylistextra (key);

Second, the use of serializable and parcelable two ways to transfer the object

There are two ways to pass objects between Android intent, one is bundle.putserializable (Key,object), and 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, which is not recommended in practical development:

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;
}
}
The following is the user class that implements the Parcelable interface:

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

========== using 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);
==================== receiving object======================
Serializableuser Serializableuser = (serializableuser) getintent (). Getserializableextra ("SerializableUser");
Parcelableuser Parcelableuser = (parcelableuser) getintent (). Getparcelableextra ("Parcelableuser");
It may be noted that 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. I recommend it in this way, too.

However, the latter class that implements the Parcelable interface is more complex, what is parcelable?

Android offers 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:


1) Writetoparcel method. This method writes the data of the class to an externally supplied parcel.

Declaration: Writetoparcel (Parcel dest, int flags).


2) Describecontents method. return directly to 0.


3) A static parcelable.creator<t> interface, this interface has two methods:


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.

Iii. Transmission of List<object>

What if we are going to pass a list of objects consisting of an Object, that is, list<object> First, the object object is implemented with the serializable interface, then the list coercion type is converted to the serializable type, and finally by:

Intent.putextra (Key, (Serializable) objectList);

This syntax is passed, and the receiving party also needs to force the type to convert to List<object> when it receives it, and 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);
==================== receiving 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:

1. 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;
}
}

2. Confirm this class in manifest, when Android builds a globally available instance.

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

3. You can use the Context.getapplicationcontext () method anywhere else to get the instance and get the state (variable) in it.

============ use global variables to pass parameters ==============
MyApp MyApp = ((myApp) Getapplicationcontext ());//Get our application MyApp
Myapp.setglobalvariable ("Global Variables");
Intent Intent = new Intent ();
Intent.setclass (Listdemoactivity.this, Globalactivity.class);
StartActivity (Intent);
============ receive parameters for global variables ==============
MyApp MyApp = (MyApp) getapplicationcontext ());
String globalvariable = myapp.getglobalvariable ();
Through the introduction of the above about passing object object, List type, list<object> type and global variable, we hope to give you some help.

This article is from the Linux commune website (www.linuxidc.com) Source Link: http://www.linuxidc.com/Linux/2012-04/58732.htm

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.