Android Shared Preferences Example

Android SharedPreferences use key value pair to store data. This is a more easier way for data storage operation in android. You do not need to care about file operation. You just need to get the SharedPreferences object, give it a key and related value. Then invoke SharedPreferences object’s apply() or commit() method. Then android OS will save the data in low level files.

1. How To Get Shared Preferences Object.

The key and value data saved in shared preferences object is finally saved in a xml file by android OS.

The xml file is saved in /data/data/<app package name>/shared_prefs folder. You can specify the file name in code, or you can use the system default shared preferences file name.

android shared preferences file saved folder

Android device monitor is a tool for you to look and transfer files between your android device and PC. Please refer article Android Device Monitor Cannot Open Data Folder Resolve Method.

Android provide below three method to get SharedPreferences Object.

1.1 Context’s getSharedPreferences(String fileName, int fileMode) Method.

  1. The first parameter is the file name to save the data in SharedPreferences object.
  2. The second parameter is the file create mode. It can be MODE_PRIVATE, MODE_APPEND. Please refer Android Read Write Internal Storage File Example to learn more.

1.2 Activity’s getPreferences(int fileMode) Method.

This method has only one parameter. The parameter value is same with method 1. The SharedPreferences file name is the activity class name.

1.3 PreferenceManager’s getDefaultSharedPreferences(Context context) Method.

This is a static method, the parameter is a context object. The SharedPreferences file name is prefixed with the activity package name.

2. How To Manipulate Data With SharedPreferences Object.

To operate data, you first need to get SharedPreferences Editor object, then use that Editor object to manipulate data.

2.1 Get Data Editor.

SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, MODE_PRIVATE);

Editor editor = sharedPreferences.edit();

2.2 Save Data In SharedPreferences Use Editor.

Do not forget invoke editor.apply() or editor.commit() method after all data operation code.

editor.putString(String key, String value);

editor.putBoolean(String key, boolean value);

editor.putLong(String key, long value);

editor.putInt(String key, int value);

editor.putFloat(String key, float value);

editor.apply();
// editor.commit();

2.3 Read Data From SharedPreferences.

Read data in shared preferences file do not need editor. SharedPreferences object just provide below method to do that.

sharedPreferences.getBoolean(String key, boolean defaultValue);

sharedPreferences.getString(String key, String defaultValue);

sharedPreferences.getInt(String key, int defaultValue);

sharedPreferences.getLong(String key, long defaultValue);

sharedPreferences.getFloat(String key, float defaultValue);

2.4 Remove Data In SharedPreferences.

Editor editor = sharedPreferences.edit();

editor.remove(String key);

editor.commit();

2.5 Remove All Data In SharedPreferences.

Editor editor = sharedPreferences.edit();

editor.clear();

editor.commit();

3. Android Shared Preferences Example.

From above introduction, we can see that android SharedPreferences object is very suitable to be used to operate application settings. So this example will use SharedPreferences to save user login username and password.

READ :   Android Count Down Timer Example

android shared preferences remember login account example

3.1 Layout Xml File.

activity_shared_preference.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="User Name :"/>

        <EditText
            android:id="@+id/shared_preference_login_username"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input user name."/>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Password :"/>

        <EditText
            android:id="@+id/shared_preference_login_password"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="3"
            android:hint="Input password."
            android:password="true"/>

    </LinearLayout>

    <CheckBox
        android:id="@+id/shared_preference_remember_account"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remember UserName Password."/>

    <Button
        android:id="@+id/shared_preference_verify_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Verify Account"/>

    <Button
        android:id="@+id/shared_preference_remove_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Remove Password"/>

    <Button
        android:id="@+id/shared_preference_clear_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear Saved Account"/>

    <Button
        android:id="@+id/shared_preference_reload_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Reload Shared Preferences Data"/>

</LinearLayout>

3.2 Activity Java File.

package com.dev2qa.example.storage.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.dev2qa.example.R;

public class SharedPreferenceActivity extends AppCompatActivity {

    // The shared preferences file name do not contain file extension.
    // Because shared preferences data will be saved in a xml format file.
    private String SHARED_PREFERENCES_FILE_NAME = "userInfo";

    private String SHARED_PREFERENCES_KEY_USERNAME = "userName";

    private String SHARED_PREFERENCES_KEY_PASSWORD = "password";

    private String SHARED_PREFERENCES_KEY_REMEMBER_ACCOUNT = "rememberAccount";

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

        setTitle("dev2qa.com - Android Shared Preferences Example.");

