Why does my Android app crash with a NullPointerException when initializing a variable with findViewById(R.id.******) at the beginning of the class?

Instance member variables are initialized when the instance itself is initialized. It’s too early for findViewById()

Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.

Therefore init your view references in onCreate() and after setContentView().

Leave a Comment