How to Create and Save Shared Preferences in Android?

«
»
Here is source code of the Program to Demonstrate Creating and Saving Shared Preferences in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Shared Preferences are a simple, lightweight name/value pair (NVP) mechanism for saving primitive application data, most commonly a user’s application preferences.

Creating And Saving Shared Preferences
Using the SharedPreferences class, you can create named maps of name/value pairs that can be persisted across sessions and shared among application components running within the same application sandbox.
To create or modify a Shared Preference, call getSharedPreferences on the current Context, passing in the name of the Shared Preference to change.

SharedPreferences mySharedPreferences = getSharedPreferences(MY_PREFS,
Activity.MODE_PRIVATE);

Shared Preferences are stored within the application’s sandbox, so they can be shared between an application’s components but aren’t available to other applications.
To modify a Shared Preference, use the SharedPreferences.Editor class. Get the Editor object by calling edit on the Shared Preferences object you want to change.

SharedPreferences.Editor editor = mySharedPreferences.edit();

Use the put methods to insert or update the values associated with the specified name:

advertisement
advertisement
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);

To save edits, call apply or commit on the Editor object to save the changes asynchronously or synchronously,
respectively.

// Commit the changes.
editor.apply();

Accessing Shared Prefernces
Accessing Shared Preferences, like editing and saving them, is done using the getSharedPreferences method
.
Use the type-safe get methods to extract saved values. Each getter takes a key and a default
value (used when no value has yet been saved for that key.)

// Retrieve the saved values.
boolean isTrue = mySharedPreferences.getBoolean(“isTrue”, false);
float lastFloat = mySharedPreferences.getFloat(“lastFloat”, 0f);
int wholeNumber = mySharedPreferences.getInt(“wholeNumber”, 1);
long aNumber = mySharedPreferences.getLong(“aNumber”, 0);
String stringPreference =
mySharedPreferences.getString(“textEntryValue”, “”);

You can return a map of all the available Shared Preferences keys values by calling getAll, and
check for the existence of a particular key by calling the contains method.

Map<String, ?> allPreferences = mySharedPreferences.getAll();
boolean containsLastFloat = mySharedPreferences.contains(“lastFloat”);

In this tutorial we create an application which stores a User name and email-id, using Shared-Preferences we save the data and retrieve the saved data ,as an example the user-name and user-password is hard-coded as test.

Main Activity

advertisement
 
package com.example.sharedpreferences;
 
import java.util.HashMap;
 
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    AlertDialogCreator alert = new AlertDialogCreator();
    SessionCreator session;
    Button Logout;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        session = new SessionCreator(getApplicationContext());
 
        TextView lblName = (TextView) findViewById(R.id.lblName);
        TextView lblEmail = (TextView) findViewById(R.id.lblEmail);
 
        Logout = (Button) findViewById(R.id.Logout);
 
        Toast.makeText(getApplicationContext(),
                "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
                .show();
 
        session.checkLogin();
 
        HashMap<String, String> user = session.getUserDetails();
        String name = user.get(SessionCreator.KEY_NAME);
        String email = user.get(SessionCreator.KEY_EMAIL);
        lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>"));
        lblEmail.setText(Html.fromHtml("Email: <b>" + email + "</b>"));
        Logout.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                session.logoutUser();
            }
        });
    }
}

AlertDialogCreator.java

 
package com.example.sharedpreferences;
 
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
 
public class AlertDialogCreator {
 
    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
 
        if (status != null) {
            alertDialog
                    .setIcon((status) ? R.drawable.success : R.drawable.fail);
        }
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        alertDialog.show();
    }
}

SessionCreator.java

 
package com.example.sharedpreferences;
 
import java.util.HashMap;
 
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
 
public class SessionCreator {
    SharedPreferences pref;
    Editor editor;
    // an editor is used to edit your preferences
    Context context;
 
    // Shared Preference file name
    private static final String PREF_NAME = "Pref";
 
    // Shared Preferences Key
    private static final String IS_LOGIN = "IsLoggedIn";
 
    public static final String KEY_NAME = "name";
    public static final String KEY_EMAIL = "email";
 
