Understanding Shared Preferences – Android

Shared Preferences is a simply way to store primitive data. It is especially useful as even when the application is closed the data will continue to exist.

First begin by declaring: 

SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

Putting variables onto Shared Preferences

To store the data begin by declaring the the editor.

SharedPreferences.Editor editor = app_preferences.edit();

After you have declared the editor you can then begin putting the variables you want to store the data of onto it. This can be anything from a String to an int.

To store them:

editor.putInt("days", Integer.parseInt(days.getText().toString()));

In this case I wanted to store an int, but the user input was from an EditText, therefore it was being returned as a String. So user parseInt and done it all in one line.

If you just wanted to pass a variable:

editor.putString("days", dates);

The most important part is ensuring that you actually save them to the editor! An easy step to forget about.
Once you have finished adding the variables to the editor place:

editor.commit();

To access the variables which you have stored. Begin by declaring:

SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

you will then need to declare which variable you want to access. For example to access an int:

int weeksUsed = app_preferences.getInt("weeks",-1);

To do so you place the name of the variable, in my example I used “weeks”. You have to give it a value just incase there is nothing stored in the variable. This can be used to check if the data is correct which has been received. For example you could have:

if(weeksUsed = -1)
{
   //You could use a toast!
   Context context = getApplicationContext();
   CharSequence text = "content received is not correct ";
   int duration = Toast.LENGTH_SHORT;

   Toast toast = Toast.makeText(context, text, duration);
   toast.show();
}//if

To access the String it is the same, however you can pass it null instead of a number.

String gettingUserName = app_preferences.getString("email", null);

To clear the editor:

editor.clear();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s