Search code examples
androidkotlinoncreateapplicationcontext

Kotlin : Why some code only works within OnCreate of Activity


I'm a beginner in dev trying to get my head around some concepts. Could someone awesome please help me the below? It's driving me nuts!!

Please take a look at this piece of code:

    val csvRawText = applicationContext.assets.open("sgsraagadata.csv").bufferedReader().use {
        it.readText()
    }

This is how I'm reading my csv file that I've imported into Assets. Can you please help me understand:

  1. Why this code doesn't work (fatal null pointer error) when I run it outside of OnCreate along with my other variable declarations and initialisations?
  2. And why it also doesn't work inside a separate class that is not an Activity? I have a separate class called csvFile which I wanted to house this code, and no matter where I put it, it doesn't work.

Solution

  • It happens because the applicationContext is not initialized before the onCreate() method get called. In other classes you can't get the applicationContext because only the classes who represents a context, like an activity class or a service, returns it to you