Use Parcelable to transfer an object from one Android activity to another

I want to do it

 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); } 

code>

How to use parcelable to pass obj to action B?

+6
source share
3 answers

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

Of course, you do not need to use putParcelable - you can instead implement Serializable and call putSerializable .

+5
source

Create your class and implement Serializable :

 private class myClass implements Serializable { } 

And do this:

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

On The host:

 myClass myClassObject = getIntent().getSerializableExtra("object"); 
+7
source

There may be pain in writing code, but more economical than Serializable. Check out the link below -

Parcelable Vs Serializable

+2
source

Source: https://habr.com/ru/post/917756/


All Articles