简体   繁体   中英

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. I implemented an ExpandableListView with a custom Adapter . I have 5 groups and each group has 1 child item. Each group element is of data type: org.myapp.ui.MyClass .

I'm now trying to get the MyClass Object of each group element when expanding it. For that I use the 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. 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

in this code line

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.

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. For example, the following code generates a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM