Friday, October 16, 2015

android - How to use SharedPreferences

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity"
    >
    <TextView
        android:id="@+id/tv"
        android:text=""
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:textSize="25dp"
        />
    <EditText
        android:id="@+id/et"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="Which is your favorite software?"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/et"
        android:text="Save to SharedPreferences"
        />
    <Button
        android:id="@+id/btn_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toEndOf="@id/btn_save"
        android:layout_toRightOf="@id/btn_save"
        android:layout_below="@id/et"
        android:text="Read from SharedPreferences"
        />
    <Button
        android:id="@+id/btn_edit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/btn_save"
        android:text="Edit and Save SharedPreferences Data"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcode;

import android.content.Context;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.content.SharedPreferences;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private String mKey_favorite_software = "key_favorite_software";

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

        // Get the application context
        mContext = getApplicationContext();

        // Get the widgets reference from XML layout
        RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final TextView tv = (TextView) findViewById(R.id.tv);
        final EditText et = (EditText) findViewById(R.id.et);
        Button btn_save = (Button) findViewById(R.id.btn_save);
        Button btn_read = (Button) findViewById(R.id.btn_read);
        Button btn_edit = (Button) findViewById(R.id.btn_edit);

        /*
            Write/save to SharedPreferences
            Read from SharedPreferences
            Edit SharedPreferences data
        */

        /*
            To write key-value data on Shared Preferences file, we need to create
            a SharedPreferences editor by calling edit() method on your SharedPreferences.

            Pass the keys and values you want to write with methods such as putInt()
            and putString(). Then call commit() to save the changes.
        */

        final SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);

        /*
            SharedPreferences.Editor
                Interface used for modifying values in a SharedPreferences object. All
                changes you make in an editor are batched, and not copied back to the
                original SharedPreferences until you call commit() or apply()
        */
        final SharedPreferences.Editor editor = sp.edit();


        // Set a click listener for sabe button
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /*
                    public abstract SharedPreferences.Editor putString (String key, String value)
                        Set a String value in the preferences editor, to be written back once
                        commit() or apply() are called.

                        Parameters
                            key : The name of the preference to modify.
                            value : The new value for the preference.
                        Returns
                            Returns a reference to the same Editor object, so you can chain put
                            calls together.
                */
                /*
                    More way to put data on SharedPreferences

                    putBoolean(String key, boolean value)
                        Set a boolean value in the preferences editor, to be written back
                        once commit() or apply() are called.

                    putFloat(String key, float value)
                        Set a float value in the preferences editor, to be written back once
                        commit() or apply() are called.

                    putInt(String key, int value)
                        Set an int value in the preferences editor, to be written back once
                        commit() or apply() are called.

                    putLong(String key, long value)
                        Set a long value in the preferences editor, to be written back once
                        commit() or apply() are called.

                    putStringSet(String key, Set<String> values)
                        Set a set of String values in the preferences editor, to be written
                        back once commit() or apply() is called.
                */
                editor.putString(mKey_favorite_software, et.getText().toString());

                /*
                    public abstract boolean commit ()
                        Commit your preferences changes back from this Editor to the SharedPreferences
                        object it is editing. This atomically performs the requested modifications,
                        replacing whatever is currently in the SharedPreferences.
                */
                //editor.commit();

                /*
                    public abstract void apply ()
                        Commit your preferences changes back from this Editor to the SharedPreferences
                        object it is editing. This atomically performs the requested modifications,
                        replacing whatever is currently in the SharedPreferences.
                */
                editor.apply();

                // Confirm the submission.
                tv.setTextColor(Color.BLACK);
                tv.setText("Saved on SharedPreferences : " + et.getText().toString());

                // Empty the EditText after saving the text in SharedPreferences
                et.setText("");
                et.setHint("Put new text to update old data");
            }
        });

        // Set an click listener for read button
        btn_read.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Read data from SharedPreferences
                /*
                    public abstract String getString (String key, String defValue)
                        Retrieve a String value from the preferences.

                    Parameters
                        key : The name of the preference to retrieve.
                        defValue : Value to return if this preference does not exist.

                    Returns
                        Returns the preference value if it exists, or defValue. Throws ClassCastException
                        if there is a preference with this name that is not a String.
                    Throws
                        ClassCastException
                */
                /*
                    More ways to read various data from SharedPreferences

                    getBoolean(String key, boolean defValue)
                        Retrieve a boolean value from the preferences.

                    getFloat(String key, float defValue)
                        Retrieve a float value from the preferences.

                    getInt(String key, int defValue)
                        Retrieve an int value from the preferences.

                    getLong(String key, long defValue)
                        Retrieve a long value from the preferences.

                    getStringSet(String key, Set<String> defValues)
                        Retrieve a set of String values from the preferences.

                    getAll()
                        Retrieve all values from the preferences.
                */
                String favoriteSoftware = sp.getString(mKey_favorite_software,"");

                // Display the data back from SharedPreferences
                tv.setTextColor(Color.BLUE);
                tv.setText("Read from SharedPreferences : " + favoriteSoftware);
            }
        });

        // Set a click listener for edit button
        btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Edit/Overwrite SharedPreferences data
                /*
                    It will overwrite your EditText new inputted value to SharedPreferences
                    existing value based on key.
                 */
                editor.putString(mKey_favorite_software,et.getText().toString());

                // Confirm about edit
                tv.setTextColor(Color.RED);
                tv.setText("Edited and saved SharedPreferences : " + et.getText().toString());

                // Empty the EditText
                et.setText("");
            }
        });

        /*
            More SharedPreferences.Editor functionality

            clear()
                Mark in the editor to remove all values from the preferences.

            remove(String key)
                Mark in the editor that a preference value should be removed, which will be
                done in the actual preferences once commit() is called.
        */
    }
}





More android examples