2

I need in my Singleton -> Context. I know that I can't passing argument in constructor, because object hasn't constructor.

Then I call it from my Application class.

Here is the code:

object Singleton {

    var userAgentInfo: String = UserAgentTools.buildUserAgent(context)

    fun initializeSdk() {
        AuthenticatorApiManager.initializeSdk(userAgentInfo)
    }
}
Twisha Kotecha
  • 1,082
  • 1
  • 4
  • 18
Morozov
  • 4,968
  • 6
  • 39
  • 70

3 Answers3

1

Move the initialization of userAgentInfo to the initializeSDK method, and send the Context as an argument, make sure to send the ApplicationContext.

object Singleton {

    var userAgentInfo: String? = null

    fun initializeSdk(context: Context) {
        userAgentInfo = UserAgentTools.buildUserAgent(context)
        AuthenticatorApiManager.initializeSdk(userAgentInfo)
    }
}
Morozov
  • 4,968
  • 6
  • 39
  • 70
Omar HossamEldin
  • 3,033
  • 1
  • 25
  • 51
  • It can causes memory leak. see [https://stackoverflow.com/questions/56102382/is-passing-context-as-a-parameter-to-a-method-in-a-singleton-class-causes-memory] – Dipakk Sharma Feb 20 '20 at 11:05
  • It will cause memory leak in case the context is an activity or something similar, but the application context is already in memory in the whole life cycle of the application , and the singletone will be destroyed when the application is destroyed with the application context – Omar HossamEldin Feb 20 '20 at 11:07
  • Yeah. If you passing application context then will not be any problem. – Dipakk Sharma Feb 20 '20 at 11:09
  • Use `context.applicationContext` within this function to be safe. Then you don't have to worry about what kind of context is passed in. – Tenfour04 Feb 20 '20 at 14:02
0

Make Application class and write below code.

companion object {
    private lateinit var sInstance: ApplicationClass
    fun getInstance(): ApplicationClass {
        return sInstance
    }
}

Use in object like below.

ApplicationClass.getInstance()
Dipakk Sharma
  • 976
  • 1
  • 8
  • 11
0

You can use context in your Singleton class using Application class instance.here it is

Komal
  • 328
  • 3
  • 15