Store Array List in Shared Preference Android

Updated 29 December 2023


In this blog, we will explore the Store Array lists in Shared Preference Android by using two ways. so let’s get started.

For storing a list of objects (String used in this article or any other object) into Shared preference. first, we need to convert List<String> into a string. we easily convert a list of objects in Java or Kotlin into a JSON string using GSON.

1. Change the ArrayList into GSON

Gson is a Java library that can be used to convert Java Objects into their JSON representation and It can also be used to convert a JSON string to an equivalent Java object.

Before using GSON in our project, please add the below dependency to your app-level Gradle file.

After adding a dependency, now we are creating an Array list in Android because we need an array list.

You can see the above code, we have created an array list and stored some string values. now we are Converting the List of objects into JSON string because we need to convert the array list into the string.

In this code, we are converting our data array list into the string by using the GSON library.

We are creating a Shared Preference Editor and storing our converted data into Shared Preference.

Accessing stored JSON string from shared preference as List of Object.

Here, type is used to tell Gson that we want this JSON to be translated to a List of Strings.

2. Change the ArrayList into HashSet

You might save your list in a hash set or a similar format after converting it. After reading it back, you can transform it into an ArrayList, arrange it as necessary, and you’re set to go.

In the above code, we are changing our Array list into the HashSet and storing the shared preference.

Thanks for reading this blog, you can also check other blogs from here for more knowledge.

Happy Coding and always welcome your feedback.

. . .

Leave a Comment

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

Be the first to comment.

Start a Project

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home