Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Shared Preferences?
2.1.
Shared Preferences Basics
2.2.
Writing to Shared Preferences
2.3.
Reading from Shared Preferences
2.4.
Managing Shared Preferences
3.
Shared Preferences in a Real-world Scenario
4.
Frequently Asked Questions
4.1.
Q: Can I store complex objects in Shared Preferences?
4.2.
Q: Are Shared Preferences cleared when the app is updated?
4.3.
Q: How secure are Shared Preferences?
5.
Conclusion
Last Updated: Mar 27, 2024

Shared Preferences In Android

Author Gunjan Batra
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

In Android application development, it's often necessary to persist simple data across application instances, such as user preferences or app settings. For this purpose, Android provides a lightweight mechanism known as Shared Preferences. 

Shared Preferences In Android

This article will delve into the concept of Shared Preferences, its use, and the best practices associated with it.

What are Shared Preferences?

Shared Preferences is an API provided by Android that allows you to store private primitive data in key-value pairs. The data persisted using Shared Preferences will be available even after your application is killed or device rebooted.

Shared Preferences Basics

To use Shared Preferences, we need to call a method getSharedPreferences() that returns a Shared Preference instance pointing to the file that contains the values of preferences.

Writing to Shared Preferences

You can save data to Shared Preferences using Editor object. The steps are as follows:

  • Call edit() on your SharedPreferences to get an instance of SharedPreferences.Editor.
     
  • Add data to the Editor.
     
  • Commit the changes to the preference file.

Below is a sample code snippet showing these steps:

SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref",MODE_PRIVATE);
SharedPreferences.Editor myEdit = sharedPreferences.edit();
myEdit.putString("name", "OpenAI");
myEdit.commit();

Reading from Shared Preferences

To retrieve values from Shared Preferences:

Call the appropriate method such as getString() or getInt(), providing the key and the default value for that key.

Here's an example:

SharedPreferences sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE);
String name = sharedPreferences.getString("name", "");

Managing Shared Preferences

It's crucial to manage Shared Preferences effectively. Some of the best practices include:

Don't store large amounts of data: Shared Preferences are designed for small data, such as user settings or app configuration details. Large data can affect the performance of your app.

Avoid Storing Sensitive Data: Shared Preferences data is not encrypted. Hence, it's not a safe place to store sensitive data like passwords or personal user information.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Shared Preferences in a Real-world Scenario

Let's take an example of an app that changes its background color based on user's preference:

public class MainActivity extends AppCompatActivity {
    private RelativeLayout layout;
    private Button button;
    private SharedPreferences sharedPreferences;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        layout = findViewById(R.id.layout);
        button = findViewById(R.id.button);


        sharedPreferences = getSharedPreferences("MySharedPref", MODE_PRIVATE);
        String color = sharedPreferences.getString("color", "white");
        if (color.equals("blue")) {
            layout.setBackgroundColor(Color.BLUE);
        } else {
            layout.setBackgroundColor(Color.WHITE);
        }


        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout.setBackgroundColor(Color.BLUE);
                SharedPreferences.Editor myEdit = sharedPreferences.edit();
                myEdit.putString("color", "blue");
                myEdit.apply();
            }
        });
    }
}

Frequently Asked Questions

Q: Can I store complex objects in Shared Preferences?

No, Shared Preferences only supports primitive data types: booleans, floats, ints, longs, and strings.

Q: Are Shared Preferences cleared when the app is updated?

No, Shared Preferences persist across user sessions and even app updates.

Q: How secure are Shared Preferences?

Shared Preferences are stored as a file in the app's private folder, so they cannot be accessed directly by other apps. However, the data is not encrypted.

Conclusion

Shared Preferences is a straightforward yet powerful tool for persisting small sets of data. It is easy to use, lightweight, and perfectly suitable for storing simple data like user settings. However, it's important to use it judiciously and avoid storing large or sensitive data. As with many tools in Android, understanding Shared Preferences and using it effectively can greatly enhance the functionality and user experience of your applications.

You may refer to our Guided Path on Code Ninjas Studios for enhancing your skill set on DSACompetitive ProgrammingSystem Design, etc. Check out essential interview questions, practice our available mock tests, look at the interview bundle for interview preparations, and so much more!

Happy Learning!

Previous article
Android Hello World Application
Next article
Android App Components and Folder Structure
Live masterclass