Null pointer Exception – findViewById()

findViewById() returns a View if it exists in the layout you provided in setContentView(), otherwise it returns null and that’s what happening to you. Note that if you don’t setContentView(), and don’t have a valid view to findViewById() on, findViewById() will always return null until you call setContentView().

This also means variables in the top-level trigger an NPE, because they’re called before onCreate(), and by extension, before setContentView(). See also the activity lifecycle

Example if you setContentView(R.layout.activity_first); and then call findViewById(R.id.first_View); it will return a View which is your layout.

But if you call findViewById(R.id.second_View); before setContentView(), it will return null since there is not a view in your activity_first.xml layout called @+id/second_View.

Leave a Comment