This is a canonical question for a problem frequently posted on StackOverflow.
I'm following a tutorial. I've created a new activity using a wizard. I get NullPointerException
when attempting to call a method on View
s obtained with findViewById()
in my activity onCreate()
.
Activity onCreate()
:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View something = findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
Layout XML (fragment_main.xml
):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="packagename.MainActivity$PlaceholderFragment" >
<View
android:layout_width="100dp"
android:layout_height="100dp"
android:id="@+id/something" />
</RelativeLayout>
I've got the same
NullPointerException
initializing a listener after callingfindViewById()
onCreate()
andonCreateView()
methods.But when I've used the
onActivityCreated(Bundle savedInstanceState) {...}
it works. So, I could access theGroupView
and set my listener.I hope it be helpful.
Since you have declared your View in the
fragment_main.xml
,move that piece of code where you get the NPE in theonCreateView()
method of the fragment. This should solve the issue.Use onViewCreated() Method whenever using or calling views from fragments.
The view "something" is in fragment and not in activity, so instead of accessing it in activity you must access it in the fragment class like
In PlaceholderFragment.class
Agreed, this is a typical error because people often don't really understand how Fragments work when they begin working on Android development. To alleviate confusion, I created a simple example code that I originally posted on Application is stopped in android emulator , but I posted it here as well.
An example is the following:
activity_container.xml:
ExampleFragment:
fragment_example.xml:
And that should be a valid example, it shows how you can use an Activity to display a Fragment, and handle events in that Fragment. And also how to communicate with the containing Activity.
You are trying to access UI elements in the
onCreate()
but , it is too early to access them , since in fragment views can be created inonCreateView()
method. AndonActivityCreated()
method is reliable to handle any actions on them, since activity is fully loaded in this state.