Android SharedPreferences Example Tutorial

There are at times when we need to store some data in our application which will persist with the application and we will also have to opportunity to read the data and use it in different areas of the application then, we can use android shared preference.

There are many other options available to store data in your application like using a flat flat or storing the data in local application database like SQLite.

If you prefer to use a database, I wrote an extensive tutorial about different databases you can use in you android application. The list is shared below.

1. Android SQLite Database Example Tutorial 

2. Android Sugar ORM Database Tutorial

3. Android Realm Database Tutorial 

Lets continue to learn how to use Shared Preference in android. To create an instance of a SharedPreference class, we use the getSharedPreferences(String, int).

The String parameter in the method is use as the name of the shared preference file to be use if the name does not exist.

The int parameter represents the operating mode of the shared preference. Use 0 or MODE_PRIVATE for the default operation.

You can read the android SharedPreferences documentation for more information about available methods you can use.

SharedPreferences.Editor is an interface used to create an instance of an Editor class which provides access to SharedPreferences object. We can use the Editor object to make changes to the SharedPreferences object.

The list below is common methods you will frequently use when you work with android SharedPreferences.

1. contains(String key) – Checks whether the preferences contains a preference.

2. edit() – Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.

3. getAll()– Retrieve all values from the preferences.

4. getBoolean(String key, boolean defValue)– Retrieve a boolean value from the preferences.

5. getFloat(String key, float defValue)– Retrieve a float value from the preferences.

6. getInt(String key, int defValue)– Retrieve an int value from the preferences.

7. getLong(String key, long defValue)– Retrieve a long value from the preferences.

8. getString(String key, String defValue) - Retrieve a String value from the preferences.

With this we are going to create and example on how you can use android SharedPreferences to save and retrieve use input values in your application.

The screen-shot of the application is shown below
android sharedpreferences

1. Create a new android app

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidSharedPreferences

Package: com.inducesmile.androidsharedpreferences

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

2. Add the code below to activity_main.xml layout file.

Open the activity_main.xml file created by default with Android Studio and add the code below.

The layout file contains two EditText and a Button widget control.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:gravity="center"
    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.inducesmile.androidsharedpreferences.MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/fill_in_the_box_if_there_is_values_in_them" />
    <EditText
        android:id="@+id/first_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/firstname"
        android:layout_marginTop="16dp"
        android:textColorHint="@color/colorLight"
        android:inputType="text"
        android:maxLines="1"
        android:background="@drawable/border"
        android:textColor="@color/colorBlack"
        android:padding="12dp"/>
    <EditText
        android:id="@+id/last_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/lastname"
        android:layout_marginTop="16dp"
        android:textColorHint="@color/colorLight"
        android:inputType="text"
        android:maxLines="1"
        android:background="@drawable/border"
        android:textColor="@color/colorBlack"
        android:padding="12dp"/>
    <Button
        android:id="@+id/save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp"
        android:paddingBottom="16dp"
        android:paddingTop="16dp"
        android:text="@string/save_in_sharedpreferences"
        android:textAllCaps="true"
        android:textColor="@color/colorWhite"
        android:background="@color/colorAccent"
        android:textStyle="bold" />
    
</LinearLayout>

 3. Update the MainActivity.java class

we will get the instances of the widgets in the layout file. When a use enters its first name and last name and click on the save button the values will be saved in the sharedpreferences.

Open the MainActivity class and add the code below.

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private EditText firstName, lastName;
    private SharedPreferences mPref;
    private  static final String PREF_NAME = "sp_name";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mPref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        firstName = (EditText)findViewById(R.id.first_name);
        lastName = (EditText)findViewById(R.id.last_name);
        String storedFirstName = mPref.getString("FIRST_NAME", "");
        firstName.setText(storedFirstName);
        String storedLastName = mPref.getString("LAST_NAME", "");
        lastName.setText(storedLastName);
        Button saveButton = (Button)findViewById(R.id.save);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String first = firstName.getText().toString();
                String last = lastName.getText().toString();
                if(TextUtils.isEmpty(first) || TextUtils.isEmpty(last)){
                    Toast.makeText(MainActivity.this, "All fields must be filled ", Toast.LENGTH_LONG).show();
                }else{
                    SharedPreferences.Editor editor = mPref.edit();
                    editor.putString("FIRST_NAME", first);
                    editor.putString("LAST_NAME", last);
                    editor.apply();
                    firstName.setText("");
                    lastName.setText("");
                }
            }
        });
    }
}

3. Update the Strings.xml resources

Open the strings.xml file and add the code below.

<resources>
    <string name="app_name">Android SharedPreferences</string>
    <string name="fill_in_the_box_if_there_is_values_in_them">Fill in the fields if there is no values in them</string>
    <string name="firstname">Firstname</string>
    <string name="lastname">Lastname</string>
    <string name="save_in_sharedpreferences">SAVE IN SHAREDPREFERENCES</string>
</resources>

 4. Update the Colors.xml resources

Open the colors.xml file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="colorBorder">#e6e3e2</color>
    <color name="colorLight">#7F7F7F</color>
    <color name="colorBlack">#000000</color>
    <color name="colorWhite">#ffffff</color>
</resources>

 5. Create new drawable name border.xml

Create a new drawable inside the drawable folder and name it border.xml. Open the drawable file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke
        android:width="1dp"
        android:color="@color/colorBorder" />
    <solid
        android:color="#00FFFFFF"/>
</shape>

 6. How to store an Object in Android SharedPreferences

In the above section, we have learn how to save primitive types in android sharedpreferences but then, when beginner android developers are faced with saving an object in a sharedpreferences then they will realized that something has to be done and it is not possible the directly save an object as a String with first serializing the object to string.

To save object in our sharedpreferences object, we have to first serialize the object. There are different ways to serialize object in android but in this tutorial, we are going to use a third party library called Gson.

Import Gson library in your android using this gradle dependency.

compile 'com.google.code.gson:gson:2.6.1'

This is the current version of the library as at the time of writing this tutorial.

7. Update the Android Build.Gradle file

The updated version of your project build.gradle is as shown below.

apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.inducesmile.androidsharedpreferences"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.google.code.gson:gson:2.6.1'
    testCompile 'junit:junit:4.12'
}

 8. Add Gson to MainActivity class

In other to use Gson in MainActivity class, we will declare it like this

private Gson gson;
private GsonBuilder builder;

In the onCreate(Bundle saveInstanceState) method, we will instantiate it like below.

firstName = (EditText)findViewById(R.id.first_name);
lastName = (EditText)findViewById(R.id.last_name);

 9. Create a new Person class

Create a java class and name it Person. The Person class will take two parameters in its constructor. The parameters are the firstname and lastname we used in the first example.

Open the Person class and add the code below.

public class Person {
    private String firstname;
    private String lastname;
    public Person(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
}

 10 Create to methods that converts Person object to String and from String back to Person object

private String convertPersonObjectToString(Person person){
    String objectString = gson.toJson(person);
    return objectString;
}

private Person convertStringToPersonObject(String personString){
    Person person = gson.fromJson(personString, Person.class);
    return person;
}

With these methods, you can save the Person object in Android SharedPreferences by first converting to String and the store it.

When you want to recreate the Person object from the stored string, first you have to retrieve the string from SharedPreference and them use the method above and convert it to Person object.

11. Use the same method to save ArrayList and List of object

You can still use the same method as above to save ArrayList and List of objects. In some situation, you will need to represent the object in array form like this Person[].class instead of Person.class.

Finally, if you have used another method to achieve this, I will appreciate it if you can share your solution with us.

 

OTHER INTERESTING POSTS:

Add a Comment