android - Using Parceble to communicate between activities -
so trying pass object 1 activity using parceble
provided in android right thing use in case.
this bean class have serialized
implementing parceble
customer.class
public class customer implements parcelable { int a; string name; public customer(int ab , string n) { this.a=ab; this.name=n; } public int geta() { return a; } public void seta(int a) { this.a = a; } public string getname() { return name; } public void setname(string name) { this.name = name; } public customer(parcel in) { a= in.readint(); name= in.readstring(); //readfromparcel(in); } @override public int describecontents() { // todo auto-generated method stub return 0; } @override public void writetoparcel(parcel dest, int flags) { dest.writestring(name); dest.writeint(a); } public static final parcelable.creator<customer> creator= new parcelable.creator<customer>() { @override public customer createfromparcel(parcel source) { return new customer(source); } @override public customer[] newarray(int size) { return new customer[size]; } }; private void readfromparcel(parcel in) { a= in.readint(); name= in.readstring(); } }
mainactivity.class
public class mainactivity extends activity { button b; customer c; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); b=(button) findviewbyid(r.id.button1); c=new customer(33,"nn"); b.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { intent i=new intent(mainactivity.this,customactivity.class); i.putextra("myobj", c); startactivity(i); } }); } }
customactivity.class
public class customactivity extends activity{ @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); intent it=getintent(); customer c=(customer)it.getparcelableextra("myobj"); system.out.println("and object "+c.geta()+"/"+c.getname()); } }
and output in logcat:
05-15 12:02:56.014: i/system.out(25581): , object 2/null
the problem in readfromparcel
method. rule "the sequence of members must same while writing or reading members of parcelable objects"
so have change readfromparcel(parcel in)
from
private void readfromparcel(parcel in) { a= in.readint(); name= in.readstring(); }
to
private void readfromparcel(parcel in) { name= in.readstring(); a= in.readint(); }
because writetoparcel(..)
writes name
first , a
.
parcelable interface overview can reference you.
Comments
Post a Comment