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()
?
The main difference between these two options is their storage location.The arguments are stored in memory but The saveInstanceState is serialized to disk. You should look at this page: https://developer.android.com/topic/libraries/architecture/saving-states