【问题标题】:Strange ClassCastException when calling Intent.getSerializableExtra()调用 Intent.getSerializableExtra() 时出现奇怪的 ClassCastException
【发布时间】:2017-02-14 00:33:41
【问题描述】:

我有以下课程:

public class IdList extends ArrayList<Long> {

    public IdList() {
        super();
    }

    public IdList(Collection<Long> idCollection) {
        super(idCollection);
    }
}

我使用以下代码将此类的一个实例传递给IntentService

final Intent intent = new Intent(this, MyService.class);
intent.putExtra(MyService.IDS, ids);
startService(intent);

我使用以下代码在Service 中获取它:

IdList ids = (IdList) intent.getSerializableExtra(IDS);

这会导致以下ClassCastException

java.lang.ClassCastException: java.util.ArrayList 无法转换为 我的.package.IdList

但是

使用LocalBroadcastManagerService发送相同类型的对象(IdList)并在onReceive()中获取它(通过相同的方法,通过在Intent上调用getSerializableExtra()并强制转换to IdList) 完美运行

没有ClassCastException 抛出。

为什么会这样?这是 Android 中的错误吗?

编辑:

我正在使用以下方法来实例化我的IdList 对象:

public IdList getIds() {
    return selectedIds.isEmpty() ? null : new IdList(selectedIds);
}

selectedIds 是一个 HashSet&lt;Long&gt; 对象。

EDIT2:

我不是在寻找解决方法。我想知道为什么在通过广播发送Intent 时相同的代码工作得非常好,为什么在通过startService() 调用时它会抛出ClassCastException

【问题讨论】:

  • 在调用intent.putExtra(MyService.IDS, ids);之前如何实例化ids
  • 请显示您的代码以实例化ids 变量。
  • 有一篇关于您的问题的好文章:The mysterious case of the Bundle and the Map - 也适用于 ArrayLists ;-) 它解释了问题并提出了解决方法。
  • @gus42 你读过我的问题吗?我完全知道有几种解决方法,但我不是要求解决方法。我在问为什么在第一种情况下会抛出ClassCastException,为什么在第二种情况下相同的代码可以正常工作(当以广播形式发送Intent 时)。
  • 这是对它发生原因的解释stackoverflow.com/a/25626637/2267723

标签: android


【解决方案1】:

我不建议使用序列化 .. 使用 Parcelable 而不是那个

让你的 IdList 类 Parcelable,然后你可以得到 put/get 你的对象

intent.putParcelableArrayList(ids);

IdList ids = (IdList) intent.getParcelableArrayListExtra(IDS);

我希望这可能会有所帮助,'。

【讨论】:

  • 感谢您的回答,但我知道可能的解决方法。我不是在寻找解决方法,而是在问为什么我的问题中描述的问题会发生。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-26
相关资源
最近更新 更多