SharedPreferences - Store simple data quickly

Today we are going to talk about SharedPreferences. It is a place where you can store data. 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 formthe last opened screennickname for a game or 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 and a little bit more complicated data.

SharedPreferences are not intended to store a lot of data, there is no limit per say (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 and that is structure, tables and relations, primary/foreign keys… but this is a whole other topic and today we will store data in SharedPreferences anyway.

SharedPreferences are perfect for storing information about a state when we leave the application, like which screen was opened, email for login... There is a limit to what we can store in SharedPreferences out of the box. We can store 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 here too, you can store proper objects with using serialization and string or stringSet type.

We will leave this for our data course (which is already in the making, so hold on, it will be free for the first couple of users, so check our topics for more news).



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

  2. We will start with storing a simple value. In our case an integer
    • 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
  4. The next method we will add is 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 react 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 just change the title when we are done reading it
  7. Now you are ready to run the app and check the results. 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 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.

With this knowledge we can store even more. Try adding a 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
  3. Now we need to link controls with the code, add a variable for 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.
  5. Add a new method for storing the email address (we will store the email later inside the onPause method)
    • 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, 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 a Login button or Save button, or a button that takes you to the next screen. For now we will do it in onPause.
  7. The last thing to do is to read the value, we will change the onStart method to also read our email
  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 entered. E.g. now it will be easier for your user to login to the server.


 

Last time we had a lecture about storing data and a question was asked. 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, we can remove a value we have added to the SharedPreferences by using 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.


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

Last thing I want to show you with SharedPreferences is 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 dedicated to the app. How do we find this file? To find our SharedPreferences file we will use Device File Explorer and search for the folder of the app. 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 java file, it is the first line package keyword followed by package name. (in our case this is com.codebrainer.sharedpreferences)

  • Open 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

Now, that you know how to store data, it will come in handy, when writing more advanced apps. You will have a way of storing data.