Kotlin SharedPreferences - Save ListView items and load them

前端 未结 3 1922
慢半拍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:11

    SOLUTION

    After full days of research, I went to solution:

    In MainActivity.kt create you ArrayList variable as global:

        class MainActivity : AppCompatActivity() {
    
        private var values = ArrayList()
    
        ... //the rest of your code
    }
    

    Then add those 2 functions:

     private fun saveData() {
        val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        val gson = Gson()
        val json = gson.toJson(values)
        editor.putString("task list", json)
        editor.apply()
    }
    
    private fun loadData() {
        val sharedPreferences = getSharedPreferences("shared preferences", MODE_PRIVATE)
        val gson = Gson()
        val json = sharedPreferences.getString("task list", "")
        val type = object: TypeToken>() {
        }.type
    
       if(json == null)
           values = ArrayList()
       else
          values = gson.fromJson(json, type)
    }
    

    where values is your ArrayList

    To save data:

    done_fab.setOnClickListener {
    
            values.add("put your string here")
            adapter.notifyDataSetChanged() //your array adapter
            saveData()
        }
    

    And to load data, simply call the function in your MainActivity:

        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            loadData()
    
             val adapter = ArrayAdapter(this, R.layout.listview_text_color, values) //your custom arrayAdapter for the listView
    
            ... //the rest of your code
    }
    

    All this because SharedPreferences doesn't supports ArrayList storing, so passing them with a JSON is the best option

提交回复
热议问题