Home > Mobile >  Do not place Android Context in static fields
Do not place Android Context in static fields

Time:12-05

I am fairly new to android development. I know that if you are not careful with your contexts, it may cause a memory leak but what I am trying to do is to use this shared preference without instantiating it. Just call it like so:

MySharedPref.getInstance(context).amsKey.toString()

Is this the right way to do it? Is this safe from memory leak? How do I make it better? Please see the MySharedPref below:

class MySharedPref(private val ctx: Context) {
    enum class key {
        AMSKEY,
        KEYOFFSET,
        DEVICEID,
        URL,
        PORT,
        LOGIN_ENDPOINT
    }

    var pref: SecurePreferences? = null

    init {
        pref = SecurePreferences(ctx, INSTANCE, "securedkeypass", true)
    }

    companion object {
        private val INSTANCE = "shared"
        private var mInstance: SharedForAmsSecured? = null
        @Synchronized
        fun getInstance(mCtx: Context): SharedForAmsSecured {
            if(mInstance == null) mInstance = SharedForAmsSecured(mCtx)
            return mInstance as SharedForAmsSecured
        }
    }

    val amsKey: String?
        get() {
            return pref?.getString(SharedForAms.key.AMSKEY.name)
        }
    val keyOffset: Int
        get() {
            var keyOffset =  pref?.getString(SharedForAms.key.KEYOFFSET.name)
            if (keyOffset != null) {
                return keyOffset.toInt()
            }
            return 0
        }
    val deviceId: String?
        get() {
            return pref?.getString(SharedForAms.key.DEVICEID.name)
        }
    val url: String?
        get() {
            return pref?.getString(SharedForAms.key.URL.name)
        }
    val loginEndpoint: String?
        get() {
            return pref?.getString(SharedForAms.key.LOGIN_ENDPOINT.name)
        }
    val port: String?
        get() {
            return pref?.getString(SharedForAms.key.PORT.name)
        }


    SAVING CODES HERE.....
}

CodePudding user response:

That should be safe. You're saving the SharedPreference, which shouldn't have a reference back to the Activity. But if you want to be extra safe, pass in context.getApplicationContext() instead. This will return the Application object, which can be safely saved in a variable as its a singleton at the application level. In fact whenever possible pass the application context rather than the Activity context for this reason.

  • Related