Home > Software engineering >  onSaveInstance outState saving all state with last putString
onSaveInstance outState saving all state with last putString

Time:08-10

I was working with Activity I am using onSaveInstanceState lifecycle

when I tried to updating

companion object {
    const val EXTRA_INDEX = "extra_index"
    private const val STATE_COMMENT_NAME = ""
    private const val STATE_COMMENT_COMMENT = ""
}

on GalleryDetail class with

outState.putString(STATE_COMMENT_NAME, tvCommentName.text.toString())
outState.putString(STATE_COMMENT_COMMENT, tvCommentComment.text.toString())

within onSaveInstanceState lifecycle, STATE_COMMENT_NAME was filled by tvCommentComment.text.toString().trim()

even when I changed the order, for example

outState.putString(STATE_COMMENT_COMMENT, tvCommentName.text.toString().trim())
outState.putString(STATE_COMMENT_NAME, tvCommentComment.text.toString().trim())

vice versa, STATE_COMMENT_COMMENT will be filled by tvCommentName.text.toString().trim() so, the point is, everything on top of the last putString, it'll be filled by last value of putString

I have do Log the problem, and it show me that the problem is on onSaveInstanceState and not on the onCreate nor mistype variable to show on UI

so, this is the Log of my code

2022-08-09 08:14:57.384 27561-27561/com.dicoding.kelassekolah D/GalleryDetail Bundle: onSaveInstanceState Nice photos!
2022-08-09 08:14:57.384 27561-27561/com.dicoding.kelassekolah D/GalleryDetail Bundle: onSaveInstanceState Nice photos!
2022-08-09 08:14:57.519 27561-27561/com.dicoding.kelassekolah D/GalleryDetail Bundle: savedInstanceState Nice photos!
2022-08-09 08:14:57.519 27561-27561/com.dicoding.kelassekolah D/GalleryDetail Bundle: savedInstanceState Nice photos!

onSaveInstanceState Gist: https://gist.github.com/amirudev/421d76f671250e015462fa973bb984be

onCreate if savedInstanceState not null Gist: https://gist.github.com/amirudev/17d1d74f829de16bf63f672316e3beb6

CodePudding user response:

You should put these STATE_COMMENT_NAME and STATE_COMMENT_COMMENT values not identical to each other:

companion object {
    const val EXTRA_INDEX = "extra_index"
    private const val STATE_COMMENT_NAME = "stateCommentName"
    private const val STATE_COMMENT_COMMENT = "stateCommentComment"
}

If they are the same (ex. ""), they are identical.

  • Related