Question
What causes NullPointerException when using findViewById() in the onCreate() method of an Android activity?
// Example code where NPE occurs
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View something = findViewById(R.id.something); // Possible NullPointerException
something.setOnClickListener(new View.OnClickListener() { ... }); // NPE HERE
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
Answer
The NullPointerException (NPE) in this scenario is often caused by calling findViewById() on views that are set in a layout that is not currently inflated. In the provided context, this happens because the view 'something' is located in the layout defined for the PlaceholderFragment, not in the activity's layout.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
View something = view.findViewById(R.id.something);
something.setOnClickListener(new View.OnClickListener() { ... });
return view;
}
Causes
- The ID used in findViewById() does not exist in the current layout.
- The view is being accessed before it has been instantiated or inflated.
- Incorrectly referencing the fragment layout instead of the activity layout.
Solutions
- Ensure that the ID used in findViewById() matches a view in the currently set content layout.
- Move the view reference and initialization code to the fragment's onCreateView() method where the layout is inflated.
- Use getView() from fragment to access views once the fragment's layout is attached.
Common Mistakes
Mistake: Accessing views outside of the fragment's lifecycle methods.
Solution: Always perform view lookups in onCreateView() of the fragment.
Mistake: Assuming all views are accessible in the activity without checking the appropriate layout.
Solution: Verify that the views are part of the inflated layout in use.
Helpers
- NullPointerException
- findViewById()
- onCreate()
- Android programming
- PlaceholderFragment
- activity lifecycle