Using SharedPreferences in Android to store data

We are going to talk about SharedPreferences in Android. It is a place where you can store data; this is an XML file with values stored in it. Almost all applications need to store some data. Data can be a lot of different things; it can be just an email for a registration form, the last opened screen, nickname for a game or a proper database. If you are not ready to use a full-blown database yet (or just don’t need it), you can use SharedPreferences to store simple data. But you can also store a bit more complex data if you want. 

SharedPreferences are not intended to store a lot of data, there is no limit per se (since it is an xml file), but for larger sets of data, I would suggest using Room (or SQLite for the older projects). There is also another reason why storing in a database makes more sense. For example the structure, tables and relations, primary/foreign keys… but this is a whole other topic, and today we will store data in SharedPreferences anyway.

In this example we explain:

  • How to store data
  • Change stored data
  • How to check if data exists
  • How to remove data
  • And how to view data

Quick steps to store data with SharedPreferences

We have prepared a quick list to illustrate, how to store data.

Quick steps to store data with SharedPreferences: 

  • Get preferences for your context (sharedPref = getSharedPreferences)
  • get editor for sharedPreferences (editor = sharedPref.edit() )
  • Store data (editor.putInt(10))
  • Apply changes (editor.apply();)

Next, we will show you how to use this in a simple example.



Which types of data you can store in SharedPreferences in Android

SharedPreferences in Android are perfect for storing information about a state when we leave the application, like which screen was opened, email from a login or a registration form... There is a limit to what we can store in SharedPreferences out of the box. In other words, we can store the following data types boolean, int, long, float, string and stringSet. Working with only basic types always reminds me about the past, where you had to be very resourceful to store some advanced data structures, and it is the same here, you can store proper objects with using serialization and string or stringSet type.

We will explain a way to store complex data in SharedPreferences in our Friends data course (which is already in the making, so hold on, it will be free for the first couple of users)

Data types that can be stored in SharedPreferences:

  • boolean
  • Int
  • long
  • float
  • string
  • stringSet
  • custom data structure (with some workaround)


How to use SharedPreferences in Android to store data

We at CodeBrainer are looking for quick examples all the time. For instance, let’s see how we can use SharedPreferences on a small project. The whole purpose of this project will be to remember the last state of the screen. 

We have written about how the layout editor works in our blog. In this example, the layout will be a simple one. We will have 3 buttons on it, and when we press each one, a value will be stored, so that we can show it when the app is restarted.

Let’s see  how we can use SharedPreferences on a small project. The whole purpose of  this project will be to remember the last state of the screen. We will have 3 buttons on it, and when we press each one, a value will be stored, so that we can show it when the app is restarted.

  1. Put 3 buttons on a screen
    • Name them button1, button2, button3
      Store setting with SharedPreferences in Android

  2. We will start by storing a simple value. In our case an integer
    • The first button will store a value of 1, second 2, third 3
    • When we return into the app, we will show the last value pressed

  3. Let’s add a method that will save our data, we will call it saveLastButtonPressed
    Sharedpreferences saveLastButtonPressed
  4. In the next method, we will add readLastButtonPressedSharedPreferences readLastButtonPressed
    • In case, that we don’t have have a value yet, we will just go ahead and return value 0.
    • Note that if you need to check if a value exists and reacts if there is no value, you can use something like:

      if (sharedPref.contains("LAST_BUTTON")).

      For example, you could open a pop-up window to ask the user for something; when the user answers, you would not repeat it. In this case a default value would be less appropriate.

  5. Now we have to use a method for storing data. This means that we must add onClickListener for all the buttons.

  6. We will read the value in onStart method, and we will change the title when we are done reading it
    SharedPreferences onStart method
  7. Now you are ready to run the app and check the results. In fact, you can see that each time you press a button the title changes. But this is where the magic only begins. Now let’s kill the app by opening the Recents screen (also referred to as the Overview screen, recent task list, or recent apps). You can get to that screen with tapping Recents button on your android phone (usually the square button on the right). Swipe your example app to the left or to the right of the screen (can be different for some manufacturers), and the app will close.

  8. If you open the app again, you will see the stored number in the title.