        final EditText userNameEditText = (EditText)findViewById(R.id.shared_preference_login_username);

        final EditText passwordEditText = (EditText)findViewById(R.id.shared_preference_login_password);

        final CheckBox rememberAccountCheckbox = (CheckBox)findViewById(R.id.shared_preference_remember_account);

        final Context context = getApplicationContext();

        initLoginForm(context, userNameEditText, passwordEditText, rememberAccountCheckbox);

        Button verifyButton = (Button)findViewById(R.id.shared_preference_verify_button);
        verifyButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userName = userNameEditText.getText().toString();
                String password = passwordEditText.getText().toString();

                if("dev2qa.com".equalsIgnoreCase(userName) && "dev2qa.com".equalsIgnoreCase(password))
                {

                    boolean rememberAccount = rememberAccountCheckbox.isChecked();
                    if(rememberAccount)
                    {
                        writeToSharedPreferences(context, userName, password, rememberAccount);
                        Toast.makeText(context, "Username and password verified success and write to shared preferences success. ", Toast.LENGTH_SHORT).show();
                    }else
                    {
                        Toast.makeText(context, "Username and password verified success.", Toast.LENGTH_SHORT).show();
                    }
                }else
                {
                    Toast.makeText(context, "Username and password is not correct.", Toast.LENGTH_SHORT).show();
                }
            }
        });


        Button removeButton = (Button)findViewById(R.id.shared_preference_remove_button);
        removeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, MODE_PRIVATE);

                Editor editor = sharedPreferences.edit();

                editor.remove(SHARED_PREFERENCES_KEY_PASSWORD);

                editor.commit();

                Toast.makeText(context, "Remove saved username from shared preferences successfully.", Toast.LENGTH_SHORT).show();
            }
        });

        Button clearButton = (Button)findViewById(R.id.shared_preference_clear_button);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, MODE_PRIVATE);

                Editor editor = sharedPreferences.edit();

                editor.clear();

                editor.commit();

                Toast.makeText(context, "Clear saved username and password successfully.", Toast.LENGTH_SHORT).show();
            }
        });

        Button reloadButton = (Button)findViewById(R.id.shared_preference_reload_button);
        reloadButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                initLoginForm(context, userNameEditText, passwordEditText, rememberAccountCheckbox);

                Toast.makeText(context, "Reload username and password from shared preferences successfully.", Toast.LENGTH_SHORT).show();
            }
        });
    }

    // This method is used to load data from SharedPreferences object \,
    // And set those data value in related UI control.
    private void initLoginForm(Context context, EditText userNameEditText, EditText passwordEditText, CheckBox rememberAccountCheckbox)
    {
        String savedUserName = readValueFromSharedPreferences(context, SHARED_PREFERENCES_KEY_USERNAME);

        String savedPassword = readValueFromSharedPreferences(context, SHARED_PREFERENCES_KEY_PASSWORD);

        String rememberAccount = readValueFromSharedPreferences(context, SHARED_PREFERENCES_KEY_REMEMBER_ACCOUNT);

        userNameEditText.setText(savedUserName);

        passwordEditText.setText(savedPassword);

        rememberAccountCheckbox.setChecked(Boolean.valueOf(rememberAccount));
    }

    // Write data to SharedPreferences object.
    private void writeToSharedPreferences(Context context, String userName, String password, boolean rememberAccount)
    {
        // Get SharedPreferences object, the shared preferences file name is this activity class name.
        SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, MODE_PRIVATE);

        Editor editor = sharedPreferences.edit();

        editor.putString(SHARED_PREFERENCES_KEY_USERNAME, userName);

        editor.putString(SHARED_PREFERENCES_KEY_PASSWORD, password);

        editor.putBoolean(SHARED_PREFERENCES_KEY_REMEMBER_ACCOUNT, rememberAccount);

        editor.apply();
    }

    // Get key related value in SharedPreferences object.
    private String readValueFromSharedPreferences(Context context, String key)
    {
        // Get SharedPreferences object, the shared preferences file name is this activity class name.
        SharedPreferences sharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_FILE_NAME, MODE_PRIVATE);

        String ret = "";

        if(SHARED_PREFERENCES_KEY_REMEMBER_ACCOUNT.equalsIgnoreCase(key))
        {
            boolean value = sharedPreferences.getBoolean(key, false);
            ret = String.valueOf(value);
        }else {
            ret = sharedPreferences.getString(key, "");
        }

        return ret;
    }
}
(Visited 1,429 times, 2 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.