Kotlin SharedPreferences - Save ListView items and load them

前端 未结 3 1927
慢半拍i
慢半拍i 2020-12-22 06:36

I have a ListView with items created by

 val values = ArrayList().toMutableList()
 val adapter = ArrayAdapter(this, R.layout.listview_text_col         


        
3条回答
  •  无人及你
    2020-12-22 07:24

    Thank you Arfrmann for posting a working resolution that I could use. I had to modify the code to fit inside a Fragment as well as my values being a MutableList of integers. So, I thought I'd share my scenario so that others could benefit.

    class NeedsmetFragment : Fragment() {
    
        private var incorrectList = mutableListOf()
        val PREFS_FILENAME = "com.app.app.prefs"
    
        private fun saveData() {
            val sharedPreferences = context!!.getSharedPreferences(PREFS_FILENAME, 0)
            val editor = sharedPreferences.edit()
            val gson = Gson()
            val json = gson.toJson(incorrectList)
            editor.putString("incorrectList", json)
            editor.apply()
        }
    
        private fun loadData() {
            val sharedPreferences = context!!.getSharedPreferences(PREFS_FILENAME, 0)
            val gson = Gson()
            val json = sharedPreferences.getString("incorrectList", "")
            val type = object: TypeToken>() {}.type
    
            if(json == null || json == "")
                incorrectList = mutableListOf()
    
            else
                incorrectList = gson.fromJson(json, type)
        }
        //...
        x++
    
        incorrestList.add(x)
        saveData()
    
    
        loadData()
        thisval = incorrectList[x]
    
    
    }
    

提交回复
热议问题