Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Android Shared Preferences Tutorial

Hello, Developers! As we know there are different ways to store data in Android. For ex:

  1. SQLite
  2. Firebase
  3. Android Shared Preferences

In this Tutorial, we will learn how to work with Android Shared Preferences. Shared Preferences allows us to store and retrieve data in form of a key-value pair. The data is stored in an XML file in the app data folder.

When we want to store small data or When we don’t want to do many operations on our data or maybe when we don’t have Structured data, in all those scenarios we can go for Android Shared Preferences. Otherwise, SQLite etc. can be preferred. Android SDK has built in support for Android Shared Preferences API. Now let’s begin with the Tutorial!

The UI will look like this:

Creating New Project – SharedPreferences

  1. Open your Android Studio & create a new Project, we used androidtutorial.com as our domain name and have taken Blank Activity for this project.
  2. The name for activity is by default MainActivity, we kept all the things by default and clicked finish.
    After the project is created and gradle dependencies are resolved, you may start.

Creating Layout

activity_main.xml



        

        
    

Creating Logic

There are basically three Operations that we are performing

Store

When the user clicks on the Store Button. We will Create three String type variables and store data from the EditTexts to these variables. Later by using SharedPreferences.Editor, we will set a set of String values in the Preferences Editor. We are using putString(), which is a method of Editor interface. By using commit() we commit our preferences and it atomically performs requested modifications, replacing whatever is currently there, stored in the SharedPreferences.

The Code given below is little different from what we have used in the Project. It is just for your Understanding. If you want the user to Enter all the Fields, then you may write your logic like this also.

    public void Store(View view) {
        if (et_name.getText().toString().length() > 0 && et_email.getText().toString().length() > 0 && et_phone.getText().toString().length() > 0) {
            String n = et_name.getText().toString();
            String e = et_email.getText().toString();
            String p = et_phone.getText().toString();
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putString(Name, n);
            editor.putString(Email, e);
            editor.putString(Phone, p);
            editor.commit();
            Toast.makeText(getApplicationContext(), "Data Stored Successfuly!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Please Fill all the Fields!!", Toast.LENGTH_SHORT).show();
        }
    }

Fetch

Here we locate our EditTexts in the Layout First, then we set values to them by using getSharedPreferences().  Also before setting the data to the EditTexts for the user to see, we perform checks… that the data is previously stored or not. For this we use contains(). The same logic of checking data and then setting the data can be used in the onCreate() so that when the user launches the app, and the app is having some data stored in the Android Shared Preferences, then the existing data will be displayed to the user.

 public void Fetch(View view) {
        et_name = (EditText) findViewById(R.id.etName);
        et_email = (EditText) findViewById(R.id.etEmail);
        et_phone = (EditText) findViewById(R.id.etPhone);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name))
            et_name.setText(sharedpreferences.getString(Name, ""));
        if (sharedpreferences.contains(Email))
            et_email.setText(sharedpreferences.getString(Email, ""));
        if (sharedpreferences.contains(Phone))
            et_phone.setText(sharedpreferences.getString(Phone, ""));
        Toast.makeText(getApplicationContext(), "Data Displayed Successfuly!", Toast.LENGTH_SHORT).show();
    }

Clear

Whenever the user hits the Clear button we can clear the EditTexts, so that the user can now enter new values and store them!

    public void clear(View view) {
        et_name = (EditText) findViewById(R.id.etName);
        et_email = (EditText) findViewById(R.id.etEmail);
        et_phone = (EditText) findViewById(R.id.etPhone);
        et_name.setText("");
        et_email.setText("");
        et_phone.setText("");
        Toast.makeText(getApplicationContext(), "Data Cleared Successfuly!", Toast.LENGTH_SHORT).show();
    }

You can see the Entire MainActivity.java over here:

package com.androidtutorialpoint.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
    public static final String mypreference = "mypref";
    public static final String Name = "person_name";
    public static final String Email = "email_add";
    public static final String Phone = "phone_no";
    SharedPreferences sharedpreferences;
    EditText et_name;
    EditText et_email;
    EditText et_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_name = (EditText) findViewById(R.id.etName);
        et_email = (EditText) findViewById(R.id.etEmail);
        et_phone = (EditText) findViewById(R.id.etPhone);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        //Show data in EditTexts when app is launched, if data is there in Android Shared Preferences
        if (sharedpreferences.contains(Name))
            et_name.setText(sharedpreferences.getString(Name, ""));
        if (sharedpreferences.contains(Email))
            et_email.setText(sharedpreferences.getString(Email, ""));
        if (sharedpreferences.contains(Phone))
            et_phone.setText(sharedpreferences.getString(Phone, ""));
    }


    public void Store(View view) {
        String n = et_name.getText().toString();
        String e = et_email.getText().toString();
        String p = et_phone.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.putString(Phone, p);
        editor.commit();
        Toast.makeText(getApplicationContext(), "Data Stored Successfuly!", Toast.LENGTH_SHORT).show();
    }

    public void clear(View view) {
        et_name = (EditText) findViewById(R.id.etName);
        et_email = (EditText) findViewById(R.id.etEmail);
        et_phone = (EditText) findViewById(R.id.etPhone);
        et_name.setText("");
        et_email.setText("");
        et_phone.setText("");
        Toast.makeText(getApplicationContext(), "Data Cleared Successfuly!", Toast.LENGTH_SHORT).show();
    }

    public void Fetch(View view) {
        et_name = (EditText) findViewById(R.id.etName);
        et_email = (EditText) findViewById(R.id.etEmail);
        et_phone = (EditText) findViewById(R.id.etPhone);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name))
            et_name.setText(sharedpreferences.getString(Name, ""));
        if (sharedpreferences.contains(Email))
            et_email.setText(sharedpreferences.getString(Email, ""));
        if (sharedpreferences.contains(Phone))
            et_phone.setText(sharedpreferences.getString(Phone, ""));
        Toast.makeText(getApplicationContext(), "Data Displayed Successfuly!", Toast.LENGTH_SHORT).show();
    }
}

That’s it! Now you may run the app and see the changes yourself! Feel free to comment down your Views about this Tutorial. Also in case of any queries, you can let us know!

The post Android Shared Preferences Tutorial appeared first on Android tutorials for hassle-free android development and programming.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Android Shared Preferences Tutorial

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×