0

in order to use application context anywhere, I use this code:

class App : Application() {
    companion object {
        lateinit var instance: App private set
        fun isInstanceInitialized() = ::instance.isInitialized
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }
}

But sometimes it throws an error.

kotlin.UninitializedPropertyAccessException: lateinit property instance has not been initialized

As suggested here, setting a delay (before calling App.instance) helps, but I would like to call something without having to wait for a set delay. And besides that, isInstanceInitialzed method always returns false..

What can I write in the beginning of onCreate method in MainActivity, in order to make sure that the instance variable is initialized?

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
jonadv
  • 434
  • 6
  • 16
  • 1
    why do you need application context so badly ? – a_local_nobody Jul 19 '21 at 09:39
  • 1
    you are doing something wrong(calling `App.instance` too early) ... take a look at [this](https://developer.android.com/topic/libraries/app-startup) – Selvin Jul 19 '21 at 09:46
  • cause even though my app is just 1 activity, it has 800 lines of code in one module which I want to separate into separate modules for overview and readability. Seperating into several modules requires acces to things as string resources, but also just to the Main acitivity (context). For example one of the separations is a UserInformer class which basically only shows a Toast, but still is about 30 lines of code. Another example, needed with this separation, is that it makes it easy to acces string resources from anywhere (as shown in this answer https://stackoverflow.com/a/58627769/6544310) – jonadv Jul 19 '21 at 09:49
  • 1
    nothing you've said there explains to me why you need application context, you just need context as a dependency and it doesn't have to be application context. sounds like all your problems are resolved by just using a dependency injection framework, or just handling your dependencies better – a_local_nobody Jul 19 '21 at 09:52
  • so the problem is that I don't understand what "context as a dependency" and "using a dependency injection framework" means, thus coming to this 'solution' (to run into another problem). I know making an instance of app context globally is 'dirty', but as my app is small and just 1 activity, I think it is acceptable – jonadv Jul 19 '21 at 09:56
  • 2
    i'm saying, instead of having to use `App.instance.whatever`, you should be able to just write methods which take in context as a parameter, then you can supply that context when you call the method from the activity. fun `foo(context:Context)` and then you can pass in context – a_local_nobody Jul 19 '21 at 10:07

0 Answers0