How to Fix Android NullPointerException on findViewById
In this tutorial, you'll learn about How to Fix Android NullPointerException on findViewById. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your app crashes with:
java.lang.NullPointerException: Attempt to invoke virtual method
'void android.widget.Button.setText(java.lang.CharSequence)' on a null object reference
The findViewById call returned null because the view ID does not exist in the current layout, or the layout was not set.
Quick Fix
Step 1: Verify the layout is set before accessing views
// Wrong - accessing view before setting layout
setContentView(R.layout.activity_main)
// OK
val button = findViewById<Button>(R.id.my_button)
In a Fragment, ensure onCreateView returns the correct layout:
override fun onCreateView(...): View? {
return inflater.inflate(R.layout.fragment_demo, container, false)
}
Step 2: Check the view ID exists in the XML
Open res/layout/activity_main.xml and verify the ID:
<Button
android:id="@+id/my_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
A typo in the ID (@+id/my_buton vs R.id.my_button) causes findViewById to return null.
Step 3: Use view binding to avoid null views
In app/build.gradle:
android {
buildFeatures {
viewBinding true
}
}
Then in your Activity:
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.myButton.text = "Click me" // type-safe, never null
}
Step 4: Check for included layouts
If views are in an <include> tag, the included layout's root must have an ID:
<include
layout="@layout/partial_header"
android:id="@+id/header" />
Access the child view via the parent ID:
val headerText = findViewById<TextView>(R.id.header).findViewById<TextView>(R.id.title_text)
Step 5: Ensure views exist in the current layout
A Dialog must use dialog.findViewById on its own layout, not the Activity layout:
val dialog = Dialog(this)
dialog.setContentView(R.layout.dialog_custom)
val title = dialog.findViewById<TextView>(R.id.dialog_title)
Prevention
- Use View Binding for compile-time safety.
- Always call
setContentViewor return a valid view fromonCreateViewbefore accessing views. - Keep view IDs unique across the entire project.
Common Mistakes with null pointer view
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world Android code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
DodaTech Tool Reference
Doda Browser's Layout Inspector can capture the view hierarchy of any running app, making it easy to confirm which views are inflated at runtime. Durga Antivirus Pro checks for null-pointer vulnerabilities in decompiled APKs.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro