Android SharedPreferences Save/Load Java Object Example

Android SharedPreferences object can be used to store primitive java type data such as int, long, float, boolean, String, etc. It can also be used to save or load custom java objects. This article will tell you how to save objects in SharedPreferences android example.

1. Convert Java Objects To JSON String.

Before saving objects in SharedPreferences, you need first convert the java objects into JSON string. Then save that string in the android SharedPreferences object.

We recommend Gson which is a free open source java Json library. It provides methods to convert java objects to JSON string and vice versa.

1.1 Add Gson Library In Android Project.

To use Gson in android, you need first follow the below steps to add the Gson library in the android project.

  1. Change to Project view in the android studio left panel drop-down list.
  2. Double click the build.gradle file to open it.
  3. Add the below code in the right panel dependencies section.
    compile 'com.google.code.gson:gson:2.8.2'

    add-gson-java-library-in-android-project

  4. After the above configuration, click Sync Now link in the top right corner, after synchronizing, you can use the Gson library in your android code.

1.2 Use Gson To Convert Java Objects To JSON String.

1.2.1 Get Json String From Java Objects.

Gson class’s toJson() method is used to convert the java object list to JSON string. The input parameter is the java objects List.

List<UserInfoDTO> initialUserInfoList = initUserInfoList();
Gson gson = new Gson();
String userInfoListJsonString = gson.toJson(initialUserInfoList);
1.2.2 Get Java Object Array From JSON String.

Gson class’s fromJson() method can convert JSON string to a java object array. The first input parameter is the JSON string. The second input parameter is the returned java object array class.

Gson gson = new Gson();
UserInfoDTO userInfoDtoArray[] = gson.fromJson(userInfoListJsonString, UserInfoDTO[].class);

2. Save/Load Java Objects Via SharedPreferences Example.

This example has two buttons. Click the first button will save a list of UserInfoDTO java objects’ JSON format string to the android SharedPreferences object.

Click the second button will read the JSON String from SharedPreferences and convert the JSON string to UserInfoDTO array. It will also print each user info in the android monitor as debug log text. You can see the demo video from the link https://youtu.be/1YvY2OLGlDw.

When you click the first button, you can use the android device monitor to see the saved android SharedPreferences file as below. Please refer Android Device Monitor Cannot Open Data Folder Resolve Method to learn how to use it.

android-sharedpreferences-saved-file

Below is the content of the shared preferences file userInfoList.xml.

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<map>
   <string name="User_Info_List">
      [{"email":"[email protected]","password":"123456","userName":"richard"},{"email":"[email protected]","password":"123456","userName":"jerry"}]
   </string>
</map>

2.1 Layout XML File.

activity_shared_preference_store_object.xml

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

    <Button
        android:id="@+id/shared_preference_save_user_list_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save User List To Sharedpreferences"/>

    <Button
        android:id="@+id/shared_preference_load_user_list_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Load User List From Sharedpreferences"/>

</LinearLayout>

2.2 Activity Java File.

SharedPreferenceStoreObjectActivity.java

package com.dev2qa.example.storage.sharedpreferences;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.dev2qa.example.R;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class SharedPreferenceStoreObjectActivity extends AppCompatActivity {

    // This is the sharedpreferences file that is used to save UserInfoDTO list.
    private final static String SHARED_PREFERENCES_FILE_USER_INFO_LIST = "userInfoList";

    // This is the saved UserInfoDTO list jason string key in sharedpreferences file..
    private final static String SHARED_PREFERENCES_KEY_USER_INFO_LIST = "User_Info_List";

    // This is the debug log info tag which will be printed in the android monitor console.
    private final static String USER_INFO_LIST_TAG = "USER_INFO_LIST_TAG";

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

        setTitle("dev2qa.com - Android Sharedpreferences Save Load Java Object Example. ");

        // Save UserInfoDTO list json format string to SharedPreferences button.
        Button saveUserListButton = (Button)findViewById(R.id.shared_preference_save_user_list_button);
        saveUserListButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // First initialize a list of UserInfoDTO.
                List<UserInfoDTO> initialUserInfoList = initUserInfoList();

                // Create Gson object.
                Gson gson = new Gson();

                // Get java object list json format string.
                String userInfoListJsonString = gson.toJson(initialUserInfoList);

                // Create SharedPreferences object.
                Context ctx = getApplicationContext();
                SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREFERENCES_FILE_USER_INFO_LIST, MODE_PRIVATE);

                // Put the json format string to SharedPreferences object.
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString(SHARED_PREFERENCES_KEY_USER_INFO_LIST, userInfoListJsonString);
                editor.commit();

                // Popup a toast message in screen bottom.
                Toast.makeText(ctx, "User info DTO list has been saved in sharedpreferences file.", Toast.LENGTH_SHORT).show();

            }
        });

        // Load json string from sharedpreferences and translate it to java object array.
        Button loadUserListButton = (Button)findViewById(R.id.shared_preference_load_user_list_button);
        loadUserListButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Create SharedPreferences object.
                Context ctx = getApplicationContext();
                SharedPreferences sharedPreferences = ctx.getSharedPreferences(SHARED_PREFERENCES_FILE_USER_INFO_LIST, MODE_PRIVATE);

                // Get saved string data in it.
                String userInfoListJsonString = sharedPreferences.getString(SHARED_PREFERENCES_KEY_USER_INFO_LIST, "");

                // Create Gson object and translate the json string to related java object array.
                Gson gson = new Gson();
                UserInfoDTO userInfoDtoArray[] = gson.fromJson(userInfoListJsonString, UserInfoDTO[].class);

                // Loop the UserInfoDTO array and print each UserInfoDTO data in android monitor as debug log.
                int length = userInfoDtoArray.length;
                for(int i=0;i<length;i++)
                {
                    // Get each user info in dto.
                    UserInfoDTO userInfoDto = userInfoDtoArray[i];
                    StringBuffer userInfoBuf = new StringBuffer();
                    userInfoBuf.append("UserName : ");
                    userInfoBuf.append(userInfoDto.getUserName());
                    userInfoBuf.append(" , Password : ");
                    userInfoBuf.append(userInfoDto.getPassword());
                    userInfoBuf.append(" , Email : ");
                    userInfoBuf.append(userInfoDto.getEmail());

                    // Print debug log in android monitor console.Debug info tag is USER_INFO_LIST_TAG.
                    Log.d(USER_INFO_LIST_TAG, userInfoBuf.toString());
                }
            }
        });
    }

    // Used to initialize a list of UserInfoDTO objects.
    private List<UserInfoDTO> initUserInfoList()
    {
        List<UserInfoDTO> ret = new ArrayList<UserInfoDTO>();

        UserInfoDTO user1 = new UserInfoDTO();
        user1.setUserName("richard");
        user1.setPassword("123456");
        user1.setEmail("[email protected]");
        ret.add(user1);

        UserInfoDTO user2 = new UserInfoDTO();
        user2.setUserName("jerry");
        user2.setPassword("123456");
        user2.setEmail("[email protected]");
        ret.add(user2);

        return ret;
    }
}

References:

  1. Google-Gson
  2. Android Shared Preferences Example
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Riley
Riley

The article is perfect, it help me to solve my problem. In my case, I want to save a product list when user add them to shopping cart, and when user confirmed to checkout, I will read out all the product he collected and submit the product list JSON string to a web service. The andorid SharedPreferences object is just the right one to use for my requirements. And Gson is just the correct library which can be used to convert product list java object to JSON string vice versa. Thanks for the author, keep reading.

1
0
Would love your thoughts, please comment.x
()
x