Saturday, March 26, 2016

android - Save an ArrayList to 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"
    android:background="#f7fbff"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:textSize="25dp"
        android:textStyle="italic"
        />
    <Button
        android:id="@+id/btn_save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save List To SharedPreferences"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Read List From SharedPreferences"
        android:layout_toRightOf="@id/btn_save"
        android:layout_toEndOf="@id/btn_save"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
res/values/strings.xml

<resources>

    <string name="app_name">Android Example</string>
    <string name="title_activity_settings">Settings</string>
    <string name="title_activity_main">Android Example - SharedPreferences Save ArrayList</string>

    <!-- shared preferences keys-->
    <string name="sp_key_colors">colors_list</string>

</resources>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
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.RelativeLayout;
import android.widget.TextView;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;


public class MainActivity extends AppCompatActivity {

    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private Button mButtonSave;
    private Button mButtonRead;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor mEditor;


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

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

        // Get the activity
        mActivity = MainActivity.this;

        // Initialize the SharedPreference object
        mSharedPreferences = getPreferences(Context.MODE_PRIVATE);

        // Get SharedPreferences editor
        mEditor = mSharedPreferences.edit();

        // Get the widgets reference from XML layout
        mRelativeLayout = (RelativeLayout) findViewById(R.id.rl);
        mTextView = (TextView) findViewById(R.id.tv);
        mButtonSave = (Button) findViewById(R.id.btn_save);
        mButtonRead = (Button) findViewById(R.id.btn_read);

        // Set a click listener for save button
        mButtonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // Initialize a new ArrayList with bvalues
                List<String> colorsList = Arrays.asList(
                        "Red",
                        "Green",
                        "Blue",
                        "Yellow",
                        "Black"
                );

                // Initialize a new Set
                Set colorsSet = new HashSet();

                // add all the colors to the Set
                colorsSet.addAll(colorsList);

                // Put an ArrayList to SharedPreferences
                mEditor.putStringSet(
                        getResources().getString(R.string.sp_key_colors),
                        colorsSet
                );
                mEditor.apply();

                // Change the TextView text color
                mTextView.setTextColor(Color.BLUE);

                // Display the SharedPreferences saved colors list on TextView
                mTextView.setText("The following colors list saved to SharedPreferences...");

                // Iterate through the list
                for (String color : colorsList){
                    mTextView.setText(mTextView.getText() + "\n" + color);
                }
            }
        });

        // Set a click listener for read button
        mButtonRead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Read the values from SharedPreferences
                Set<String> colorsSet = mSharedPreferences.getStringSet(
                        getResources().getString(R.string.sp_key_colors),
                        null
                );

                // Set text for TextView
                mTextView.setText("This colors list retrieved from SharedPreferences...");

                // Change the TextView text color
                mTextView.setTextColor(Color.MAGENTA);

                // Display the retrieved colors to TextView
                for(String color : colorsSet){
                    mTextView.setText(mTextView.getText() + "\n" + color);
                }
            }
        });
    }
}