Introduction and use of Android parcelable

Source: Internet
Author: User

One of the places that Parcelable uses is to pass a custom, more complex object between processes, and parcelable to write down his own point of view.

An object, such as a custom class named cartoon, is passed to the other activity by one activity, and this time the parcelable is used. First, we'll build a bean.

 PackageCom.example.sendobjfromactivity.bean;ImportAndroid.graphics.Bitmap; Public classCartoon {PrivateBitmap figure; PrivateString name; PrivateString Creator;  PublicBitmap getfigure () {returnFigure ; }     Public voidsetfigure (Bitmap figure) { This. Figure =Figure ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getcreator () {returnCreator; }     Public voidSetcreator (String creator) { This. Creator =Creator; }}

This is the format of the data we want to transfer, think about it, to transfer it between threads, it is necessary to serialize it, in Android is to implement the Parcelable interface, this excuse needs us to implement the Main method has Writetoparcel,describe, contentsparcelable.creator<? >. Complete serialization is done by relying on the Writetoparcel method, while deserializing the object and returning an object instance is dependent on contentsparcelable.creator< >.

Here's a piece of code that implements the Parcelable interface for the Parcelablecartoon class

 PackageCom.example.sendobjfromactivity.bean;ImportAndroid.graphics.Bitmap;ImportAndroid.os.Parcel;Importandroid.os.Parcelable;ImportAndroid.util.Log; Public classParcelablecartoonImplementsparcelable {PrivateCartoon Cartoon; Private Static FinalString MSG = "MESSAGE";  PublicParcelablecartoon (Cartoon Cartoon) {log.i (MSG,"Parcelablecartoon::[email protected]");  This. cartoon =cartoon; }        //writes an object to the parcel container//to complete serialization of an object    /*** Flatten This object with to a Parcel. *      * @paramdest the Parcel in which the object should is written. * @paramThe flags Additional flags about how the object should is written. * May is 0 or {@link#PARCELABLE_WRITE_RETURN_VALUE}. */@Override Public voidWritetoparcel (Parcel dest,intflags) {log.i (MSG,"Parcelablecartoon::writetoparcel");        Dest.writestring (Cartoon.getname ());        Dest.writestring (Cartoon.getcreator ());    Dest.writeparcelable (Cartoon.getfigure (), parcelable_write_return_value); }            //complete deserialization of serialized objects     Public Static FinalParcelable.creator<parcelablecartoon> Creator =NewParcelable.creator<parcelablecartoon>(){        //gets the serialized object from the parcel container and deserializes it to get an instance of the object        /*** Create A new instance of the Parcelable class, instantiating it * from the given Parcel whose data Had previously been written by * {@linkparcelable#writetoparcel parcelable.writetoparcel ()}. *          * @paramSOURCE The Parcel to read the object's data from. * @returnReturns A new instance of the Parcelable class. */@Override PublicParcelablecartoon Createfromparcel (Parcel source) {log.i (MSG,"Parcelablecartoon::P arcelable.creator::createfromparcel"); return NewParcelablecartoon (source); } @Override PublicParcelablecartoon[] NewArray (intsize) {log.i (MSG,"Parcelablecartoon::P Arcelable.creator::newarray"); return NewParcelablecartoon[size];        }            };  PublicParcelablecartoon (Parcel in) {log.i (MSG,"Parcelablecartoon::[email protected]"); Cartoon=NewCartoon (); String name=in.readstring ();        Cartoon.setname (name);        Cartoon.setcreator (In.readstring ()); Cartoon.setfigure (Bitmap) in.readparcelable (Bitmap.class. getClassLoader ())); }         PublicCartoon Getcartoon () {log.i (MSG,"Parcelablecartoon::getcartoon"); returncartoon; } @Override Public intdescribecontents () {log.i (MSG,"Parcelablecartoon::d escribecontents"); return0; }}

Comments in the English language are referenced in this class in an Android document. In this class, it involves a parcel, which is a container whose main task is to write to the object that needs to be serialized and write out (construct an instance) the object that needs to be deserialized.

By doing this, we can serialize the object, which means we can pass the object.

The following completes two activity, one is responsible for sending data, one to receive data.

Sendobjfromactivity.java Complete Send

 Packagecom.example.sendobjfromactivity;ImportJava.io.InputStream;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.graphics.Bitmap;Importandroid.graphics.BitmapFactory;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button;ImportCom.example.sendobjfromactivity.bean.Cartoon;ImportCom.example.sendobjfromactivity.bean.ParcelableCartoon; Public classSendobjfromactivityextendsActivity {PrivateButton SendData; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.main); SendData= (Button) This. Findviewbyid (R.id.button1); Senddata.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Cartoon Cartoon=NewCartoon (); Cartoon.setname ("Android"); Cartoon.setcreator ("Google"); InputStream is=getresources (). Openrawresource (R.drawable.ic_launcher); Bitmap Bitmap=Bitmapfactory.decodestream (IS);                Cartoon.setfigure (bitmap); Intent Intent=NewIntent (sendobjfromactivity. This, Receiveobjactivity.class); //to complete the serialization of an objectParcelablecartoon Parcelablecartoon =NewParcelablecartoon (Cartoon); Intent.putextra ("MSG", Parcelablecartoon);                            StartActivity (Intent);    }}); }}

Receiveobjactivity.java Completion of data reception

 Packagecom.example.sendobjfromactivity;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.os.Bundle;ImportAndroid.util.Log;ImportAndroid.widget.ImageView;ImportAndroid.widget.TextView;ImportCom.example.sendobjfromactivity.bean.Cartoon;ImportCom.example.sendobjfromactivity.bean.ParcelableCartoon; Public classReceiveobjactivityextendsActivity {PrivateImageView ShowImage; PrivateTextView Showtext; @Overrideprotected voidonCreate (Bundle savedinstancestate) {log.i ("MESSAGE", "go into another activity."); Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.display_obj); ShowImage= (ImageView) This. Findviewbyid (R.id.imageview1); Showtext= (TextView) This. Findviewbyid (R.id.textview1); Intent Intent=getintent (); Parcelablecartoon Parcelablecartoon=(Parcelablecartoon) intent. Getparcelableextra ("MSG"); Cartoon Cartoon=Parcelablecartoon.getcartoon ();        Showimage.setimagebitmap (Cartoon.getfigure ()); Showtext.settext (Cartoon.getname ()+ "\ n" +cartoon.getcreator ()); }}

In this program, the method inside the parcelable.creator<parcelablecartoon> is called to complete the deserialization.

Requires up to two XML layout files: Display_obj.xml,main.xml. Relatively simple no longer described.

The activity is configured under Androidmanifest.xml. This completes a small data transfer program, to see the results of the operation

Information that is output in the console

This shows how and in what order parcelable are run.

Related Article

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.