Android - Shared Preferences

Android - Shared Preferences


Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save
and retrieve data in the form of key, value pair.
In order to use shared preferences, you have to call a method getSharedPreferences() that returns a Shared Preference instance pointing to the file that contains the values of preferences.

Android Shared Preferences Overview

Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.
Android stores Shared Preferences settings as an XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().
SharedPreferences is application-specific, i.e. the data is lost on performing one of the following options:
  • on uninstalling the application
  • on clearing the application data (through Settings)
As the name suggests, the primary purpose is to store user-specified configuration details, such as user-specific settings, keeping the user logged into the application.
To get access to the preferences, we have three APIs to choose from:
  • getPreferences(): used from within your Activity, to access activity-specific preferences
  • getSharedPreferences(): used from within your Activity (or other application Context), to access application-level preferences
  • getDefaultSharedPreferences(): used on the PreferenceManager, to get the shared preferences that work in concert with Android’s overall preference framework
In this tutorial, we’ll go with getSharedPreferences(). The method is defined as follows:
getSharedPreferences (String PREFS_NAME, int mode)
PREFS_NAME is the name of the file.
mode is the operating mode.
Following are the operating modes applicable:
  • MODE_PRIVATE: the default mode, where the created file can only be accessed by the calling application
  • MODE_WORLD_READABLE: Creating world-readable files is very dangerous, and likely to cause security holes in applications
  • MODE_WORLD_WRITEABLE: Creating world-writable files is very dangerous, and likely to cause security holes in applications
  • MODE_MULTI_PROCESS: This method will check for modification of preferences even if the Shared Preference instance has already been loaded
  • MODE_APPEND: This will append the new preferences with the already existing preferences
  • MODE_ENABLE_WRITE_AHEAD_LOGGING: Database open flag. When it is set, it would enable write-ahead logging by default

Initialization

We need an editor to edit and save the changes in shared preferences. The following code can be used to get the shared preferences

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();

Android Shared Preferences Project Code

The activity_main.xml layout consists of two EditText views which store and display name and email. The three buttons implement their respective onClicks in the MainActivity.

activity_main.xml
    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" >

   
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="Save"
        android:text="Save" />

   
        android:id="@+id/btnRetr"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:onClick="Get"
        android:text="Retrieve" />

   
        android:id="@+id/btnClear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignRight="@+id/etEmail"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="clear"
        android:text="Clear" />

   
        android:id="@+id/etEmail"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Email"
        android:inputType="textEmailAddress"
        android:layout_below="@+id/etName"
        android:layout_marginTop="20dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

   
        android:id="@+id/etName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Name"
        android:inputType="text"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/etEmail"
        android:layout_alignStart="@+id/etEmail" />



The MainActivity.java the file is used to save and retrieve the data through keys.



package com.journaldev.sharedpreferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    SharedPreferences sharedpreferences;
    TextView name;
    TextView email;
    public static final String mypreference = "mypref";
    public static final String Name = "nameKey";
    public static final String Email = "emailKey";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);
        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }

    }

    public void Save(View view) {
        String n = name.getText().toString();
        String e = email.getText().toString();
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString(Name, n);
        editor.putString(Email, e);
        editor.commit();
    }

    public void clear(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        name.setText("");
        email.setText("");

    }

    public void Get(View view) {
        name = (TextView) findViewById(R.id.etName);
        email = (TextView) findViewById(R.id.etEmail);
        sharedpreferences = getSharedPreferences(mypreference,
                Context.MODE_PRIVATE);

        if (sharedpreferences.contains(Name)) {
            name.setText(sharedpreferences.getString(Name, ""));
        }
        if (sharedpreferences.contains(Email)) {
            email.setText(sharedpreferences.getString(Email, ""));

        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}


Android - Shared Preferences Android - Shared Preferences Reviewed by Mohammed Sabeel on October 14, 2018 Rating: 5

1 comment:

If you have some difficulties. Let me know

Powered by Blogger.