Open In App

Android – Save ArrayList to SharedPreferences with Kotlin

Last Updated : 15 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

SharedPreferences is local storage in android which is used to store data in the form of key and value pairs within the android devices. We can store data in the form of key and value pairs using Shared Preferences. In this article, we will take a look at How to Save Array List to SharedPreferences in Android using Kotlin. A sample video is given below to get an idea about what we are going to do in this article.

Note: If you are looking to implement How to Save Array List to Shared Preferences in Android using Java. Check out the following article: How to Save ArrayList to SharedPreferences in Android using Java

Step-by-Step Implementation:

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Adding dependency for gson in build.gradle

Navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.

implementation 'com.google.code.gson:gson:2.8.5'

After adding this dependency simply sync your project to install it. 

Step 3: Creating a modal class for storing our data

Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class and name your class as CourseRVModal and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
data class CourseRVModal(
    // on below line we are creating a two
    // variable one for course name
    // and other for course image.
    var courseName: String,
    var courseImg: Int
)


Step 4: Creating a layout file for our item of RecyclerView

Navigate to the app > res > layout > Right-click on it > New > layout resource file and name your layout as course_rv_item and add the below code to it. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="4dp">
     
      <!--on below line we are creating a
        linear layout for grid view item-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--on below line we are creating
             a simple image view-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:padding="5dp"
            android:src="@mipmap/ic_launcher" />
 
        <!--on below line we are creating
            a simple text view-->
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:text="@string/app_name"
            android:textAlignment="textStart"
            android:textColor="@color/black"
            android:textStyle="bold"
            tools:ignore="RtlCompat" />
 
    </LinearLayout>
 
</androidx.cardview.widget.CardView>


Step 5: Creating an adapter class for setting data to items of our RecyclerView

Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class and name it as CourseRVAdapter and add the below code to it. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
 
// on below line we are creating
// a course rv adapter class.
class CourseRVAdapter(
    // on below line we are passing variables
    // as course list and context
    private var courseList: ArrayList<CourseRVModal>,
) : RecyclerView.Adapter<CourseRVAdapter.CourseViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CourseRVAdapter.CourseViewHolder {
        // this method is use to inflate the layout file
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
            R.layout.course_rv_item,
            parent, false
        )
        // at last we are returning our view holder
        // class with our item View File.
        return CourseViewHolder(itemView)
    }
     
    override fun onBindViewHolder(holder: CourseRVAdapter.CourseViewHolder, position: Int) {
        // on below line we are setting data to our text view and our image view.
        holder.courseNameTV.text = courseList.get(position).courseName
        holder.courseIV.setImageResource(courseList.get(position).courseImg)
    }
 
    override fun getItemCount(): Int {
        // on below line we are returning
        // our size of our list
        return courseList.size
    }
 
    class CourseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing our course name text view and our image view.
        val courseNameTV: TextView = itemView.findViewById(R.id.idTVCourse)
        val courseIV: ImageView = itemView.findViewById(R.id.idIVCourse)
    }
}


