1

I am getting an error that my late init variable, container, has not been initialised, when it is being accessed by a viewModelProvider even though I initialise it's value during onCreate(). Any help would be appreciated.

Container Initialisation code

import android.app.Application
import com.example.flashcardapp.data.AppContainer
import com.example.flashcardapp.data.AppDataContainer

class FlashcardApplication: Application() {
    lateinit var container: AppContainer
    override fun onCreate() {
        super.onCreate()
        container = AppDataContainer(this)
    }
}

I have added this application class to my manifest also:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <application
        android:name=".FlashcardApplication"
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.FlashcardApp"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.FlashcardApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Factory Initialisation code

import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewmodel.CreationExtras
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.example.flashcardapp.FlashcardApplication

object AppViewModelProvider {
    val Factory = viewModelFactory {
        initializer {
            FlashcardViewModel(FlashcardApplication().container.flashCardsRepository)
        }
    }
}
  • 1
    Need to see your ViewModel initialization and/or factory code. – Tenfour04 Jun 16 '23 at 15:10
  • You should be able to get a stacktrace from that error. That tells you when / by which path the property gets accessed prior to what you expect. – arkascha Jun 16 '23 at 16:52

1 Answers1

1

I think it's because of this part of your code:

FlashcardApplication()

You're creating a new instance of your application, not the one which had onCreate called. You need to get an instance of the existing application, not create a new one.

See this answer for details of how: Correct way to get the instance of Application in android

For example:

(activity.application as FlashcardApplication)
Ian Newson
  • 7,679
  • 2
  • 47
  • 80