1

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!

GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
Silver Sagely
  • 404
  • 1
  • 5
  • 10

2 Answers2

5

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"));
Damian Kozlak
  • 7,065
  • 10
  • 45
  • 51
  • To add, on the receiving side, to unwrap the object: `User user = (User) Parcels.unwrap(getIntent().getParcelableExtra("user"));` https://guides.codepath.com/android/Using-Parceler#wrapping-up-a-parcel – Siklab.ph Nov 08 '18 at 07:45
1

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
Juanes30
  • 2,398
  • 2
  • 24
  • 38