Step 6: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating a card view-->
    <androidx.cardview.widget.CardView
        android:id="@+id/idCVAddLanguage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="4dp"
        app:cardCornerRadius="4dp"
        app:cardElevation="3dp">
 
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
 
            <!--on below line we are creating edit text
                 for adding a language name-->
            <EditText
                android:id="@+id/idEdtLanguage"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Enter Language" />
 
            <!--on below line we are creating a linear layout for
                adding different images within it-->
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/idEdtLanguage"
                android:orientation="horizontal"
                android:weightSum="5">
 
                <ImageView
                    android:id="@+id/idIVAndroid"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:padding="3dp"
                    android:src="@drawable/android" />
 
                <ImageView
                    android:id="@+id/idIVC"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:padding="3dp"
                    android:src="@drawable/c" />
 
                <ImageView
                    android:id="@+id/idIVJava"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:padding="3dp"
                    android:src="@drawable/java" />
 
                <ImageView
                    android:id="@+id/idIVJs"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:padding="3dp"
                    android:src="@drawable/js" />
 
                <ImageView
                    android:id="@+id/idIVPython"
                    android:layout_width="0dp"
                    android:layout_height="40dp"
                    android:layout_margin="4dp"
                    android:layout_weight="1"
                    android:padding="3dp"
                    android:src="@drawable/python" />
 
 
            </LinearLayout>
 
        </RelativeLayout>
    </androidx.cardview.widget.CardView>
 
    <!--on below line we are creating our recycler view-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVLanguages"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/idBtnSaveList"
        android:layout_below="@id/idCVAddLanguage"
        android:layout_margin="4dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
 
    <!--on below line we are creating a button to
         save our list to shared preferences-->
    <Button
        android:id="@+id/idBtnSaveList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp"
        android:layout_marginBottom="10dp"
        android:text="Save List"
        android:textAllCaps="false" />
 
</RelativeLayout>


Step 7: Working with the MainActivity.kt file

Navigate to app > java > your app’s package name > MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.RecyclerView
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.lang.reflect.Type
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating
    // a variable for our button
    lateinit var androidIV: ImageView
    lateinit var cIV: ImageView
    lateinit var javaIV: ImageView
    lateinit var jsIV: ImageView
    lateinit var pythonIV: ImageView
    lateinit var languageRV: RecyclerView
    lateinit var saveBtn: Button
    lateinit var lngEdt: EditText
 
    lateinit var courseList: ArrayList<CourseRVModal>
    lateinit var courseRVAdapter: CourseRVAdapter
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing
        // our views with their ids.
        androidIV = findViewById(R.id.idIVAndroid)
        cIV = findViewById(R.id.idIVC)
        javaIV = findViewById(R.id.idIVJava)
        jsIV = findViewById(R.id.idIVJs)
        pythonIV = findViewById(R.id.idIVPython)
        languageRV = findViewById(R.id.idRVLanguages)
        saveBtn = findViewById(R.id.idBtnSaveList)
        lngEdt = findViewById(R.id.idEdtLanguage)
 
        // method to load arraylist from shared prefs
        // initializing our shared prefs with name as
        // shared preferences.
        val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
 
        // creating a variable for gson.
        val gson = Gson()
 
        // below line is to get to string present from our
        // shared prefs if not present setting it as null.
        val json = sharedPreferences.getString("courses", null)
 
        // below line is to get the type of our array list.
        val type: Type = object : TypeToken<ArrayList<CourseRVModal?>?>() {}.type
 
        // in below line we are getting data from gson
        // and saving it to our array list
        courseList = gson.fromJson<Any>(json, type) as ArrayList<CourseRVModal>
 
        // checking below if the array list is empty or not
        if (courseList == null) {
            // if the array list is empty
            // creating a new array list.
            courseList = ArrayList()
        }
 
        // on below line we are initializing our adapter
        // and setting it to recycler view.
        courseRVAdapter = CourseRVAdapter(courseList)
        languageRV.adapter = courseRVAdapter
 
        androidIV.setOnClickListener {
            if (lngEdt.text.toString().isNotEmpty()) {
                // on below line adding item to recycler view.
                addItemToList(lngEdt.text.toString(), R.drawable.android)
            }
        }
 
        cIV.setOnClickListener {
            if (lngEdt.text.toString().isNotEmpty()) {
                // on below line adding item to recycler view.
                addItemToList(lngEdt.text.toString(), R.drawable.c)
            }
        }
 
        javaIV.setOnClickListener {
            if (lngEdt.text.toString().isNotEmpty()) {
                // on below line adding item to recycler view.
                addItemToList(lngEdt.text.toString(), R.drawable.java)
            }
        }
 
        jsIV.setOnClickListener {
            if (lngEdt.text.toString().isNotEmpty()) {
                // on below line adding item to recycler view.
                addItemToList(lngEdt.text.toString(), R.drawable.js)
            }
        }
 
        pythonIV.setOnClickListener {
            if (lngEdt.text.toString().isNotEmpty()) {
                // on below line adding item to recycler view.
                addItemToList(lngEdt.text.toString(), R.drawable.python)
            }
        }
 
        // on below line we are adding
        // click listener for our save button
        saveBtn.setOnClickListener {
  
            // method for saving the data in array list.
            // creating a variable for storing data in
            // shared preferences.
            val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)         
 
            // creating a variable for editor to
            // store data in shared preferences.
            val editor = sharedPreferences.edit()       
 
            // creating a new variable for gson.
            val gson = Gson()           
 
            // getting data from gson and storing it in a string.
            val json: String = gson.toJson(courseList)
            
            // below line is to save data in shared
            // prefs in the form of string.
            editor.putString("courses", json)
 
            // below line is to apply changes
            // and save data in shared prefs.
            editor.apply()
 
            // after saving data we are displaying a toast message.
            Toast.makeText(this, "Saved Array List to Shared preferences. ", Toast.LENGTH_SHORT)
                .show()
 
        }
    }
 
    private fun addItemToList(lngName: String, lngImg: Int) {
        // in this method we are adding item to list and
        // notifying adapter that data has changed
        courseList.add(CourseRVModal(lngName, lngImg))
        courseRVAdapter.notifyDataSetChanged()
    }
}


