Home > database >  lateinit property for String has not been initialized
lateinit property for String has not been initialized

Time:06-05

I just started to learn Hilt for dependency injection,and was on field injection and i am getting this following error even though i have initialised, lateinit property someRandomString has not been initialized

Code for Appmodule class

@Module
@InstallIn(SingletonComponent::class)
object AppModule{

    @Singleton
    @Provides
    fun provideApplication(@ApplicationContext app: Context): BaseApplication{
        return app as BaseApplication
    }

    /* provideRandomString is a dependency we can inject to something else.
       This string object is gonna exist as long as the Application is alive */
    @Singleton
    @Provides
    fun provideRandomString(): String{
        return "Hey look a random string"
    }

}

Code for Activity class

@AndroidEntryPoint
class HiltTestActivity : AppCompatActivity() {
    private val TAG: String = "AppDebug"

    /* Hilt will be looking to any modules for any dependencies that has type string and will inject here */
    @Inject
    lateinit var someRandomString:String

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_hilt_test)

        Log.d(TAG, "onCreate: $someRandomString")
    }
}

stack trace

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property someRandomString has not been initialized
        at com.example.mvvmtester.view.HiltTestActivity.getSomeRandomString(HiltTestActivity.kt:17)
        at com.example.mvvmtester.view.HiltTestActivity.onCreate(HiltTestActivity.kt:23)
        at android.app.Activity.performCreate(Activity.java:8000)
        at android.app.Activity.performCreate(Activity.java:7984)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1309)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3422)

CodePudding user response:

Add the curly braces to someRandomString in your log statement. That should fix it.

Yours: Log.d(TAG, "onCreate: $someRandomString")

Try: Log.d(TAG, "onCreate: ${someRandomString}")

CodePudding user response:

The Issue was with my project gradle classpath plugin version, just updated it to the latest and solved

buildscript {

dependencies {

    classpath 'com.google.dagger:hilt-android-gradle-plugin:2.42'
}

}

  • Related