Kotlin store list in RecyclerView by SharedPrefernce

Issue

I m trying to store list which i get from spinner from modal class store in RecyclerView shared preference but i m only getting last item selected instead of multiple selection from spinner

  spinner.onItemSelectedListener = object :
            AdapterView.OnItemSelectedListener{
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {

                val data_  = ArrayList<Model>()
                data_.add(Model(department[p2]))
                val gson: Gson =Gson()
                val json:String = gson.toJson(data_)
                val editor:SharedPreferences.Editor = sharedPreferences.edit()
                editor.putString("list",json)
                editor.apply()
            }

Fill adapter

    val gson: Gson =Gson()
    val json: String? = sharedPreferences.getString("list",null)
    val type= object :TypeToken<ArrayList<Model>>(){
    }.type
    data_ = gson.fromJson(json,type)
    if (data_ == null){
        Toast.makeText(this,"null",Toast.LENGTH_SHORT).show()
    }
    else{
        val rec = binding.recyclerView
        rec.layoutManager = LinearLayoutManager(this)
        val adapter = AddEditTextAdapter(data_)
        rec.adapter = adapter
    }

Solution

The problem is that you are always re-initializing the data_ array in the onItemSelectedListener function everytime.
You could declare separate functions to retrieve and set your SharedPreference:

fun getData(): ArrayList<Model>? {
    val json = sharedPreferences.getString("list", "")
    if (json == "") return null
    val type = object : TypeToken<ArrayList<Model>>(){ }.type
    return Gson().fromJson(json, type)
}

fun setData(data: ArrayList<Model>) {
    val json = Gson().toJson(data)
    sharedPreferences.edit()
        .putString("list", json)
        .apply()
}

And use these functions in your code:

spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
    override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
        val data_ = getData() ?: arrayListOf<Model>()
        // Add data to existing values
        data_.add(Model(department[p2]))
        // Update prefs
        setData(data_)
    }
}

New adapter’s code:

val data_ = getData()
if (data_ == null){
    Toast.makeText(this,"null",Toast.LENGTH_SHORT).show()
}
else {
    val rec = binding.recyclerView
    rec.layoutManager = LinearLayoutManager(this)
    val adapter = AddEditTextAdapter(data_)
    rec.adapter = adapter
}

Answered By – lpizzinidev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published