[英]java.lang.ClassCastException: java.lang.String cannot be cast to org.myapp.ui.MyClass
I am new to android developing and I encountered a problem which I can't solve. 我是android开发的新手,遇到了无法解决的问题。 I implemented an
ExpandableListView
with a custom Adapter
. 我使用自定义
Adapter
实现了ExpandableListView
。 I have 5 groups and each group has 1 child item. 我有5组,每组有1个子项。 Each group element is of data type:
org.myapp.ui.MyClass
. 每个组元素的数据类型为:
org.myapp.ui.MyClass
。
I'm now trying to get the MyClass
Object of each group element when expanding it. 我现在正在尝试在扩展每个组元素时获取
MyClass
对象。 For that I use the setOnGroupExpandListener
: 为此,我使用
setOnGroupExpandListener
:
lv.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
public void onGroupExpand (int groupPosition){
MyClass selected = (MyClass)lv.getAdapter().getItem(groupPosition);
servId = selected.getServiceId();
// Do more stuff here
}
});
When I now test this code in the emulator, i get the following ClassCastException
, but only after expanding some groups in the ExpandableListView
a few times. 现在,当我在模拟器中测试此代码时,会得到以下
ClassCastException
,但仅在ExpandableListView
的某些组ExpandableListView
了几次之后。 So for a few times it works and then suddenly it doesn't and i get this exception. 所以有几次它起作用,然后突然不起作用,我得到了这个异常。
java.lang.ClassCastException: java.lang.String cannot be cast to org.myapp.ui.MyClass
java.lang.ClassCastException:无法将java.lang.String强制转换为org.myapp.ui.MyClass
in this code line 在此代码行中
MyClass selected = (MyClass)lv.getAdapter().getItem(groupPosition);
MyClass selected =(MyClass)lv.getAdapter()。getItem(groupPosition);
If anyone has an idea why this happens (but only after expanding a few groups in the ExpandableListView
), please let me know. 如果有人知道为什么会发生这种情况(但仅在
ExpandableListView
扩展了几个组之后),请告诉我。
Taken from oracle docs, ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. 取自oracle文档,ClassCastException被抛出以指示代码已尝试将对象强制转换为不是实例的子类。 For example, the following code generates a ClassCastException:
例如,以下代码生成ClassCastException:
Object x = new Integer(0);
System.out.println((String)x);
In your case you are trying to convert a string to a custom class which will never pass because the line lv.getAdapter().getItem(groupPosition)
gives String instead of MyClass Object. 在您的情况下,您尝试将字符串转换为永远不会通过的自定义类,因为
lv.getAdapter().getItem(groupPosition)
给出的是String而不是MyClass Object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.