Android Shared Preferences tutorial

Android Shared Preferences tutorial

Android provide several storage options for you to store persistent application data. This article covers one of the mostly used storage option for this purpose of storing persistent data which is Android SharedPreferences. Last time we have discussed about SQLite in android if you have not seen that tutorial you can check it here Android SQLite Database tutorial.

Steps involved in this Android SharedPreferences Tutorial are:

1. Introduction to Android SharedPreferences.

2. Storing data to shared preference at activity level.

3. Storing data to shared preference at application level.

4. Different operations in shared preference.

So before going further let me explain various storage options for storing persistent data. And what persistent data actually is.

Persistence data is to store our data for longer duration of time and make it available for your application to use whenever your application needs it. Android SharedPreferences store data in a key-value pair and this file has the format of XML.

SharedPreferences file can be both public and private,which means making the file private block the unauthorized access to our shared preferences file from other applications, for this purpose we need to use MODE_PRIVATE flag. And making the file public helps other application to access the shared preferences file in which, we will be using MODE_WORLD_READABLE flag.

Since public mode is not used anymore we will be using private mode in this tutorial.

1.Creating the project and adding resources

1. Open Android studio click on file->New->NewProject then enter the details of the project like name,backward compatibility, and package name.
2. Create an empty activity and name it the default one which is MainActivity (I just want to make it simple) then click finish. Now you have created your project. Make sure that there is no error by tapping on the RUN button at the top.
3. In the styles.xml file located under res->values change the line

Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.Light.NoActionBar to hide the default actionbar(This step is optional).

styles.xml

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

2. Creating Layout

In the activity_main.xml add the following code.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_margin="10dp">
        <EditText
            android:layout_margin="10dp"
            android:id="@+id/ed1"
            android:hint="Name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <EditText
            android:hint="Email"
            android:layout_margin="10dp"
            android:id="@+id/ed2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="save"
            android:id="@+id/btn_save"/>
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Load"
            android:id="@+id/btn_load"/>
        <TextView
            android:id="@+id/txt_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Name"
            android:layout_margin="8dp"
            android:layout_gravity="center_horizontal"
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            />
        <TextView
            android:id="@+id/txt_email"
            android:layout_margin="8dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Email"
            android:layout_gravity="center_horizontal"
            style="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
            />
        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Second Activity"
            android:id="@+id/btn_second"/>
    </LinearLayout>

</LinearLayout>

Now run the app and you should get screen similar to this.

Initialising layout components in MainActivity.java

MainActivity.java

package com.techpakka.sharedpreferences;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button btn_save,btn_load,btn_second;
    EditText ed_name,ed_email;
    TextView txt_name,txt_email;
    String str_name,str_email;

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

         //initialising layout components
        btn_save = findViewById(R.id.btn_save);
        btn_load = findViewById(R.id.btn_load);
        btn_second = findViewById(R.id.btn_second);
        txt_name= findViewById(R.id.txt_name);
        txt_email= findViewById(R.id.txt_email); 
        ed_name = findViewById(R.id.ed1); 
        ed_email = findViewById(R.id.ed2);

    }
}

Activity level Shared Preferences

It is used to create separate Shared Preferences file for your Activity.

Set up onclick listener for the save button. In that onclick method initialise the activity-level Shared Preferences. Also get the data from edit text and store in string file which, later we will use to add to shared preferences file.

MainActivity.java

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

        btn_save = findViewById(R.id.btn_save);
        btn_load = findViewById(R.id.btn_load);
        btn_second = findViewById(R.id.btn_second);
        ed_name = findViewById(R.id.ed1);
        ed_email = findViewById(R.id.ed2);

        //implementing onclick listener
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getdata from edittext and store in corresponding string file
                str_email = ed_email.getText().toString();
                str_name = ed_name.getText().toString();
                SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
                //we need editor to edit created shared preference file
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("name",str_name);
                editor.putString("email",str_email);
                editor.apply();
            }
        });
    }

now run the app and type the fields and click save. It will save the entered data to shared preferences file.now lets retrieve those values from file and load them into the textview.

