I'm trying to get my edittext1.text while clicking on the getName button after screen flipped but it doesn't work. How it should work
- adding some text to the et1
- click setName then tv1 appears (tv1.text = et1.text, var "name" = tv1.text)
- flip the screen
- click getName (at the et1 have to be value "name" that we put to the SaveInstanceState before)
I'm a noobie, hope You can help me! Thanks in advance. <3
class MainActivity : AppCompatActivity() {
private var name: String? = null
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater).also { setContentView(it.root) }
binding.setButton.setOnClickListener { setName() }
binding.getButton.setOnClickListener { getName() }
}
fun getName(){
binding.et1.setText(name)
}
fun setName(){
binding.tv1.text = binding.et1.text
name = binding.tv1.text.toString()
}
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
name = savedInstanceState.getString(KEY_NAME, "unknown")
}
override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {
super.onSaveInstanceState(outState, outPersistentState)
outState.putString(KEY_NAME, name)
}
companion object{
private val KEY_NAME = "NAME"
}
CodePudding user response:
You need to use another overload of the onSaveInstanceState
function: the one with with just one parameter: fun onSaveInstanceState(outState: Bundle)
Your code should look the following:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString(KEY_NAME, name)
}