How can I pass an object of a custom type from one Activity to another using the putExtra()
method of the class Intent?
相关问题
- How can I create this custom Bottom Navigation on
- Bottom Navigation View gets Shrink Down
- How to make that the snackbar action button be sho
- Listening to outgoing sms not working android
- How to create Circular view on android wear?
相关文章
- android开发 怎么把图片放入drawable的文件夹下
- android上如何获取/storage/emulated/下的文件列表
- androidStudio有个箭头不认识
- SQLite不能创建表
- Windows - Android SDK manager not listing any plat
- Animate Recycler View grid when number of columns
- Why is the app closing suddenly without showing an
- Android OverlayItem.setMarker(): Change the marker
If you're just passing objects around then Parcelable was designed for this. It requires a little more effort to use than using Java's native serialization, but it's way faster (and I mean way, WAY faster).
From the docs, a simple example for how to implement is:
Observe that in the case you have more than one field to retrieve from a given Parcel, you must do this in the same order you put them in (that is, in a FIFO approach).
Once you have your objects implement
Parcelable
it's just a matter of putting them into your Intents with putExtra():Then you can pull them back out with getParcelableExtra():
If your Object Class implements Parcelable and Serializable then make sure you do cast to one of the following:
You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.
In that case you just put the string return value from
(new Gson()).toJson(myObject);
and retrieve the string value and usefromJson
to turn it back into your object.If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.
if your object class implements
Serializable
, you don't need to do anything else, you can pass a serializable object.that's what i use.
I use Gson with its so powerful and simple api to send objects between activities,
Example
2 functions you add them to the objects that you want to send
Usage
Send Object From A to B
Receive In B
I use it almost in every project i do and I have no performance issues.
You can send serializable object through intent
implement serializable in your class
Then you can pass this object in intent
int the second activity you can get data like this
But when the data become large,this method will be slow.