Android Sharedpreferences Save/Load Java Object Example

Android SharedPreferences 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 show you how to do that.

1. Convert Java Objects To Json String.

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

We recommend Gson which is a free open source java Json library. It provide 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 below steps to add Gson library in android project.

  1. Change to Project view in android studio left panel dropdown list.
  2. Double click build.gradle file to open it.
  3. Add below code in right panel dependencies section.
    compile ''

    add gson java library in android project

  4. After above configuration, click Sync Now link in top right corner, after synchronize, you can use 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 translate 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 translate json string to 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 have two buttons. Click the first button will save a list of UserInfoDTO java objects’s json format string to SharedPreferences.

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.

android shared preferences save load java objects example

When you click the first button, you can use android device monitor to see the saved 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

The content of the shared preferences file userInfoList.xml.

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

2.1 Layout Xml File.



        android:text="Save User List To Sharedpreferences"/>

        android:text="Load User List From Sharedpreferences"/>


2.2 Activity Java File.


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

import com.dev2qa.example.R;

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";

    protected void onCreate(Bundle savedInstanceState) {

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

        // Save UserInfoDTO list json format string to SharedPreferences button.
        Button saveUserListButton = (Button)findViewById(;
        saveUserListButton.setOnClickListener(new View.OnClickListener() {
            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);

                // 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(;
        loadUserListButton.setOnClickListener(new View.OnClickListener() {
            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(" , Password : ");
                    userInfoBuf.append(" , Email : ");

                    // 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.setEmail("[email protected]");

        UserInfoDTO user2 = new UserInfoDTO();
        user2.setEmail("[email protected]");

        return ret;


  1. Google-gson
  2. Android Shared Preferences Example
(Visited 1,879 times, 6 visits today)
READ :   Android Combine Custom And General Gestures Example

Leave a Reply

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

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