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
Start another activity from this activity pass parameters via Bundle Object
Retrieve on another activity (YourActivity)
This is ok for simple kind data type. But if u want to pass complex data in between activity u need to serialize it first.
Here we have Employee Model
You can use Gson lib provided by google to serialize the complex data like this
You can use android BUNDLE to do this.
Create a Bundle from your class like:
Then pass this bundle with INTENT. Now you can recreate your class object by passing bundle like
Declare this in your Custom class and use.
Create Android Application
File >> New >> Android Application
Enter Project name: android-pass-object-to-activity
Pakcage: com.hmkcode.android
Keep other defualt selections, go Next till you reach Finish
Before start creating the App we need to create POJO class “Person” which we will use to send object from one activity to another. Notice that the class is implementing Serializable interface.
Person.java
Two Layouts for Two Activities
activity_main.xml
activity_another.xml
Two Activity Classes
1)ActivityMain.java
2)AnotherActivity.java
If you have a singleton class (fx Service) acting as gateway to your model layer anyway, it can be solved by having a variable in that class with getters and setters for it.
In Activity 1:
In Activity 2:
In Service:
This solution does not require any serialization or other "packaging" of the object in question. But it will only be beneficial if you are using this kind of architecture anyway.
POJO class "Post" (Note that it is implemented Serializable)
POJO class "Comment"(Since being a member of Post class,it is also needed to implement the Serializable)
Then in your activity class, you can do as following to pass the object to another activity.
In your recipient class "CommentsActivity" you can get the data as the following
First implement Parcelable in your class. Then pass object like this.
SendActivity.java
ReceiveActivity.java
The package string isn't necessary, just the string needs to be the same in both Activities
REFERENCE