Persisting data with SharedPreferences

In Android, there are a few ways to make data persist. By persist, I mean that if the user quits the app, then when they come back to it, their data is still available. What method is the correct one to use is dependent upon the app and the type of data.

In this book, we will look at three ways to make data persist. For saving our user's settings, we only need a simple method. After all, we just need to know whether they want the decorative divider between each of the notes in the RecyclerView.

Let's look at how we can make our apps save and reload variables to the internal storage of the device. We need to use SharedPreferences objects. SharedPreferences is a class that provides access to data that can be accessed and edited by all Activity classes of an app. Let's look at how we can use it:

// A SharedPreferences for reading data
SharedPreferences prefs;

// A SharedPreferences.Editor for writing data
SharedPreferences.Editor editor;

As with all objects, we need to initialize them before we can use them. We can initialize the prefs object using the getSharedPreferences method and passing in a String that will be used to refer to all the data read and written using this object. Typically, we could use the name of the app as this string. In the following code, Mode_Private means that any class, in this app only, can access it:

prefs = getSharedPreferences("My App", MODE_PRIVATE);

We then use our newly initialized prefs object to initialize our editor object by calling the edit method:

editor = prefs.edit();

Let's say we wanted to save the user's name, which we have in a String called username. We can then write the data to the internal memory of the device like this:

editor.putString("username", username);
editor.commit();

The first argument used in the putString method is a label that can be used to refer to the data, while the second is the actual variable that holds the data we want to save. The second line in the previous code initiates the saving process. So, we could write multiple variables to disk like this:

editor.putString("username", username);
editor.putInt("age", age);
editor.putBoolean("newsletter-subscriber", subscribed);

// Save all the above data
editor.commit();

The preceding code demonstrates that you can save other variable types and it, of course, assumes that the username, age, and subscribed variables have previously been declared and then initialized with appropriate values.

Once editor.commit() has executed, the data is stored. We can quit the app, even turn off the device, and the data will persist.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.142.193