Home > Back-end >  Kotlin store list in RecyclerView by SharedPrefernce
Kotlin store list in RecyclerView by SharedPrefernce

Time:06-10

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
    }

CodePudding user response:

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
}
  • Related