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 'com.google.code.gson:gson:2.8.2'

    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"?>
<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
(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.