Code Mastery Guides

Your Journey to Mastering Programming Languages: Where Knowledge Meets Code

Understanding Shared Preferences in Android ~ Kotlin and Java

Introduction:

When developing Android applications, it’s common to need a way to store small pieces of data persistently. In this blog post, we delve into the realm of SharedPreferences, a powerful tool tailored for handling small, persistent data in Android applications. Throughout this exploration, we’ll unravel the process of creating SharedPreferences, assigning values to them, deleting specific values, and mastering other essential operations that contribute to efficient data management in your Android projects.

Shared Preferences is a simple key-value pair storage system provided by the Android framework. It allows you to store primitive data types (such as booleans, floats, ints, longs, and strings) persistently across app sessions. Shared Preferences are particularly useful for saving settings, user preferences, and other lightweight data.

Creating SharedPreferences:

Navigate to your activity or fragment, and integrate the following code to instantiate a SharedPreferences object using the getSharedPreferences method. If you are working within a fragment, ensure you precede the function with requireContext():

Java:


    //In Activity use following code
        SharedPreferences activityPreferences = 
                getSharedPreferences("MyApplication", Context.MODE_PRIVATE);
    
    //In fragment use following code
        SharedPreferences sharedPreferences = 
                requireContext().getSharedPreferences("MyApplication", Context.MODE_PRIVATE);

Kotlin:


     //In Activity use following code
        val sharedPreferences =
            getSharedPreferences("MyApplication", Context.MODE_PRIVATE)
            

    //In Fragment use following code
        val sharedPreferences =
            requireContext().getSharedPreferences("MyApplication", Context.MODE_PRIVATE)

This code snippet initializes a SharedPreferences object named “YourPrefsName” with a private mode, ensuring its accessibility is confined to your application. If you’re working within a fragment, don’t forget to use requireContext() before invoking getSharedPreferences. This establishes a secure and application-specific storage space for your data.

Add Value to SharedPreferences:

To facilitate modifications like adding, deleting, or editing values in SharedPreferences, you’ll need to utilize the SharedPreferences Editor. In the following section, we’ll delve into the intricacies of adding values to SharedPreferences, enhancing your understanding of this fundamental aspect of Android app data management.

Java:


     SharedPreferences.Editor editor = activityPreferences.edit();

    //Add String Value
    editor.putString("string_key", "Enter Value Here");

    //Add Integer Value
    editor.putInt("int_key", 1);

    //Add Boolean Value
    editor.putBoolean("boolean_key", false);

    editor.apply();

Kotlin:


        val editor = sharedPreferences.edit()

        //Add String Value
        editor.putString("string_key", "Enter Value Here")

        //Add Integer Value
        editor.putInt("integer_key", 1)
        
        //Add Boolean Value
        editor.putBoolean("boolean_key", false)
        
        editor.apply()

You can useputLong, and putFloat in the above code. Don’t forget to use apply function to perform the editor action.

Edit/Update Value of SharedPreferences:

Additionally, you can edit or update a value by employing the same method described above. When editing a value, it is crucial to ensure the usage of the same key associated with the desired value. This approach guarantees seamless modifications to existing SharedPreferences data, maintaining the integrity of your stored information.

Java:


        SharedPreferences.Editor editor = activityPreferences.edit();

        editor.putString("string_key", "New String Value");
        
        editor.apply();

Kotlin:


        val editor = activityPreferences.edit()

        editor.putString("string_key", "New String Value")
        
        editor.apply()

Delete Value of SharedPreferences:

You just need to use the remove method to delete the value from SharedPreferences:


    editor.remove("integer_key")

Clear all Values of SharedPreferences:

Use the below code to completely delete all values from SharedPreferences.


    editor.clear()

Best Practices:

  • Choose a Unique Name: When creating your SharedPreferences, choose a unique name for better separation and avoid conflicts with other apps.
  • Be Mindful of Data Size: Shared Preferences are suitable for small amounts of data. For larger datasets, consider other storage options, such as a local database or Room Database.

Conclusion:

Shared Preferences in Kotlin for Android provide a convenient way to store and retrieve small amounts of persistent data. By following these simple steps, you can enhance your app by saving user preferences and settings effectively. Remember to use Shared Preferences judiciously and consider alternative storage solutions for more extensive data requirements.

To learn more about SharedPreferences, Click Here.

Understanding Shared Preferences in Android ~ Kotlin and Java

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top