dev_android
dev_android

Reputation: 8818

Android: Sending an object from one activity to other activity

To send intent with any object from one activity to another activity we can use Parcelable Interface or Serializable Interface. What is the difference between two? Which one is preferable to use?

Moreover, we can send string, integer type of object without using all this Interface. How it is possible?

Upvotes: 2

Views: 1199

Answers (4)

Midhu
Midhu

Reputation: 1697

You can send String, Integer and such data types, and also the objects of the classes that implemented Parcelable interface as follows...

Intent intent = new Intent(CallingActivity.this, CalledActivity.class);
intent.putExtra("IntegerExtra", intValue);
intent.putExtra("StringExtra", stringValue);
intent.putExtra("ParcExtra", parcObject);
startActivity(intent);

And, at the receiving end you can write the following code,

intValue = getIntent().getIntExtra("IntegerExtra", 0);
stringValue = getIntent().getStringExtra("StringExtra");    
parcObject = ((YourParcalabeDataType) getIntent().getParcelableExtra("ParcExtra"));

Hope this may solve your problem... :)

Upvotes: 2

denizt
denizt

Reputation: 713

You can find difference between Parcelable and Serializable Interface from that link . Basically Parcelable is created for android and is far more efficient than Serializable.

You can simply send string or integer by using Bundles and linking those bundles to intents.

Intent i = new Intent(getApplicationContext(),YourClass.class);
Bundle b = new Bundle();
b.putString("string", "string");
i.putExtras(b);
startActivity(i);

Upvotes: 0

Mohammod Hossain
Mohammod Hossain

Reputation: 4114

Java Serializable: Serializable comes from standard Java and is much easier to implement all you need to do is implement the Serializable interface and add override two methods.

  private void writeObject(java.io.ObjectOutputStream out)
              throws IOException 
  private void readObject(java.io.ObjectInputStream in)
              throws IOException, ClassNotFoundException

The problem with Serializable is that it tries to appropriately handle everything under the sun and uses a lot reflection to make determine the types that are being serialized. So it becomes a beefy Object

Androids Parcelable: Android Inter-Process Communication (AIPC) file to tell Android how is should marshal and unmarshal your object.It is less generic and doesn't use reflection so it should have much less overhead and be a lot faster.

Upvotes: 3

jtt
jtt

Reputation: 13541

Intead of sending an object, it may be easier to just send a URI that points to your content. This would simplify the sending and would remove the need to send the object, since the URI would ideally point to the content you are interested in. Of course this depends on the content that you're trying to pass.

Upvotes: 0

Related Questions