Saving data with SharedPreferences — Android #9

Here’s a short post on how to save small pieces of information in your app so you can use it again later. So you may want to save someone’s name, or a top score or anything else really that you want the app to “remember”.

There’s lots of different ways to save data in apps, today we’ll use the simplest — SharedPreferences.

To create an instance:

SharedPreferences myPrefs;

To set it up for use:

myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);

The “prefID” is important — this is how you identify it, you can change this to anything you want, but remember it as you’ll be re-using it.

To store something in the SharedPreferences:

SharedPreferences.Editor editor = myPrefs.edit();

and then:

editor.putString("nameKey", "Bruce the Hoon");

The “nameKey” is the key — this is the identifier for the item of data you’re storing. You can call this anything, but when you’re retrieving the item, you need to use the same key. The “Bruce the Hoon” is the value — what is actually being stored.

Finally:

editor.apply();

to actually “save” the info. Note you can also use:

editor.commit();

but apply runs in the background so is theoretically better for app performance.

To retrieve the data:

myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);

String name = myPrefs.getString("nameKey","Default");

The “getString” method here has two parameters — the first is the key you defined earlier and the second is a value that will be returned if there isn’t a value for that key.

Let’s try it out. Create a new project with an Empty Activity. In the activity_main.xml file, add the following:

  • a vertical LinearLayout and inside that:
  • a Plain Text EditText — give it an ID of “nameID”
  • a Number EditText — give it an ID of “numberID”
  • a Button — give it an onClick of “onButtonClick” and change the text to “Save Name and Age”
  • a TextView — give it an ID of “labelID”

Remember — we use the IDs to reference the objects in the matching Java file (here MainActivity.java).

The Component Tree should like this:

and the layout looks like this:

and for info, the XML looks like this:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.whatever.twoscreens.MainActivity"
>

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="18dp"
>

<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="@+id/nameID"
android:hint="name "
/>


<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/numberID"
android:hint="age"
/>

<Button
android:text=" Save Name
& Age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:onClick="onButtonClick"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello"
android:textSize="24sp"
android:textAlignment="center"
android:id="@+id/labelID"
/>
</LinearLayout>

</RelativeLayout>

So — the idea here is that the user will enter in a name and an age, we’ll save it to SharedPreferences when they hit the button — and then the next time the app is ran, it will check in SharePreferences for name and age values. If they are stored, we’ll display them in the TextView, if not we’ll show the default values.

Makes sense?

Either way, head to the MainActivity.java file. Once open, create a new variable for the SharedPreferences:

SharedPreferences myPrefs;

Create a new function onButtonClick:

public void onButtonClick(View v){

//get reference to TextView
TextView label = (TextView) findViewById(R.id.labelID);

//get references to Name and Age EditTexts
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText ageEditText = (EditText) findViewById(R.id.ageID);

//set up SharedPreferences
myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();
editor.putString("nameKey", nameEditText.getText().toString());
editor.putInt("ageKey", Integer.parseInt(ageEditText.getText().toString()));
editor.apply();
label.setText("Saved");
}

The first lines get references to the TextView and EditTexts on our layout file:

//get reference to TextView
TextView label = (TextView) findViewById(R.id.labelID);

//get references to Name and Age EditTexts
EditText nameEditText = (EditText) findViewById(R.id.nameID);
EditText ageEditText = (EditText) findViewById(R.id.ageID);

These get the SharedPreferences ready:

//set up SharedPreferences
myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = myPrefs.edit();

and these store the values, taken from the EditTexts:

editor.putString("nameKey", nameEditText.getText().toString());
editor.putInt("ageKey", Integer.parseInt(ageEditText.getText().toString()));

Note the “Integer.parseInt” — this is a handy method to turn a String into a int (a number).

and then we save:

editor.apply();

and then change the TextView on screen to tell the user that we’ve saved the data:

label.setText("Saved");

Ok, now in the onCreate method, which is ran everytime the Activity is created on screen, add this:

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

myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);

String name = myPrefs.getString("nameKey","No name");
int age = myPrefs.getInt("ageKey",0);

TextView label = (TextView) findViewById(R.id.labelID);
label.setText(name + " " + age);
}

The

myPrefs = getSharedPreferences("prefID", Context.MODE_PRIVATE);

gets the SharedPreferences.

String name = myPrefs.getString("nameKey","No name");
int age = myPrefs.getInt("ageKey",0);

gets the values stored. If there hasn’t been any values stored yet, “No name” and 0 will be returned for the name and age respectively.

TextView label = (TextView) findViewById(R.id.labelID);

gets a reference to the TextView in the layout and then show the stored name and age:

label.setText(name + " " + age);

Ok, run the app:

We can see that the TextView shows “No name 0” — exactly as it should, as there’s nothing stored in the SharedPreferences yet!

Ok, fill in a name and age and hit the button, you should see the TextView change to Saved:

Now run the app again and you should see:

Awesome! We’ve pulled back the name and age from SharedPreferences and displayed them on screen!

Any issues or comments let me know below, and if you found it useful and want to shout it to the world, please hit the little heart button below! Thanks, Andy

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Andy O'Sullivan

Andy O'Sullivan

Creator of Boxapopa, the iOS game for young kids with zero ads, just fun! https://apps.apple.com/ie/app/boxapopa/id1550536188