[Solved] Android code without casting


Because if you want to assign a supertype to a specific subtype variable, you need to downcast it to the actual type. Much of the Android framework is from an era before Java generics was available.

Is there some better way to approach this?

If you only need the View from a findViewById() return, make the variable type a View.

You can also use generics to hide the casts. For example:

public <T extends View> T getView(@ResInt int resId) {
    return (T) findViewById(resId);
}

This way you can assign like

EditText yourEditText = getView(R.id.yourEditText);

and the correct type is automatically inferred.

especially a way you can detect where you did go wrong before runtime

It’s still runtime and you’ll get ClassCastException if R.id.yourEditText is in fact not an EditText.

For getSystemService() there’s already a method like that in API level 23. Implementing this pattern for older API levels is left as an exercise to the reader 🙂


It’s mostly casting errors when you Replace in the layout file a LineairLayout -> RelativeLayout and forget to do it in the code. And suddenly everything breaks at run time while my editor does not show any errors and the code just compiles

Note that Android Lint will detect many errors like this and will report “Unexpected cast” errors.

0

solved Android code without casting