Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 432
Namratha Avatar asked Jun 11 '12 06:06

Namratha


People also ask

What is the use of Parcelable in Android?

Stay organized with collections Save and categorize content based on your preferences. Parcelable and Bundle objects are intended to be used across process boundaries such as with IPC/Binder transactions, between activities with intents, and to store transient state across configuration changes.

How do I move an object from one fragment to another in Android?

Step 1 − Create a new project in Android Studio, go to File ⇉ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. Step 3 − Create two FragmentActivity and add the codes which are given below.


2 Answers

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");  
like image 60
Paresh Mayani Avatar answered Sep 17 '22 18:09

Paresh Mayani


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.

like image 38
Jon Skeet Avatar answered Sep 17 '22 18:09

Jon Skeet