Shared Preferences & Data Saving in Android

Shared Preferences & Data Saving in Android

Shared Preferences allows us to save & retrieve data in the form of key:value pair

  • Data belonging to primitive data types(integer, float, boolean, string, long)

  • Shared Preferences files are managed by an Android Framework and can be accessed anywhere within the application to read and write data

E.g. - Remember Me Checkbox in Login, etc.

Implementation -

//MainActivity.kt
import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast

class MainActivity : AppCompatActivity() {
    lateinit var userName : EditText
    lateinit var userCount : Button

    var name : String? = null
    var count : Int? = null

    var countNum = 0

    lateinit var sharedPreferences : SharedPreferences

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        userName = findViewById(R.id.nameInput)
        userCount = findViewById(R.id.countBtn)

        userCount.setOnClickListener{
            countNum++
            userCount.setText(""+countNum)
        }
    }

    override fun onPause() {
//onPause method is the best time to save the values 
        super.onPause()
        sharedPreferences = this.getSharedPreferences("saveData", Context.MODE_PRIVATE)
//getSharedPrefereces used to get the instance of SharedPreference
//where saveData is the name of the file
//MODE_PRIVATE makes the created file only accessible by the calling application
        name = userName.text.toString()
        count = userCount.text.toString().toInt()

        val editor : Editor = sharedPreferences.edit()
//Editor is used to edit the values in the SharedPreference
        editor.putString("NAME:",name)
        editor.putInt("COUNT:", count!!)
        editor.apply() 
//apply() saves the values

        Toast.makeText(this,"DATA SAVED",Toast.LENGTH_SHORT).show()
    }

    override fun onResume() {
//onResume is the best time to retreive data
//as onCreate isn't called when acitivity regains focus
        super.onResume()

        sharedPreferences = this.getSharedPreferences("saveData", Context.MODE_PRIVATE)

        name = sharedPreferences.getString("NAME:",null)
        count = sharedPreferences.getInt("COUNT:",0)

        userName.setText(name)
        userCount.setText(""+count)
    }
}