Random ClassCastExceptions to apparently random views using findViewById

Viewed 64

I don’t consider myself an experienced developer, but I can say that I’m experienced enough to avoid ClassCastExceptions on views: I know which view is linked to which id in my layout.

What’s happening is that I’m getting silly crashes along the line of:

TextView v = (TextView) view.findViewById(R.id.my_text_view);
ClassCastException: cannot cast AppCompatImageView to TextView

in different parts of the app, but not in a reproducible way (it doesn’t happen every time I do that particular action). This is driving me crazy!

Examples

// IN A AppCompatDialogFragment
// R.layout.sheet_menu is a frame with only two childs:
// a TextView and a RecyclerView.

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    return inflater.inflate(R.layout.sheet_menu, container, false);
}    

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    titleView = (TextView) view.findViewById(R.id.menu_sheet_title);
    list = (RecyclerView) view.findViewById(R.id.menu_sheet_list);

    // CLASSCASTEXCEPTION! Cannot cast AppCompatTextView to RecyclerView!
}

And another:

// IN A RECYCLERVIEW ADAPTER
// Inflating the view holder layout with
// View.inflate(mContext, R.layout.editable_story, null);

private class EditableStoryHolder extends PrimaryHolder {

    public EditableStoryHolder(View itemView) {
        super(itemView);
        ...
        likes = (TextView) itemView.findViewById(R.id.likes_count);

        // CLASSCASTEXCEPTION! Cannot cast AppCompatImageView to TextView
    }

Double Checked

I’m never explicitly calling removeView or anything else

  • I am importing the right package R class

  • The ids I’m using are unique in all the project, and I’m pretty sure they are not used inside any of my dependencies

So, what’s happening? Why does findViewById return the wrong child? I’m testing on API23, using support libraries v. 23.2.1. This is a pretty new issue. Something wrong with the appcompat layout inflater?

2 Answers

Did you introduce library that will affect the LayoutInflater or related factories? Make sure the inflater create a correct view. I think you can debug into LayoutInflater.java to make sure everything works correctly.

Related