In applications, you may need to pass the data when you jump to another activity, and you may use the bundle object.
In the mainactivity, there is a intent that navigates to bactivity,
Intent
Copy Code code as follows:
{
Intent Intent = new Intent (context context, class<?> Class);
New a bundle object, and the data to be passed into, Bunde equivalent to map<key,value> structure
Bundle Bundle = new Bundle ();
Bundle.putstring ("name", "Livingstone");
Bundle.putxxx (Xxxkey, Xxxvalue);
Add the bundle object to the intent
Intent.putextras (bundle);
Invoke the intent corresponding activity
StartActivity (Intent);
}
In Bactivity, the following code is used to get the data passed by Mainactivity.
Bundle Bundle = This.getintent (). Getextras ()//Get the Bundle that encapsulates the data passed over
String name = bundle.getstring ("name");//get Name_key corresponding value
When getting a value, what type of fetch is added to get what type of value
--> bundle.getxxx (Xxxkey);
Return Xxxvalue
The above is the general basic data types, when the need to pass objects, you can enable the object to implement Parcelable or Serializable interface;
Add the object to the bundle through the bundle.putparcelable (key,obj) and Bundle.putserializable (Key,obj) methods, and then add the bundle object to the intent!
In the target page of the jump through Intent.getparcelableextra (Key) to achieve the Parcelable object;
In the target page of the jump through Intent.getserializableextra (Key) to achieve the serializable object;
In the study today, we found that Intent.putextra (Key,value) can actually pass the data, including the objects mentioned above!
Implement serializable interface is very simple, no longer described;
The following describes the implementation of the Parcelable interface:
Copy Code code as follows:
public class book implements Parcelable {
Private String BookName;
Private String author;
public static final Parcelable.creator Creator = new Creator () {///Here must define a Creator member variable, or it will be an error!
@Override
Public book Createfromparcel (Parcel source) {//Gets the data from the Parcel and needs to get the object instance through this method when fetching the data
Book book = new book ();
Book.setauthor (source.readstring ())//read from the parcel, read the data in the same order as the data written!
Book.setbookname (Source.readstring ());
return book;
}
@Override
Public book[] NewArray (int size) {
return new Book[size];
}
};
@Override
public int describecontents () {
return 0;
}
@Override//write Parcel
public void Writetoparcel (Parcel dest, int flags) {
Dest.writestring (author)//writes the data to the parcel, writes the data and reads the data in the same order!
Dest.writestring (BookName);
}
}
About parcel, probably looked over the description:
A final class for writing or reading all kinds of data, but it's all about WriteValue (Object) and read (ClassLoader)! (Personal translation comprehension)