Fix "lateinit property binding has not been initialized" in Kotlin (Android)
kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized
- lateinit property adapter has not been initialized
- kotlin.UninitializedPropertyAccessException: lateinit property viewModel has not been initialized
- lateinit property repository has not been initialized
- Caused by: kotlin.UninitializedPropertyAccessException: lateinit property binding has not been initialized at com.example.app.HomeFragment.getBinding(HomeFragment.kt:18)
You read a lateinit property before giving it a value. With ViewBinding, assign binding in onCreate() (Activity) or onCreateView() (Fragment) before any use; elsewhere, check the initialisation order, test ::binding.isInitialized or replace lateinit with by lazy or a nullable type.
What this error means
In Kotlin, a non-nullable property must be initialised at construction. The lateinit var modifier lets you postpone that initialisation (dependency injection, Android lifecycle, test @Before) by promising the compiler it will happen before the first read. Kotlin checks that promise at runtime: reading the property before it is assigned throws UninitializedPropertyAccessException with its name. The name (binding, adapter, viewModel) tells you which assignment is missing or too late; the stack trace shows where the read happened.
Common causes
- Binding used before being created:
bindingaccessed in a property, aninit {}block or before thebinding = ...Binding.inflate(...)line inonCreate(). - Fragment: access outside the view lifecycle: a callback, observer or coroutine touching
bindingbeforeonCreateView()or afteronDestroyView(). - Injection that does not happen:
@Inject lateinit varin an Activity or Fragment without@AndroidEntryPoint(Hilt), or a Dagger component never invoked. - Tests:
@MockK/@Mock lateinit varmocks withoutMockKAnnotations.init(this),@ExtendWith(MockitoExtension::class)or a@Beforemethod creating them.
Step-by-step fix
-
Find the property and where it is read
The message gives the property name; the first
atline in your package shows where it is read. Compare with where it is assigned: the read comes first. -
Activity: create the binding at the start of onCreate
Assign
bindingright aftersuper.onCreate()and passbinding.roottosetContentView. Do not usebindingin any property initialised when the Activity is constructed.class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) binding.title.text = "Hello" } } -
Fragment: follow the view lifecycle
A Fragment’s view can be destroyed and recreated while the Fragment survives. The pattern recommended by Android: a nullable property filled in
onCreateView()and reset tonullinonDestroyView(), used only in between.class HomeFragment : Fragment() { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onDestroyView() { super.onDestroyView() _binding = null } } -
Tie observers to the view, not the Fragment
Observe LiveData and launch coroutines with
viewLifecycleOwner: they stop when the view is destroyed, so they never touch a missing binding.override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewModel.title.observe(viewLifecycleOwner) { binding.title.text = it } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.state.collect { binding.progress.isVisible = it.loading } } } } -
Test or replace lateinit
::prop.isInitializedlets you check before reading (inside the class that declares the property). For a value computed once,by lazyis safer; if absence is normal, use a nullable type with?..if (::adapter.isInitialized) { adapter.submitList(items) } // Activity only: created on first access private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) } // absence is a normal state private var player: ExoPlayer? = null player?.pause() -
Hilt and tests
With Hilt, annotate the Activity or Fragment (and the Activity hosting the Fragment) with
@AndroidEntryPoint, and the Application with@HiltAndroidApp. In tests, initialise the mocks before use.@AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var repository: UserRepository } // MockK test @MockK lateinit var api: Api @Before fun setUp() = MockKAnnotations.init(this)
Did this fix work for you?
Confirm it in one click: it will rise for the next developers stuck on the same error.
Keep it from coming back
- Keep
lateinitfor cases where a framework guarantees initialisation (lifecycle, injection,@Before); otherwise, prefer an initial value,by lazyor a nullable type. - In Fragments, never use
by lazyorlateinitfor the binding: the view is recreated and the old binding would stay in memory or be missing. - Always use
viewLifecycleOwnerto observe from a Fragment.
Frequently asked questions
How is it different from a NullPointerException?
The result is the same (a missing value), but Kotlin throws a dedicated exception that names the lateinit property, which makes diagnosis easier than an NPE.
Why does lateinit not work with Int or Boolean?
lateinit is only allowed for non-primitive, non-nullable types. For an Int, use an initial value or Delegates.notNull<Int>().
The crash happens after a screen rotation, why?
Rotation recreates the Activity and the Fragment view. A callback from the old instance (network request, timer) runs while no binding exists: tie it to viewLifecycleOwner or cancel it in onDestroyView().
Useful tools for this error
More Java, Kotlin & .NET errors
- Fix "java.lang.NullPointerException: Cannot invoke … because … is null" in Java
- Fix "UnsupportedClassVersionError: compiled by a more recent version of the Java Runtime"
- Fix "Could not resolve all files for configuration" and "Could not find" in Gradle
- Fix "Web server failed to start. Port 8080 was already in use" in Spring Boot
- Fix "Failed to configure a DataSource: 'url' attribute is not specified" in Spring Boot
- Fix "java.lang.OutOfMemoryError: Java heap space" (and GC overhead limit exceeded)
- Fix "Object reference not set to an instance of an object" (NullReferenceException) in C#