This article describes in detail the method of passing complex parameters between Android intents. Share it for your reference, as follows:
Intent is the medium that passes parameters between Activity and Activity, Activity and Service, and these two usually implement the passing of Java basic object types and String.
In actual projects, in addition to the above, there are often requirements for passing values between pages to pass Object objects, List types, List<Object> types, global variables, etc. This article introduces how to pass these types of parameters.
1. Pass List<String> and List<Integer>
The following is the example of passing List<String>, and the syntax for sending List<String> is:
(key, list);
The syntax for receiving List<String> is:
list = (ArrayList<String>)getIntent().getStringArrayListExtra(key);
Here is an application example:
// ==================Send List<String>=================ArrayList<String> stringList = new ArrayList<String>(); ("string1"); ("string2"); ("string3"); Intent intent = new Intent(); (, ); ("ListString", stringList); startActivity(intent); // ================================ Receive List<String>===========================ArrayList<String> stringList = (ArrayList<String>) getIntent().getStringArrayListExtra("ListString");
List<Integer> can also implement sending and receiving by calling the following methods:
(key, list); list =(ArrayList<Integer>) getIntent().getIntegerArrayListExtra(key);
2. Use Serializable and Parcelable to pass Object
There are two ways to pass objects between Android's Intents, one is (Key,Object); the other is (Key,Object). The Object 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. Named SerializableUser is purely to easily distinguish the User class that implements the Parcelable interface from the class name. In actual development, this is not recommended:
public class SerializableUser implements Serializable { private String userName; private String password; public SerializableUser() { } public SerializableUser(String userName, String password) { = userName; = password; } public String getUserName() { return userName; } public void setUserName(String userName) { = userName; } public String getPassword() { return password; } public void setPassword(String 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) { = userName; = password; } public String getUserName() { return userName; } public void setUserName(String userName) { = userName; } public String getPassword() { return password; } public void setPassword(String password) { = password; } public static final <ParcelableUser> CREATOR = new Creator<ParcelableUser>() { @Override public ParcelableUser createFromParcel(Parcel source) { ParcelableUser parcelableUser = new ParcelableUser(); = (); = (); 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 (userName); (password); } }
Two ways to usetransferThe syntax of the following are:
(key,object); (key,object);
Two ways to usetake overThe syntax of the following are:
object=(Object) getIntent().getSerializableExtra(key); object=(Object) getIntent().getParcelableExtra(key);
// ============ 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(); ("serializableUser", serializableUser); ("parcelableUser", parcelableUser); (,); (bundle); startActivity(intent); // ===========================================================SerializableUser serializableUser = (SerializableUser) getIntent().getSerializableExtra("serializableUser"); ParcelableUser parcelableUser = (ParcelableUser) getIntent().getParcelableExtra("parcelableUser");
Some people may notice that implementing the Serializable interface is to serialize objects and then transmit them. It is no obvious difference from the commonly used Java programming, and the User does not need to be significantly changed, so it is relatively simple. I also recommend this method.
However, the latter class that implements the Parcelable interface is more complicated. What is Parcelable?
Android provides a new type: Parcel, which is used as a container for encapsulating data. The encapsulated data can be passed through Intent or IPC. In addition to basic types, only classes that implement the Parcelable interface can be put into Parcel.
Implementing the Parcelable interface requires three methods:
1) writeToParcel method. This method writes the data of the class into the externally provided Parcel.
Statement: writeToParcel (Parcel dest, int flags).
2) describeContents method. Just return to 0.
3) There are two methods for the static <T> interface:
createFromParcel(Parcel in) implements the function of creating an instance of a class from in.
newArray(int size) Create an array of type T and length size, return new T[size]; This method is used for external classes to deserialize the array of this class.
Through the log test output, we can know the operation of the program. When ("parcelableUser", parcelableUser);, the publicvoid writeToParcel(Parcel dest, int flags) method in the ParcelableUser class is called, and data is written to dest. When ParcelableUserparcelableUser= (ParcelableUser)getIntent().getParcelableExtra("parcelableUser");, the public ParcelableUser createFromParcel(Parcel source) method in the ParcelableUser class is called, and a ParcelUser object is created, and the attributes of this object are assigned. Here source and Parcel dest are the same, and then return this ParcelableUser object. Finally, you can print out the property information of parcelableUser.
3. Pass List<Object>
What should we do if we want to pass a List list composed of Object, that is, List<Object>? First, you need to implement the Serializable interface of the Object object, then cast the list type to the Serializable type, and finally pass:
(key, (Serializable)objectList);
For such syntax to pass, the receiver also needs to cast the type to List<Object> when receiving it. The syntax used to receive List<Object> is:
objectList= (List<Object>) getIntent().getSerializableExtra(key);
The following is an application example. The SerializableUser class used here was given in the previous step, so I will not repeat it here.
// ==================== Send List<Object>==============SerializableUser user1 = new SerializableUser("user1", "123456"); SerializableUser user2 = new SerializableUser("user2", "654321"); List<SerializableUser> objectList = new ArrayList<SerializableUser>(); (user1); (user2); Intent intent = new Intent(); (, ); ("ListObject", (Serializable) objectList); startActivity(intent); // =============================== Receive List<Object>=============================List<SerializableUser> objectList = (List<SerializableUser>) getIntent().getSerializableExtra("ListObject");
4. Global variables
If some special application-level parameters are not convenient to use intent to pass parameters, it is easy for us to think of whether there are global or static variables that can be used? Static variables in Java are suitable here, but their values are lost after Activity calls (0) or finish().
And there is a more elegant way in android to use ApplicationContext. This global variable method is more secure than static classes, and will not be released until all the activities applied are destory.
Android's SDK says that Application is used to save global variables and exists when the package is created. So when we need to create global variables, we no longer need to create static variables with public permissions like J2SE, but implement them directly in the application. You only need to call the getApplicationContext of Context or the getApplication method of Activity to obtain an Application object, and you can set or read the value of the global variable.
When starting Application, the system will create a PID, that is, the process ID, and all activities will run on this process. Then we initialize global variables when the Application is created, and all 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 a certain activity, the values in other activities of the same application will change.
usage:
1. Create a subclass of your own and add setter and getter methods to the private global variable you want to share.
public class MyApp extends Application{ private String globalVariable; public String getGlobalVariable() { return globalVariable; } public void setGlobalVariable(String globalVariable) { = globalVariable; } }
2. Declare this class in manifest, and then Android will create a globally available instance for this.
In fact, it is to create a name for the application on the only application tag as this global instance.
3. You can use the() method to obtain this instance anywhere else, and then obtain the state (variable).
// =======================================MyApp myApp = ((MyApp) getApplicationContext());//Get our app MyApp("Global Variables"); Intent intent = new Intent(); (, ); startActivity(intent); // =================== Receive global variable parameters================MyApp myApp = ((MyApp) getApplicationContext()); String globalVariable = ();
For more information about Android related content, please check out the topic of this site:Android development introduction and advanced tutorial》、《Android programming activity operation skills summary》、《Android resource operation skills summary》、《Android file operation skills summary》、《Summary of Android's SQLite database skills》、《Summary of Android data skills for operating json format》、《Android database operation skills summary》、《A summary of SD card operation methods for Android programming and development》、《Android View View Tips Summary"and"Android control usage summary》
I hope this article will be helpful to everyone's Android programming design.