Shared Preferences. How to store objects and primitive values

Shared preferences are easy and convenient way to store small chunks of data. In this tutorial, we will store objects as well as primitive variables (Strings, Integers, etc).

first, import this library in your build.gradle(Module:app)

build.gradle(Module:app)
compile 'com.google.code.gson:gson:2.7'

Design a layout for main activity:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="pdf.tutorials.virtuoza.virtuozatutorials.MainActivity">

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

    <TextView
        android:id="@+id/string"
        android:text="String: "
        android:textColor="#000"
        android:textSize="18sp"
        android:layout_margin="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/integer"
        android:text="Int: "
        android:textColor="#000"
        android:textSize="18sp"    android:layout_margin="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    <TextView
        android:id="@+id/bool"
        android:text="Boolean: "
        android:textColor="#000"
        android:textSize="18sp"   android:layout_margin="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/decimal"
        android:text="Decimal: "
        android:textColor="#000"
        android:textSize="18sp"  android:layout_margin="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/object"
        android:text="Object username: "
        android:textColor="#000"
        android:textSize="18sp"  android:layout_margin="15dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />


    </LinearLayout>

        <Button
            android:id="@+id/btn_show"
            android:text="FETCH VALUES"
            android:layout_alignParentBottom="true"
            android:layout_marginBottom="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />




</RelativeLayout>

Create User class, so we can later create object to store into shared preferences:

User.java
package pdf.tutorials.virtuoza.virtuozatutorials;

/**
 * Created by azem on 12/21/17.
 */

public class User {

    private String userName;
    private String password;

    public User() {
    }

    public User(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }


}

And finally, MainActivity:

MainActivity.java
package pdf.tutorials.virtuoza.virtuozatutorials;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

public class MainActivity extends AppCompatActivity {

    TextView integerTextView, stringTextView, boolTextView, decimalTextView, objectTextView;
    Button show;

    public static String MY_PREFS_NAME= "nameOfSharedPreferences";

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

        integerTextView=(TextView)findViewById(R.id.integer);
        stringTextView=(TextView)findViewById(R.id.string);
        boolTextView=(TextView)findViewById(R.id.bool);
        decimalTextView=(TextView)findViewById(R.id.decimal);
        objectTextView=(TextView)findViewById(R.id.object);

        show = (Button)findViewById(R.id.btn_show);


        show.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //retrieve primitive values
                SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
                String string = prefs.getString("name", null);
                int i = prefs.getInt("id",0);
                boolean bool = prefs.getBoolean("bool",false);
                float f = prefs.getFloat("decimal",0);


                //retrieve objects
                Gson gson = new Gson();
                String json = prefs.getString("user", "");
                User obj = gson.fromJson(json, User.class);
                String objectUsername=obj.getUserName();
                
                // set fetched texts to textViews 
                integerTextView.setText(integerTextView.getText()+String.valueOf(i));
                stringTextView.setText(stringTextView.getText()+string);
                boolTextView.setText(boolTextView.getText()+String.valueOf(bool));
                decimalTextView.setText(decimalTextView.getText()+String.valueOf(f));
                objectTextView.setText(objectTextView.getText()+String.valueOf(objectUsername));

            }
        });


        // storing primitive values
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString("name", "HellBoy");
        editor.putInt("id", 100);
        editor.putBoolean("bool", true);
        editor.putFloat("decimal",1.23f);
        editor.apply();


        // storing objects
        User user = new User("username","password");
        Gson gson = new Gson();
        String json = gson.toJson(user);
        editor.putString("user", json);
        editor.commit();



    }
}

And that’s it.
This is very nice way to use shared preferences.

Share with your friends