Shared Preferences in Android Development


In Android development, SharedPreferences is a key-value pair storage mechanism that allows you to store simple data in the form of primitive data types such as boolean, int, float, long, and String. It is commonly used for saving application settings, user preferences, and other small pieces of data that should persist across app sessions.

1. Storing Data using SharedPreferences

SharedPreferences allows you to store data in an XML file in the app’s internal storage. The data is saved in the form of key-value pairs.

Example 1: Saving Data to SharedPreferences

    class MainActivity : AppCompatActivity() {

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

            // Get the SharedPreferences object
            val sharedPref = getSharedPreferences("MyPreferences", MODE_PRIVATE)

            // Save data to SharedPreferences
            val editor = sharedPref.edit()
            editor.putString("username", "JohnDoe")
            editor.putInt("userAge", 30)
            editor.apply() // Apply changes
        }
    }
        

In this example:

  • getSharedPreferences("MyPreferences", MODE_PRIVATE) is used to get the SharedPreferences instance. The first parameter is the name of the preferences file, and the second parameter is the mode of operation (in this case, private mode).
  • editor.putString("username", "JohnDoe") saves a string with the key "username".
  • editor.putInt("userAge", 30) saves an integer with the key "userAge".
  • editor.apply() commits the changes asynchronously, saving the data to SharedPreferences.

2. Retrieving Data from SharedPreferences

After saving data to SharedPreferences, you can easily retrieve it using the appropriate get methods for each data type (e.g., getString, getInt, etc.).

Example 2: Retrieving Data from SharedPreferences

    class MainActivity : AppCompatActivity() {

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

            // Get the SharedPreferences object
            val sharedPref = getSharedPreferences("MyPreferences", MODE_PRIVATE)

            // Retrieve data from SharedPreferences
            val username = sharedPref.getString("username", "defaultName")
            val userAge = sharedPref.getInt("userAge", 0)

            // Display the retrieved data
            Toast.makeText(this, "Username: $username, Age: $userAge", Toast.LENGTH_LONG).show()
        }
    }
        

In this example:

  • sharedPref.getString("username", "defaultName") retrieves the string value associated with the key "username", and if the key is not found, it returns the default value "defaultName".
  • sharedPref.getInt("userAge", 0) retrieves the integer value associated with the key "userAge", and if the key is not found, it returns the default value 0.

3. Clearing or Removing Data from SharedPreferences

You can also clear all the data or remove specific key-value pairs from SharedPreferences when you no longer need them.

Example 3: Clearing Data from SharedPreferences

    class MainActivity : AppCompatActivity() {

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

            // Get the SharedPreferences object
            val sharedPref = getSharedPreferences("MyPreferences", MODE_PRIVATE)

            // Remove specific data from SharedPreferences
            val editor = sharedPref.edit()
            editor.remove("username") // Remove the 'username' key-value pair
            editor.apply()

            // Clear all data from SharedPreferences
            val editorClear = sharedPref.edit()
            editorClear.clear() // Clears all the saved data
            editorClear.apply()
        }
    }
        

In this example:

  • editor.remove("username") removes the value associated with the key "username".
  • editorClear.clear() clears all the saved data in the SharedPreferences file.

4. Using SharedPreferences for Boolean Values

SharedPreferences can be particularly useful for storing simple flags or settings in your app, such as whether a user is logged in or if a tutorial has been shown.

Example 4: Storing Boolean Value

    class MainActivity : AppCompatActivity() {

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

            // Get the SharedPreferences object
            val sharedPref = getSharedPreferences("MyPreferences", MODE_PRIVATE)

            // Store a boolean value indicating if the user has seen the tutorial
            val editor = sharedPref.edit()
            editor.putBoolean("hasSeenTutorial", true)
            editor.apply()
        }
    }
        

In this example:

  • editor.putBoolean("hasSeenTutorial", true) stores a boolean value indicating that the user has seen the tutorial.

5. Conclusion

SharedPreferences provides a simple way to store and retrieve small amounts of data in Android applications. It is ideal for scenarios like saving user preferences, flags, settings, and other data that needs to persist across app sessions. The key-value pair structure of SharedPreferences makes it easy to manage and retrieve data in a way that is lightweight and fast.





Advertisement