English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article details the complex parameter passing method between Android intents. Shared for everyone's reference, as follows:
Intent is the medium for passing parameters between Activity and Activity, and between Activity and Service, and these two usually implement the transmission of Java basic object types and Strings.
In actual projects, when passing values between pages, in addition to the above several methods, there is often a need to pass Object objects, List types, List<Object> types, and global variables, etc. This article introduces how to pass these types of parameters.
I. Passing List<String> and List<Integer>
Here is an example of sending List<String>, the syntax for sending List<String> is:
intent.putStringArrayListExtra(key, list);
The syntax for receiving List<String> is:
list = (ArrayList<String>)getIntent().getStringArrayListExtra(key);
Here is an example of usage:
// =============Send List<String>============= ArrayList<String> stringList = new ArrayList<String>(); stringList.add("string"1"); stringList.add("string"2"); stringList.add("string"3"); Intent intent = new Intent(); intent.setClass(ListDemoActivity.this, StringListActivity.class); intent.putStringArrayListExtra("ListString", stringList); startActivity(intent); // ====================Receive List<String>====================== ArrayList<String> stringList = (ArrayList<String>) getIntent().getStringArrayListExtra("ListString");
Similar to the above operations, the following method can also be used to send and receive: List<Integer>
intent.putIntegerArrayListExtra(key, list); list = (ArrayList<Integer>) getIntent().getIntegerArrayListExtra(key);
Part Two: Passing Objects Using Both Serializable and Parcelable
There are two ways to pass objects between Android Intents: one is Bundle.putSerializable(Key, Object); and the other is Bundle.putParcelable(Key, Object). The Object in the method must meet certain conditions, with the former implementing the Serializable interface and the latter implementing the Parcelable interface.
The following is the User class that has implemented the Serializable interface, named SerializableUser purely for the convenience of distinguishing it from the User class that has implemented the Parcelable interface. It is not recommended to name classes this way in actual 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 has implemented 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); } }
using two methodspassThe syntax is as follows:
bundle.putSerializable(key, object); bundle.putParcelable(key, object);
using two methodsreceiveThe syntax is as follows:
object = (Object) getIntent().getSerializableExtra(key); object = (Object) getIntent().getParcelableExtra(key);
// ==========Sending Object Using Serializable and Parcelable respectively=========== SerializableUser serializableUser = new SerializableUser("user"1", "123456"); ParcelableUser parcelableUser = new ParcelableUser("user"2""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");
Someone may have noticed that implementing the Serializable interface is essentially serializing an object and then transmitting it, which does not significantly differ from common Java programming practices, and the User class does not need to be changed significantly, making it relatively simple. I also recommend using this method.
However, the latter implementation of Parcelable interface is more complex. What is Parcelable, exactly?
Android provides a new type: Parcel, which is used as a container for encapsulating data. Encapsulated data can be passed through Intent or IPC. In addition to basic types, only classes that implement the Parcelable interface can be placed in a Parcel.
To implement Parcelable interface, it is necessary to implement three methods:
1The writeToParcel method. This method writes the data of the class into the Parcel provided externally.
Declaration: writeToParcel(Parcel dest, int flags).
2The describeContents method. Just return 0 can be.
3The static Parcelable.Creator<T> interface, this interface has two methods:
createFromParcel(Parcel in) implements the function of creating an instance of the class from in.
newArray(int size) creates an array of type T with a length of size, and return new T[size]; can be. This method is provided for external classes to deserialize arrays of this class.
Through log test output, we can see the running status of the program. When calling bundle.putParcelable("parcelableUser", parcelableUser);, the public void writeToParcel(Parcel dest, int flags) method in ParcelableUser class is called, and data is written to dest. When ParcelableUser parcelableUser = (ParcelableUser) getIntent().getParcelableExtra("parcelableUser");, the public ParcelableUser createFromParcel(Parcel source) method in ParcelableUser class is called to create a ParcelableUser object and assign values to its properties. Here, Parcel source and Parcel dest are the same, and then the ParcelableUser object is returned. Finally, we can print out the property information of parcelableUser.
3. Passing List<Object>
What should we do if we need to pass a List composed of Objects, i.e., List<Object>? First, we need to implement the Serializable interface for the Object object, then cast the list to the Serializable type, and finally through:
Intent.putExtra(key, (Serializable)objectList);
This syntax is used to pass, and the receiver also needs to perform a type cast to List<Object> when receiving, and the syntax used to receive List<Object> is:}
objectList= (List<Object>) getIntent().getSerializableExtra(key);
Here is an application example. The SerializableUser class used in the previous step is given here, so it will not be 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");
4. Global Variables
If some special application-level parameters are not convenient to pass through intent, we might easily think if there are global variables or static variables that can be used? Java static variables are suitable here, but their values are lost after the Activity calls System.exit(0) or finish().
In Android, there is a more elegant way to use ApplicationContext. This method of global variables is more secure than static classes, and it will only be released after all the Activities of the application have been destroyed.
The Android SDK states that an Application is used to store global variables and it exists since the package is created. Therefore, when we need to create global variables, we do not need to do it in the same way as J2Instead of creating public static variables with the SE permission, we can implement it directly in the application. We just need to call Context.getApplicationContext or Activity.getApplication method to get an Application object, and then we can set or read the values of global variables.
When the Application is started, the system creates a PID, which is the process ID, and all Activities will run on this process. So, we initialize the global variables when the Application is created, and all Activities in the same application can access the values of these global variables. In other words, if we change the values of these global variables in one Activity, the values will change in other Activities in the same application.
Usage:
1Create a subclass of android.app.Application that belongs to you, and add setter and getter methods for 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; } }
2Declare this class in the manifest, and at this point, Android will create a globally available instance for it.
It is actually adding a name to the existing single application tag for the global instance.
<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
3You can use the Context.getApplicationContext() method to get this instance anywhere else, and then access the state (variables) within it.
// ============Using Global Variables to Pass Parameters============== MyApp myApp = ((MyApp) getApplicationContext());//Get our application 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();
Readers who are interested in more content related to Android can check the special topics on this site: 'Android Development入门与进阶教程', 'Android Programming Activity Operation Skills Summary', 'Android Resource Operation Skills Summary', 'Android File Operation Skills Summary', 'Android Operation SQLite Database Skills Summary', 'Android Operation JSON Format Data Skills Summary', 'Android Database Operation Skills Summary', 'Android Programming Development SD Card Operation Method Summary', 'Android View View Skills Summary', and 'Android Widget Usage Summary'
I hope the content described in this article will be helpful to everyone in Android program design.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @ when sending an email) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.