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
.
Emphasis added
For those cases within an Activity class.
Activity.findViewById(int id)
Finds a view that was identified by the
id
attribute from the XML that was processed inonCreate(Bundle)
.
Otherwise, such as an Fragment, Adapter, a View
from a LayoutInflater
, etc.
View.findViewById(int id)
Look for a child view with the given
id
. If this view has the given id, return this view.
Either case,
Returns
The view if found ornull
otherwise.
Now, re-check your XML files. Make sure you put the right value into setContentView
or inflater.inflate
.
In the case of an Activity, call findViewById
after setContentView
.
Then, make sure there is a View you are looking for with android:id="@+id/..."
in that layout. Make sure the +
is at @+id
, which will add the resource to the R.id
values to ensure you can find it from Java.