java.lang.ClassCastException: java.lang.String cannot be cast to org.myapp.ui.MyClass

1k views Asked by At

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.

1

There are 1 answers

3
Bhargav Kumar R On

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.