K
K
Koshkasobaka2021-04-23 10:32:23
Android
Koshkasobaka, 2021-04-23 10:32:23

How to save ListView state when changing screen orientation?

I'm trying to pass list through onSaveInstanceState(), but for some reason it doesn't work

class MainActivity : AppCompatActivity(), EditFragment.onSomeEventListener { 
 lateinit var mainBindingClass: ActivityMainBinding 
 private var list = ArrayList<String>() 
 private val detailFragment = DetailFragment() 
 private val editFragment = EditFragment() 
 lateinit var adapter: ArrayAdapter<String> 
 
 override fun onCreate(savedInstanceState: Bundle?) { 
 super.onCreate(savedInstanceState) 
 mainBindingClass = ActivityMainBinding.inflate(layoutInflater) 
 setContentView(mainBindingClass.root) 
 init() 
 initListeners() 
 } 
 
 override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) { 
 outState?.run { 
 putStringArrayList("sand", list) 
 } 
 super.onSaveInstanceState(outState, outPersistentState) 
 } 
 
 override fun onRestoreInstanceState(savedInstanceState: Bundle?) { 
 super.onRestoreInstanceState(savedInstanceState) 
 list = savedInstanceState?.getStringArrayList("sand") as ArrayList<String> 
 } 
 
 private fun init() { 
 adapter = ArrayAdapter(this, R.layout.my_list_item, list) 
 mainBindingClass.lvListOfNotes.adapter = adapter 
 }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis Zagaevsky, 2021-04-23
@Koshkasobaka

Reading the documentation onRestoreInstanceState

This method is called between onStart() and onPostCreate(Bundle)

That is, this method is called strongly after onCreate, in which your adapter is initialized. The same bundle comes in onCreate, so it's better to just get the data right there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question