How to store an email address with SharedPreferences

With this knowledge, we can store even more. Further, try adding an EditText to the screen and store the text inside it

  1. Add EditText (E-Mail)
    • Use E-Mail button from the palette because you will have an appropriate keyboard for entering an email
    • name it “email”
    • Add it below the buttons
    • Set text field to empty text
    • Set text hint field to “Enter email”

  2. This is how the screen should look like
    Store email with SharedPreferences in Android

  3. Now we need to link controls with the code, add a variable for new EditText
    New EditText

  4. We will now link the variable with the control. We will do this using findViewByID, and we will put the code inside the onCreate method.
    SharedPreferences findViewByID

  5. Add a new method for storing the email address (we will store the email later inside the onPause method).
    SharedPreferences saveEmail
    • Inside the method getSharedPreferences, we have a constant string “application”. This is a string that defines the name of the XML file where values are stored. We will use this information later when we explain how to find this file.

  6. Now we need to store our email address when we leave the app. We will use the onPause method. In a real app, the more appropriate place to store an email would be when you press the Login button or the Save button, or a button that takes you to the next screen. For now, we will do it in onPause.
    onPause method

  7. The last thing to do is to read the value; we will change the onStart method also to read our email address.
    onStart method

  8. Now you can try it out, run the app and enter an email address. If you close the app and open it again, you will see that the email is already there. E.g. now it will be easier for your user to login to the server.



Changing stored data

How do we change the stored data you might ask? Android does all the work for us here, since we are working with the Editor object, it will store value for us in both cases if this is a new value or if we want to change it.


Check if data exists

Sometimes we want to know if the value is already stored. For example, if we have a registration form, we could check if we have already stored an email. If email is stored, we do not need to show the registration form, but we can move on to the first screen (in more complex scenarios, this is not the only check we make).

SharedPreferences isEmailSaved

This is a simple function that will check if an email address is stored. We read the value using a contains method for SharedPreferences.


Remove values in SharedPreferences

What if you want to reset or remove a stored value or is there a way of removing all the data stored within your app? Yes, there is. In fact, we can remove a value we have added to the SharedPreferences in Android by using the remove method. This is useful if we reset the login and we don’t want to show the email address to the user again. Or if we have stored the last screen, but the user visits the home screen, we should reset that value.

haredPreferences in Android by using the remove method

Remove all values in SharedPreferences

But is there a way to remove all the values? Yes, we can also remove all the values at once. We must be careful with this method and use it for an appropriate reason, but nevertheless, we can do it.
SharedPreferences remove all the values at once


Viewing values stored on your device

When developing we want to see what we stored in most cases. Knowing what was stored confirms, that our code is working as it should. We will show you, how to view the values you have stored. It seems like the only way is through the code, but this is not the case. All the values are stored in an XML file, and this file is stored inside folders that are dedicated to the app. How do we find this file? To find our SharedPreferences in an Android file, we will use the Device File Explorer and search for the folder of the app. 

Furthermore to find the file you need to know the name of your package and find it amongst all the apps on your Android device. You can check it out in the java file; it is the first line package keyword followed by the package name. (in our case this is com.codebrainer.sharedpreferences, com.codebrainer is the reverse domain name of our web page it is used a lot when naming packages)

  • Open Device File Explorer
    Device File Explorer

  • You will find the file at:
    • /data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFERENCES_NAME.xml
    • Name of the XML file is defined with getSharedPreferences method; first parameter is the name of the file.
    • You must change the package name and the name of the file
      Explore SharedPreferences in Android - Change the package name


How can I use this knowledge?

Now, that you know how to store data with SharedPreferences in Android, you can use it when writing more advanced apps. More importantly, when you have a way of storing data, you can build applications on another level, imagine how many things you can make with this knowledge. CodeBrainer is an excellent stop to learn. For one thing, the best way is to read our blog; there is a good example of how to show data with RecyclerView.