For that you need to implement onClicklistener on the load button and add the following code to it.

MainActivity.java

btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
                String name = sharedPreferences.getString("name","default_value");
                String email = sharedPreferences.getString("email","default_value");
                txt_name.setText(name);
                txt_email.setText(email);
            }
        });
    }

Now run the app. when clicked on load button your textview should show the exact same text in edittext. Like below

This sharedpreferences is limited to a single activity which is MainActivity.java

now lets jump on to application level sharedpreferences

Application level Shared Preferences

First lets create another activity by clicking on yourpackagename -> new ->activity -> empty activity and name it SecondActivity.

To navigate from MainActivity toIn our MainActivity.java change the code inside save button click listener to following.

  btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getdata from edittext and store in corresponding string file
                str_email = ed_email.getText().toString();
                str_name = ed_name.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences("my_sharedpreference_file_name",Context.MODE_PRIVATE);
                //we need editor to edit created shared preference file
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("name",str_name);
                editor.putString("email",str_email);
                editor.apply();
            }
        });

And also change the code in the load button onClick method with following

   btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("my_sharedpreference_file_name",Context.MODE_PRIVATE);
                String name = sharedPreferences.getString("name","default_value");
                String email = sharedPreferences.getString("email","default_value");
                txt_name.setText(name);
                txt_email.setText(email);
            }
        });

Now implement onclicklistener on the second activity button for navigating to second activty on clicking it.

btn_second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });

Now open second_activity.xml and add following code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SecondActivity">
<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/btn_load"
    android:layout_margin="16dp"
    android:text="load"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="name"
        android:layout_margin="16dp"
        android:layout_gravity="center_horizontal"
        android:id="@+id/txt_name"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_margin="16dp"
        android:layout_gravity="center_horizontal"
        android:layout_height="wrap_content"
        android:text="email"
        android:id="@+id/txt_email"/>
</LinearLayout>

In SecondActivity.java initialise the layout components just like we did in MainActivity.java also add click listener to the button to get data from shared preference and load them in textview.

final SecondActivity.java look like below.

SecondAcivity.java

package com.techpakka.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
Button btn_load;
TextView txt_name,txt_email;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        btn_load = findViewById(R.id.btn_load);
        txt_email = findViewById(R.id.txt_email);
        txt_name = findViewById(R.id.txt_name);

        btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("my_sharedpreference_file_name", Context.MODE_PRIVATE);
                txt_name.setText(sharedPreferences.getString("name","default_value"));
                txt_email.setText(sharedPreferences.getString("email","default_value"));
            }
        });
    }
}

final MainActivity.java look like below.

package com.techpakka.sharedpreferences;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    Button btn_save,btn_load,btn_second;
    EditText ed_name,ed_email;
    TextView txt_name,txt_email;
    String str_name,str_email;

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

        btn_save = findViewById(R.id.btn_save);
        btn_load = findViewById(R.id.btn_load);
        btn_second = findViewById(R.id.btn_second);
        ed_name = findViewById(R.id.ed1);
        ed_email = findViewById(R.id.ed2);
        txt_name = findViewById(R.id.txt_name);
        txt_email = findViewById(R.id.txt_email);

        //implementing onclick listener
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //getdata from edittext and store in corresponding string file
                str_email = ed_email.getText().toString();
                str_name = ed_name.getText().toString();
                SharedPreferences sharedPreferences = getSharedPreferences("my_sharedpreference_file_name",Context.MODE_PRIVATE);
                //we need editor to edit created shared preference file
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("name",str_name);
                editor.putString("email",str_email);
                editor.apply();
            }
        });

        btn_load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("my_sharedpreference_file_name",Context.MODE_PRIVATE);
                String name = sharedPreferences.getString("name","default_value");
                String email = sharedPreferences.getString("email","default_value");
                txt_name.setText(name);
                txt_email.setText(email);
            }
        });

        btn_second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        });
    }
}

Run the app and i hope you got a screen as follows

%d bloggers like this: