NullPointerException accessing views in onCreate() NullPointerException accessing views in onCreate() java java

NullPointerException accessing views in onCreate()


The tutorial is probably outdated, attempting to create an activity-based UI instead of the fragment-based UI preferred by wizard-generated code.

The view is in the fragment layout (fragment_main.xml) and not in the activity layout (activity_main.xml). onCreate() is too early in the lifecycle to find it in the activity view hierarchy, and a null is returned. Invoking a method on null causes the NPE.

The preferred solution is to move the code to the fragment onCreateView(), calling findViewById() on the inflated fragment layout rootView:

@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,    Bundle savedInstanceState) {  View rootView = inflater.inflate(R.layout.fragment_main, container,      false);  View something = rootView.findViewById(R.id.something); // not activity findViewById()  something.setOnClickListener(new View.OnClickListener() { ... });  return rootView;}

As a side note, the fragment layout will eventually be a part of the activity view hierarchy and discoverable with activity findViewById() but only after the fragment transaction has been run. Pending fragment transactions get executed in super.onStart() after onCreate().


Try OnStart() method and just use

View view = getView().findViewById(R.id.something);

or Declare any View using getView().findViewById method in onStart()

Declare click listener on view by anyView.setOnClickListener(this);


Try to shift your accessing views to the onViewCreated method of fragment because sometimes when you try to access the views in onCreate method they are not rendered at the time resulting null pointer exception.

 @Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) {    super.onViewCreated(view, savedInstanceState);     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();    } }