I have a ListView with items created by
val values = ArrayList().toMutableList()
val adapter = ArrayAdapter(this, R.layout.listview_text_col
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