Android: Sending an object from one activity to other activity

我的梦境 提交于 2021-01-27 19:21:44

问题


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?


回答1:


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.




回答2:


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... :)




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/11843482/android-sending-an-object-from-one-activity-to-other-activity

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