【发布时间】: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
但是
使用LocalBroadcastManager从Service发送相同类型的对象(IdList)并在onReceive()中获取它(通过相同的方法,通过在Intent上调用getSerializableExtra()并强制转换to IdList) 完美运行。
没有ClassCastException 抛出。
为什么会这样?这是 Android 中的错误吗?
编辑:
我正在使用以下方法来实例化我的IdList 对象:
public IdList getIds() {
return selectedIds.isEmpty() ? null : new IdList(selectedIds);
}
selectedIds 是一个 HashSet<Long> 对象。
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