How to pass a Custom data object within a intent

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I need to pass my data object within the intent so that called activity can use that. But finding no method to add those to the intent.

Can any one please put light in this

Thanks

回答1:

You will need to make your data object parcelable and send it within the intent.

Check the link below. Hope it will help you :)

http://prasanta-paul.blogspot.com/2010/06/android-parcelable-example.html



回答2:

You can attach data to an intent using putExtras

String dataToPass = "The next activity needs this sentence."; ... Intent intent = new Intent(this, NextActivity.class); intent.putExtras("KeyToAccessData", dataToPass); startActivity(intent); 

And to retreive it from the intent

String dataToCollect; ... Intent intent = getIntent(); dataToCollect = intent.getStringExtra("KeyToAccessData"); 


回答3:

Just make your custom object implement Serializable. Then you can use intent.putExtra("package.name.Name", <your-serializable-object>). In the second activity you read it using getIntent().getSerializableExtra("package.name.Name")



回答4:

You could try creating a method in your custom object class to create an object from a json string and also create a method to convert the object to a json string. This way, you can pass the object as a string and rebuild it when you get to string from the other intent.

String objectJsonString = '["name":"objName", "value":"somevalue"]'; ... Intent intent = new Intent(this.getApplicationContext(), OtherActivity.class); intent.putExtras("KeyToAccessData", objectJsonString); sartActivity(intent); 

Then you recreate it in the new activity

Intent i = getIntent(); CustomObj obj = CustomObj.makeFromJsonString(i.getStringExtra("KeyToAccessData")); 


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