Should we use savedInstanceState in fragments if there are getArguments()?

Viewed 1653

In Android fragments we can get initial data in onCreate() from savedInstanceState or getArguments(). I often check them both for null and then assign variables. For instance, in Kotlin:

val bundle = savedInstanceState ?: arguments
bundle?.let {
    startDate = Date(it.getLong(ARG_START_DATE, 0))
    endDate = Date(it.getLong(ARG_END_DATE, startDate.time))
}

So, first I check whether savedInstanceState != null and if so, will get data from there. If it is null, I will check getArguments() != null and if so will get data from there. Otherwise variables will be null, 0 or false.

When we leave a fragment and call onSaveInstanceState() we can write data to a bundle and later can read them in onCreate(). But we can also write data to getArguments() and read them from any place of the fragment. Why should we use savedInstanceState as we can write to getArguments()?

3 Answers

setting and getting argument is really doesn't do anything about savedInstanceState, when you call a Fragment you can set a Bundle to it and when you are in the Fragment you can get what you sent to the Fragment using getArgument. savedInstanceState is normally used when you don't want to loose data when configuration changes, like rotation of the device.

As @SinaMN75 said, when a fragment is created, it can check whether it restores after configuration change or is initialized for the first time. After screen rotation some difficulties can happen, for instance, duplication of menu items, change of the Toolbar title. In this case in onCreate() we should check savedInstanceState != null and read data from there. getArguments() won't give us the information about configuration change.

Of course, we should override onSaveInstanceState() in order to save needed variables.

Related