Cannot pass custom Object in an Intent: The Method Put Extra is Ambiguous for the type Intent

耗尽温柔 提交于 2019-11-27 13:52:47
faylon

The first error: 'The Method Put Extra is Ambiguous for the type Intent'.

The class Car is both Serializable and Parcelable, the compiler doesn't know whether to use putExtra(Serializable s) or putExtra(Parcelable p) to handle your request. So you have to cast your Car to one of them when using Intent.putExtra().

Intent.putExtra("car", (Parcelable)myCarObject);
Intent.putExtra("car", (Serializable)myCarObject);

The second error: java.lang.ClassCastException: java.util.ArrayList

You put the Car object in a ArrayList and use putExtra to send to the next activity. An ArrayList is not Parcelable but only Serializable. The putExtra(ArrayList) works as putExtra(Serializable), but you read it by getParcelable(). An ArrayList cannot be cast to Parcelable.

Khaled Annajar

I use this

In the sender Activiy

Intent intent = new Intent(activity, MyActivity.class);

Bundle bundle = new Bundle();
bundle.putSerializable("my object", myObject);

intent.putExtras(bundle);

startActivity(intent);

In the receiver:

myObject = (MyObject) getIntent().getExtras().getSerializable("my object");

Works fine for me try it. But the object must be serializable :)

This is how I pass my objects which are serializable, I believe it should work the same way for parcelable. Pass:

Intent intent=new Intent(OverviewActivity.this,CarDetailTabActivity.class);         
            intent.putExtra("CAR",myCarObject);
            startActivity(intent);  

Receive:

Car carObject=(Car)getIntent().getSerializableExtra("CAR");

Car:

import java.io.Serializable;

public class Car implements Serializable {

private static final long serialVersionUID = 1L;
......

getIntent().getExtras() returns extra Bundle from your intent, not your data. To get your list use getIntent().getParcelableArrayListExtra("Car")

Solution : implement Serializable interface by your class like implements Serializable

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