Android# passing objects using intent

Source: Internet
Author: User

Reference from the first line of code--Guo Lin

Intent usage I believe you are familiar with it, we can use it to launch activities, send broadcasts, launch services, and more. In doing so, we can also add some additional data in the intent to achieve the effect of the value, such as adding the following code in the firstactivity:

New Intent (firstactivity.  this, secondactivity. class ); Intent.putextra ("String_data", "Hello"), Intent.putextra ("Int_data", "startactivity"); Intent);

Here the Intent Putextra () method is called to add the data to be passed, and then the values are available in secondactivity, as shown in the following code:

Getintent (). Getstringextra ("String_data"); Getintent (). Getintextra ("Int_data", 0);

But I don't know if you found out. The data types supported in the PutExtra () method are limited, although some commonly used data types are supported, but when you want to pass some custom objects, you will find it impossible. Don't worry, let's learn the techniques of using intent to pass objects.

First, Serializable way

There are usually two implementations of using intent to pass objects, serializable and parcelable, which we'll start with in this section to learn the first implementation.
Serializable is the meaning of serialization, which indicates that an object is converted to a state that can be stored or transportable. The serialized object can be transferred on the network or stored locally. As for the serialization method is also very simple, only need to let a class to implement serializable this interface can be.
For example, there is a person class that contains both the name and age fields, and you want to serialize it so you can write:

 Public classPersonImplementsSerializable {PrivateString name; Private intAge ;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }}

Where the Get and set methods are used to assign and read field data, the most important part is in the first row. This allows the person class to implement the serializable interface so that all the person objects are serializable.
The next step in Firstactivity is very simple:

New Person ();p erson.setname ("Tom");p erson.setage (new Intent (firstactivity.  this, secondactivity. class ); Intent.putextra ("Person_data", person); StartActivity (intent) ;

As you can see, here we create an instance of the person and then directly pass it into the Putextra () method. Because the person class implements the serializable interface, this can only be written.
It is also easy to get this object in Secondactivity, as follows:

Person person = (person) getintent (). Getserializableextra ("Person_data");

This invokes the Getserializableextra () method to get the serialized object passed through the parameter, then transforms it down to the person object, so that we can successfully implement the function of passing the object using intent.

Second, the Parcelable way

In addition to serializable, using parcelable can achieve the same effect, but unlike serializing an object, the parcelable approach is to decompose a complete object, and each part of the decomposition is a data type supported by intent. , it also implements the function of passing objects.
Let's take a look at how the parcelable is implemented, modifying the code in person, as follows:

 Public classPersonImplementsparcelable {PrivateString name; Private intAge ; @Override Public intdescribecontents () {return0; } @Override Public voidWritetoparcel (Parcel dest,intflags) {dest.writestring (name);//Write nameDest.writeint (age);//Write Age    }     Public Static FinalParcelable.creator<person> Creator =NewParcelable.creator<person>() {@Override PublicPerson createfromparcel (Parcel source) { person person=NewPerson (); Person.name= Source.readstring ();//Read namePerson.age = Source.readint ();//Read Age            returnPerson ; } @Override PublicPerson[] NewArray (intsize) {            return NewPerson[size]; }    };}

Parcelable is a little more complicated to implement. As you can see, first we let the person class implement the Parcelable interface, so that the two methods of Describecontents () and Writetoparcel () must be rewritten. where the Describecontents () method returns 0 directly, and in the Writetoparcel () method we need to call Parcel's writexxx () method to write out field one by one in the person class. Note that the string data calls the WriteString () method, the integer data calls the Writeint () method, and so on.
In addition, we must also provide a constant named creator in the person class, where an implementation of the Parcelable.creator interface is created, and the generic is specified as man. Then we need to rewrite the two methods of Createfromparcel () and NewArray (), in the Createfromparcel () method We are going to read the name and age fields we just wrote and create a person object to return. Where both name and age are read by the Readxxx () method called parcel, note that the order of reading here must be exactly the same as the order you just wrote. The implementation in the NewArray () method is much simpler, just a new person array is required, and the size of the passed in method is used as an array.
Next in Firstactivity we can still use the same code to pass the person object, except that we need to make a little change when we get the object in Secondactivity, as follows:

Person person = (person) getintent (). Getparcelableextra ("Person_data");

Note that this is no longer called the Getserializableextra () method, but instead calls the Getparcelableextra () method to get the object passed over, and the rest of the place is exactly the same.
In this way we have learned the two implementations of using intent to pass objects, and in contrast, the serializable is simpler, but because the entire object is serialized, the efficiency will be lower than the parcelable way, Therefore, in general, it is more recommended to use the Parcelable method to implement the function of the intent transitive object.

Android# passing objects using intent

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.