Shared Preferences - Android Kotlin : Best Practice and Tips.

 Hello Everyone I hope you all are doing good

Today we are doing to explore Shared Preference in android Using kotlin language.

if is most Important to save data of the application. So Shared Preference is one of the way to save data in the form of key and value.


Introduction of Shared Preferences. 

> Android Provides many ways of string data of an application. one of this way is called Shared Preferences.

> Shared Preferences allow you to save and retrieve data in the form of key, value Pair.


First Let's Create the Class for Shared Preferences.


class SharePref(context: Context) {

var pref : SharedPreferences
var editor : SharedPreferences.Editor
private var _context : Context = context

private val PREF_NAME = "sharePrefDemo"
private val PRIVATE_MODE = 0

private val IS_FIRST_TIME = "isFirstTime"
private val USER_NAME = "name"
private val USER_EMAIL = "email"

init {
pref = _context.getSharedPreferences(PREF_NAME,PRIVATE_MODE)
editor = pref.edit()
}

fun setFirstTimeLaunch(isFirstTime : Boolean){
editor.putBoolean(IS_FIRST_TIME,isFirstTime)
editor.apply()
}

fun isFirstTimeLaunch() : Boolean{
return pref.getBoolean(IS_FIRST_TIME,true)
}

fun setUserName(name : String){
editor.putString(USER_NAME,name)
editor.apply()
}

fun getUserName() : String{
return pref.getString(USER_NAME,"Admin").toString()
}

fun setUserEmail(email : String){
editor.putString(USER_EMAIL,email)
editor.apply()
}

fun getUserEmail() : String{
return pref.getString(USER_EMAIL,"Admin@gmail.com").toString()
}
}


Below is the Example : How to Use the Class.

First Create the Object of Shared Pref Class. As shown Below.

var sharePref = SharePref(application)

After That, 
To save the Data. Call set Method. As Shown Below.

sharePref.setUserName("OUR STRING")

And To Get the Data Call the get Method.

sharePref.getUserName()

To Understand it, Watch the Full Tutorial .





Post a Comment

0 Comments