Home > front end >  Existence of EditText data prior to int activity?
Existence of EditText data prior to int activity?

Time:04-17

There is activity, activity. I enter the text in EditText of A, click the button, move to B, do other activities, and come back to A. At this time, I hope the text remains in A's EditText. What should I do? Attempted startActivityForResult, but onActivityResult() is not invoked. Is this the wrong way?

CodePudding user response:

Since Activity A is destroyed when you move to B, in order to restore the data you had in the EditText you first have to store it somewhere. To do this you can use the onSaveInstanceState() method from Activity which will be called right before the Activity is destroyed.

You can then restore the data by using either onRestoreInstanceState(savedInstanceState: Bundle?) or directly in onCreate(savedInstanceState: Bundle?)

For example:

const val TEXT_KEY = "editText_text"

override fun onSaveInstanceState(outState: Bundle) {
  super.onSaveInstanceState(outState)
  outState.putInt(TEXT_KEY, yourEditText.text)
}

override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
  super.onRestoreInstanceState(savedInstanceState)

  savedInstanceState?.run {
    yourEditText.text = getString(TEXT_KEY)
  }
}

Note: you should only save simple, lightweight data using onSaveInstanceState.

  • Related