June 21, 2018

SharedPreferences in Kotlin

                 On this blog I am going to explain how to use SharedPreferences in Android Kotlin. As you knew SharedPreferences is used for saving application data as key-value pair. You can find more about shared prederance from Here.


Here I am creating a new class AppSettings. With the help of this class we are going to save a String, Boolean, Int values..


Java Code


class AppSettings(context: Context) {
    val PREFS_FILENAME = "BMatesTechnologies"

    val UserID = "UserID"  //Int value
    val LoginStatus = "LoginStatus" //Boolean Value
    val UserEmail = "Email"  //String Value

    val prefs: SharedPreferences = context.getSharedPreferences(PREFS_FILENAME,
 Context.MODE_PRIVATE);


    var userId: Int
        get() = prefs.getInt(UserID,0 )
        set(value) = prefs.edit().putInt(UserID, 0).apply()

    var loginStatus: Boolean
        get() = prefs.getBoolean(LoginStatus, false)
        set(value) = prefs.edit().putBoolean(LoginStatus, value).apply()

    var email: String
        get() = prefs.getString(UserEmail, null)
        set(value) = prefs.edit().putString(UserEmail, value).apply()

}


I am using the following method to save or get values from the shared Preferance.


Initilize AppSettings

     var appSettings: AppSettings? = null


Declaration

     appSettings = AppSettings(applicationContext)


Assigning Values


     appSettings!!.loginStatus = true

     appSettings!!.email = "shidhi.shidhin@gmail.com"

     appSettings!!.userId = 1






---------------
Thanks For Reading, Wish you a Happy Coding....