Storing data in SharedPreferences – Android

In previous post Store Data – SharedPreferences – Android we discussed about cases, when we should save data in SharedPreferences. Here is a demo Android App for the same.

Create a new Android project using following information.

Project Name SharedPreference Demo
Package Name com.pcsalt.example.sharedpreferencedemo
Minimum SDK Version 16
Activity Type Empty Activity
Activity Name MainActivity
Layout Name activity_name

Adding dependencies in build.gradle

In this tutorial we are going to display all saved keys and values in RecyclerView. So, following dependency needs to be added into SharedPreferenceDemo/app/build.gradle.

dependencies {
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:recyclerview-v7:23.0.1'
}


(adsbygoogle = window.adsbygoogle || []).push({});

Update layout of activity_main.xml

By default, activity_main.xml comes with RelativeLayout as parent Layout and a TextView with Hello world text. Update this layout to have:
– two EditText for Key and Value,
– one Button to save Key and Value pair in SharedPreferences, and
– a RecyclerView to display all saved values in SharedPreferences.



    
    
    
    

Create list item for RecyclerView

The RecyclerView would display the saved key, value pair in a list. So, create a resource file list_item_pref.xml



    
    
    

Create Utility classes

It is a good idea to keep things separate, if it does not do the similar thing. For this purpose, we have two utility classes.
– Utility.java : for getting text from EditText.
– PrefUtil.java : for performing basic operations on SharedPreferences.

Create Utility.java

package com.pcsalt.example.sharedpreferencedemo;
import android.widget.TextView;
/**
 * Created by krrishnaaaa on Oct 02, 2015
 */
public final class Utility {
    public static String getText(TextView textView) {
        String text = "";
        if (textView != null) {
            text = textView.getText().toString();
        }
        return text;
    }
}

Create PrefUtil.java

package com.pcsalt.example.sharedpreferencedemo;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * Created by krrishnaaaa on Oct 02, 2015
 */
public final class PrefUtil {
    private static SharedPreferences getPref(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }
    public static void saveString(Context context, String key, String value) {
        getPref(context).edit().putString(key, value).apply();
    }
    public static String getString(Context context, String key, String defValue) {
        return getPref(context).getString(key, defValue);
    }
    public static void removeString(Context context, String key) {
        getPref(context).edit().remove(key).apply();
    }
    public static List getAllValues(Context context) {
        Map values = getPref(context).getAll();
        List prefDataList = new ArrayList();
        for (Map.Entry entry : values.entrySet()) {
            PrefData prefData = new PrefData();
            prefData.key = entry.getKey();
            prefData.value = entry.getValue().toString();
            prefDataList.add(prefData);
        }
        return prefDataList;
    }
}

Create model class PrefData.java

This model class would hold the key and value stored in SharedPreferences and list of this model would be displayed in RecyclerView.

package com.pcsalt.example.sharedpreferencedemo;
/**
 * Created by krrishnaaaa on Oct 02, 2015
 */
public final class PrefData {
    public String key;
    public String value;
    public PrefData() {
    }
    public PrefData(String key, String value) {
        this.key = key;
        this.value = value;
    }
    @Override
    public boolean equals(Object object) {
        return object instanceof PrefData && key.equals(((PrefData) object).key);
    }
    @Override
    public int hashCode() {
        return super.hashCode();
    }
}

Create Adapter for RecyclerView

This adapter will hold and display the key value stored in SharedPreferences.

package com.pcsalt.example.sharedpreferencedemo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.List;
/**
 * Created by krrishnaaaa on Oct 02, 2015
 */
public class PrefAdapter extends RecyclerView.Adapter {
    private LayoutInflater mLayoutInflater;
    private List mPrefDataList;
    public PrefAdapter(Context context, List prefDataList) {
        this.mLayoutInflater = LayoutInflater.from(context);
        this.mPrefDataList = prefDataList;
    }
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mLayoutInflater.inflate(R.layout.list_item_pref, parent, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (holder instanceof ViewHolder) {
            ViewHolder viewHolder = (ViewHolder) holder;
            PrefData current = mPrefDataList.get(position);
            viewHolder.textViewKey.setText(current.key);
            viewHolder.textViewValue.setText(current.value);
        }
    }
    @Override
    public int getItemCount() {
        if (mPrefDataList != null) {
            return mPrefDataList.size();
        } else {
            return 0;
        }
    }
    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textViewKey, textViewValue;
        public ViewHolder(View itemView) {
            super(itemView);
            textViewKey = (TextView) itemView.findViewById(R.id.text_view_key);
            textViewValue = (TextView) itemView.findViewById(R.id.text_view_value);
        }
    }
}

Update MainActivity.java to store and display contents to/from SharedPreferences

MainActivity will be performing following tasks:
– Link all views from its layout
– Save key and value from EditText in SharedPreferences
– Update RecyclerView with the values stored in SharedPreferences

package com.pcsalt.example.sharedpreferencedemo;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.pcsalt.example.sharedpreferencedemo.listener.RecyclerClickListener;
import com.pcsalt.example.sharedpreferencedemo.listener.RecyclerTouchListener;
import java.util.List;
public class MainActivity extends AppCompatActivity {
    private Context mContext = MainActivity.this;
    private EditText mEditTextKey;
    private EditText mEditTextValue;
    private List mPrefDataList;
    private PrefAdapter mPrefAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
    }
    private void initViews() {
        mEditTextKey = (EditText) findViewById(R.id.edit_text_key);
        mEditTextValue = (EditText) findViewById(R.id.edit_text_value);
        Button buttonSave = (Button) findViewById(R.id.button_save);
        buttonSave.setOnClickListener(mOnClickListener);
        RecyclerView recyclerViewPrefValues = (RecyclerView) findViewById(R.id.recycler_view_pref_values);
        recyclerViewPrefValues.setLayoutManager(new LinearLayoutManager(mContext));
        mPrefDataList = PrefUtil.getAllValues(mContext);
        mPrefAdapter = new PrefAdapter(mContext, mPrefDataList);
        recyclerViewPrefValues.setAdapter(mPrefAdapter);
        RecyclerTouchListener recyclerTouchListener = new RecyclerTouchListener(mContext, recyclerViewPrefValues, new RecyclerClickListener() {
            @Override
            public void onClick(View view, int position) {
                PrefData prefData = mPrefDataList.get(position);
                PrefUtil.removeString(mContext, prefData.key);
                mPrefDataList.remove(position);
                mPrefAdapter.notifyItemRemoved(position);
            }
        });
        recyclerViewPrefValues.addOnItemTouchListener(recyclerTouchListener);
    }
    private void saveValueInPref() {
        String key = Utility.getText(mEditTextKey);
        String value = Utility.getText(mEditTextValue);
        if (key.isEmpty()) {
            mEditTextKey.setError("Enter key");
        } else if (value.isEmpty()) {
            mEditTextValue.setError("Enter value");
        } else {
            PrefUtil.saveString(mContext, key, value);
            mEditTextKey.setText("");
            mEditTextValue.setText("");
            PrefData newPrefData = new PrefData(key, value);
            if (mPrefDataList.contains(newPrefData)) {
                int index = mPrefDataList.indexOf(newPrefData);
                mPrefDataList.remove(index);
                mPrefAdapter.notifyItemRemoved(index);
            }
            mPrefDataList.add(newPrefData);
            int position = mPrefAdapter.getItemCount() - 1;
            mPrefAdapter.notifyItemInserted(position);
        }
    }
    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.button_save:
                    saveValueInPref();
                    break;
            }
        }
    };
}

Download source code

Working source code is shared on GitHub – SharedPreference-Demo