    public SessionCreator(Context context) {
        this.context = context;
        /*
         * Setting the mode as Private so that the preferences should only be
         * used in this application and not by any other application
         * also the preferences can be Shared Globally by using -
         *Activity.MODE_WORLD_READABLE - to read Application components data
         *globally and,
         *Activity.MODE_WORLD_WRITEABLE -file can be written globally by any
         *other application. 
         */
 
 
        pref = context.getSharedPreferences(PREF_NAME, Activity.MODE_PRIVATE);
        /*
         * the same pref mode can be set to private by using 0 as a flag instead
         * of Acticity.MODE_PRIVATE
         */
        editor = pref.edit();
    }
 
    // Creating a login session
    public void createLoginSession(String name, String email) {
        editor.putBoolean(IS_LOGIN, true);
        editor.putString(KEY_NAME, name);
        editor.putString(KEY_EMAIL, email);
        editor.commit();
    }
 
    public void checkLogin() {
        // Check login status
        if (!this.isLoggedIn()) {
            // user is not logged in redirect to Login Activity
            Intent i = new Intent(context, Login.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
            context.startActivity(i);
        }
 
    }
 
    // Getting stored session data of user and returing this data as a HASH MAP
    public HashMap<String, String> getUserDetails() {
        HashMap<String, String> user = new HashMap<String, String>();
        // user name
        user.put(KEY_NAME, pref.getString(KEY_NAME, null));
 
        // user email id
        user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
        return user;
    }
 
    // Clearing a session data
    public void logoutUser() {
        editor.clear();
        editor.commit();
 
        Intent i = new Intent(context, Login.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 
        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 
        context.startActivity(i);
    }
 
    // Get Login State
    public boolean isLoggedIn() {
        return pref.getBoolean(IS_LOGIN, false);
    }
}

Login.java

advertisement
package com.example.sharedpreferences;
 
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
 
public class Login extends Activity {
 
    EditText txtUsername, txtPassword;
    Button btnLogin;
 
    AlertDialogCreator alert = new AlertDialogCreator();
    SessionCreator session;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        session = new SessionCreator(getApplicationContext());
 
        txtUsername = (EditText) findViewById(R.id.Username);
        txtPassword = (EditText) findViewById(R.id.Password);
 
        Toast.makeText(getApplicationContext(),
                "User Login Status: " + session.isLoggedIn(), Toast.LENGTH_LONG)
                .show();
 
        btnLogin = (Button) findViewById(R.id.Loginbutton);
 
        btnLogin.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View arg0) {
                String username = txtUsername.getText().toString();
                String password = txtPassword.getText().toString();
 
                if (username.trim().length() > 0
                        && password.trim().length() > 0) {
                    if (username.equals("test") && password.equals("test")) {
                        session.createLoginSession("SanFoundry",
                                "[email protected]");
                        Intent i = new Intent(getApplicationContext(),
                                MainActivity.class);
                        startActivity(i);
                        finish();
 
                    } else {
                        alert.showAlertDialog(Login.this, "Login failed",
                                "Username/Password is incorrect", false);
                    }
                } else {
                    alert.showAlertDialog(Login.this, "Login failed",
                            "Please enter username and password", false);
                }
 
            }
        });
    }
 
}

ActivityMain.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    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=".MainActivity"
    android:orientation="vertical" >
 
    <TextView
        android:id="@+id/lblName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:layout_marginTop="40dip"
        android:singleLine="true" />
 
    <TextView
        android:id="@+id/lblEmail"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="40dip"
        android:singleLine="true" />
 
    <Button
        android:id="@+id/Logout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/lblName"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="95dp"
        android:text="Logout" />
 
</LinearLayout>

Login.xml

 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:singleLine="true"
        android:text="Username" />
 
    <EditText
        android:id="@+id/Username"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip" />
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:text="Password" />
 
    <EditText
        android:id="@+id/Password"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="20dip"
        android:password="true"
        android:singleLine="true" />
 
    <Button
        android:id="@+id/Loginbutton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Login" />
 
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sharedpreferences"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
 
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.sharedpreferences.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.sharedpreferences.Login"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.Login" />
 
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>

shared_prefernces

shared_prefernces1

shared_prefernces2

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

If you wish to look at all Tutorials, go to Java Android Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.