Now run your application to see the output of it. 

Output:

To save an ArrayList to SharedPreferences in Kotlin on Android, you can follow these steps:

Convert the ArrayList to a Set of strings using the toSet() function.

  1. Get an instance of the SharedPreferences using the getSharedPreferences() method.
  2. Get an instance of the SharedPreferences.Editor using the edit() method.
  3. Put the Set of strings into the SharedPreferences.Editor using the putStringSet() method.
  4. Call the apply() method on the SharedPreferences.Editor instance to save the changes.

Here’s some sample code that demonstrates how to save an ArrayList of strings to SharedPreferences in Kotlin:

Kotlin




import android.content.Context
import android.content.SharedPreferences
 
class MainActivity : AppCompatActivity() {
     
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // Create an ArrayList of strings
        val myArrayList = arrayListOf("item1", "item2", "item3")
         
        // Save the ArrayList to SharedPreferences
        saveArrayListToSharedPreferences("myArrayList", myArrayList)
         
        // Retrieve the saved ArrayList from SharedPreferences
        val retrievedArrayList = getArrayListFromSharedPreferences("myArrayList")
         
        // Print the retrieved ArrayList to the console
        Log.d("TAG", "Retrieved ArrayList: $retrievedArrayList")
    }
     
    private fun saveArrayListToSharedPreferences(key: String, arrayList: ArrayList<String>) {
        // Convert the ArrayList to a Set of strings
        val mySet = arrayList.toSet()
         
        // Get an instance of the SharedPreferences
        val sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
         
        // Get an instance of the SharedPreferences.Editor
        val editor = sharedPreferences.edit()
         
        // Put the Set of strings into the SharedPreferences.Editor
        editor.putStringSet(key, mySet)
         
        // Apply the changes to the SharedPreferences
        editor.apply()
    }
     
    private fun getArrayListFromSharedPreferences(key: String): ArrayList<String> {
        // Get an instance of the SharedPreferences
        val sharedPreferences = getSharedPreferences("my_prefs", Context.MODE_PRIVATE)
         
        // Retrieve the Set of strings from SharedPreferences
        val mySet = sharedPreferences.getStringSet(key, emptySet())
         
        // Convert the Set of strings back to an ArrayList
        val myArrayList = arrayListOf<String>()
        myArrayList.addAll(mySet!!)
         
        return myArrayList
    }
}


Output:

Retrieved ArrayList: [item1, item2, item3]
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads