Android SharedPreferences Example

Android SharedPreferences use key-value pairs to store data. This is an 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 Android SharedPreferences Object.

The key and value data saved in the android SharedPreferences object is finally saved in an 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

If you want to find and browse the above shared_prefs folder, you may need to use the android device monitor, 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 provides below three methods to get the 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 the SharedPreferences object.
  2. The second parameter is the file creation 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 the same as 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 the 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 the shared preferences file does not need an editor. The SharedPreferences object just provides the 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 the above introduction, we can see that the android SharedPreferences object is very suitable to be used to operate application settings data. So this example will use SharedPreferences to save user login username and password. You can see the demo video from the link https://youtu.be/BhHi3muNLMI. Below is the example description.

  1. The android app will use the android SharedPreferences object to save user login credentials include the username and password.
  2. There are 2 input text boxes, the first one is the user name input textbox, the second one is the password input textbox.
  3. There are 4 buttons. The first button has the label text VERIFY ACCOUNT. When you click this button it will check whether the username and password are correct or not. The user account info is hardcoded in the source code.
  4. If the login username and password are correct, and if the user checked the Remember UserName Password checkbox, it will write the user name and password to the android SharedPreferences object to save it and prompt login username and password are correct.
  5. If the username and password are not correct, it will just prompt the user that the login username and password are incorrect.
  6. The second button is the REMOVE PASSWORD button, when you click this button, it will remove the saved login password only from the android SharedPreferences object and prompt a toast message.
  7. The third button is the CLEAR SAVED ACCOUNT button, when you click this button, it will clear all the data in the android SharedPreferences object.
  8. The fourth button is the RELOAD SHARED PREFERENCES DATA button, when you click this button if the android SharedPreferences save data are not cleared, it will load those data and use the data to initialize the login username, password, and the Remember UserName Password checkbox.

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;
    }
}
0 0 votes
Article Rating
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x