'Android Kotlin Singleton

I'm new to android and kotlin. But, I've read some articles about intent.

so in this project, I want to store an authKey from API to this intent but I noticed something that this authKey only used on activity that we defined on startActivity like this

startActivity(
     Intent(this, MainActivity::class.java).putExtra("credentials",
           response.getJSONObject("data").getString("authKey")
           )
)

I also read about singleton, and I want to know what is singleton and how to implement this to my authKey issue.

can any body help me with this?

thanks in advance



Solution 1:[1]

If you want to store this authKey in your Singleton object, you can implement it as follows code:

object AuthKeyStore {
    private var _authKey: String? = null
    
    val authKey: String?
        get() = _authKey
    
    fun putAuthKey(key: String) {
        _authKey = key
    }
}

Then, you can use it like this:

 /**
     * This only mock for api request returned.
     */
    fun getResponseFromApi(response: Response) {
        val data = response.getJSONObject("data")
        if (data != null) {
            val authKey = data.getString("authKey")
            AuthKeyStore.putAuthKey(authKey)
        }
    }

At last, you can get this authKey in other activities by:

  val storedAuthKey = AuthKeyStore.authKey

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 J.su