Reputation: 403
I decided to use Parceler because it looks like a great library and it is very well supported by the author. I am using Parceler to wrap an object and pass it to another Activity in a Bundle. When I attempt to unwrap the object I am getting the error: android.os.Bundle cannot be cast to org.parceler.ParcelWrapper
My FirstActivity code:
User user = responseData.getUser();
Bundle bundle = new Bundle();
bundle.putParcelable("User", Parcels.wrap(user));
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", bundle);
startActivity(intent);
My SecondActivity code:
User user = Parcels.unwrap(this.getIntent().getParcelableExtra("User"));
I suspect this is just a newbie mistake. Any constructive assistance is appreciated!
Upvotes: 1
Views: 1675
Reputation: 2566
In kotlin you can do it as follows:
val user = responseData.getUser()
val bundle = Bundle()
bundle.putParcelable("User", Parcels.wrap(user))
val intent = Intent(this@FirstActivity, SecondActivity::class.java)
intent.putExtra("User", bundle)
startActivity(intent)
and in the second activity, where you are going to get the data you can do it as follows:
val user: User = Parcels.unwrap(data?.getParcelableExtra("User"))
NOTE: When using this library you need to use Parcels.wrap
andParcels.unwrap
Although, I would recommend that if you use Kotlin
you use @Parcelize
annotation, since its implementation is very easy and your code is very clean.
If you want to implement @Parcelize
you can do it as follows:
first, in your build.gradle file add the following:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
// ... other codes
// Add this code
androidExtensions {
experimental = true
}
}
second, create your data class User with the necessary properties:
@Parcelize
data class User(
val userId: Int,
val name: String,
// more properties
) : Parcelable
Upvotes: 1
Reputation: 7083
You just need put wrapped object as argument for putExtra
, not Bundle
. Here is solution:
User user = responseData.getUser();
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("User", Parcels.wrap(user));
startActivity(intent);
On SecondActivity, in its onCreate() method do:
User user = (User) Parcels.unwrap(getIntent().getParcelableExtra("User"));
Upvotes: 5