Use Parcelable to pass an object from one android activity to another

社会主义新天地 提交于 2019-12-09 17:48:43

问题


I want to do this

class A extends Activity{
   private class myClass{
   }
   myClass obj = new myClass();

  intent i = new Intent();
  Bundle b = new Bundle();
  b.putParcelable(Constants.Settings, obj); //I get the error The method putParcelable(String, Parcelable) in the type Bundle is not applicable for the arguments (int, A.myClass)
  i.setClass(getApplicationContext(),B.class);
  startActivity(i);  
}

How do I use Parcelable to pass obj to activity B?


回答1:


As the error suggests, you need to make your class (myClass in this case) implement Parcelable. If you look at the documentation for Bundle, all the putParcelable methods take either a Parcelable or a collection of them in some form. (This makes sense, given the name.) So if you want to use that method, you need to have a Parcelable instance to put in the bundle...

Of course you don't have to use putParcelable - you could implement Serializable instead and call putSerializable.




回答2:


Create your class and implements Serializable:

private class myClass implements Serializable  {
   }

And do like:

myClass obj = new myClass();
Intent aActivity = (A.this, B.class);
intent.putExtra("object", obj);

On Receiving side:

myClass myClassObject = getIntent().getSerializableExtra("object");  



回答3:


Parcelable is pain in writing code but more cost effective than Serializable. Have a look at the given below link -

Parcelable Vs Serializable



来源:https://stackoverflow.com/questions/10975239/use-parcelable-to-pass-an-object-from-one-android-activity-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!