We all know that Android only allows primitives types like int, float to be stored in preferences.
But we can change this with the help of GSON.
If you want to know more about GSON, you can refer my post here…

Using GSON in Android – Simple Demo

Now, In this demo, I will show you how to store a class object in android preferences.

Non Primitive Android Preferences

Here I will use a simple user class which will be stored in preferences and retreived.

User

package gradle_demo.coderzheaven.com.nonprimitivepreferences;

public class User {

    String firstName;
    String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

Layout

A simple layout for demonstration.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    android:orientation="vertical"
    android:padding="20dp"
    tools:context="gradle_demo.coderzheaven.com.nonprimitivepreferences.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Storing Non Primitive Objects in Shared Preferences"
        android:textColor="@android:color/black"
        android:textSize="25sp"
        android:textStyle="bold" />

    <EditText
        android:id="@+id/firstName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="first name" />

    <EditText
        android:id="@+id/lastName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:hint="last name"
        android:lines="1" />

    <Button
        android:id="@+id/btnStore"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:lines="1"
        android:text="Store Object in Shared Preferences" />

    <Button
        android:id="@+id/btnRetrieve"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Get Object from Shared Preferences" />

    <TextView
        android:id="@+id/tvDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:text=""
        android:textColor="@android:color/black"
        android:textStyle="bold" />

</LinearLayout>

MainActivity

I think the code itself is pretty descriptive so that you can follow easily.

package gradle_demo.coderzheaven.com.nonprimitivepreferences;

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

import com.google.gson.Gson;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    public static final String MY_PREFS_NAME = "Pref";
    public static final String OBJECT_KEY = "user";
    private Gson gson;
    private Button btnStore, btnRetrieve;
    private EditText edFirstName, edLastName;
    private TextView tvDisplay;

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

        btnStore = findViewById(R.id.btnStore);
        btnRetrieve = findViewById(R.id.btnRetrieve);
        tvDisplay = findViewById(R.id.tvDisplay);
        edFirstName = findViewById(R.id.firstName);
        edLastName = findViewById(R.id.lastName);

        btnStore.setOnClickListener(this);
        btnRetrieve.setOnClickListener(this);

        gson = new Gson();
    }

    @NonNull
    private void storeObject(User user) {
        // Convert User Object to Json String
        String json = gson.toJson(user);
        // Store the Json String in Shared Preferences
        store(OBJECT_KEY, json);
        Toast.makeText(this, "User Stored in preferences", Toast.LENGTH_SHORT).show();
    }

    private User getObject() {
        // Get the Stored object as String
        String userStr = get(OBJECT_KEY);
        // Convert back to object using GSON
        User user = gson.fromJson(userStr, User.class);
        return user;
    }

    @NonNull
    private User createUser(String firstName, String secondName) {
        User user = new User();
        user.setFirstName(firstName);
        user.setLastName(secondName);
        return user;
    }

    void store(String key, String value) {
        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString(key, value);
        editor.apply();
    }

    String get(String key) {
        SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
        return prefs.getString(key, null);
    }

    @Override
    public void onClick(View view) {
        if (view == btnStore) {
            String fName = edFirstName.getText().toString().trim();
            String lName = edLastName.getText().toString().trim();
            if (fName.isEmpty() || lName.isEmpty()) {
                Toast.makeText(this, "Fields empty", Toast.LENGTH_SHORT).show();
                return;
            }
            User user = createUser(fName, lName);
            storeObject(user);
            return;
        }

        if (view == btnRetrieve) {
            User user = getObject();
            if (null != user)
                tvDisplay.setText("Firstname :: " + user.firstName + "\nLastname :: " + user.getLastName());
        }
    }
}

Code

You can download the complete source code from here.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

 

 

 

Theme by HermesThemes

Copyright © 2018 CoderzHeaven. All Rights Reserved

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.