In my code, I use two methods to pass data to a new fragment. Either I pass data through Bundle or sometimes write setters to pass data.
Both works fine, no issues faced yet.
But now, I am optimising my code keeping in mind savedInstances, orientation changes or any other possible way where data can be lost.
So, the exact doubt in my mind is whether the data sent via bundle remains intact by default on orientation change / fragment restored from background. Or we have to use savedInstance in the case of bundles as well. As per my knowledge, data set through setters get lost.
Whenever the OS needs to re-layout your view, it will call onCreate
and onCreateView
with a saved instance state. If you are using a constructor and passing variables, you will lose whatever you set. If you are using a bundle and are using it to directly change some of your variables, you will likely overwrite them with the original values in your bundle. To get around this, just check if the bundle is null before performing the mutation.
TLDR: Passed in bundle will remain intact through orientation changes and instance restores. You can add extra data to the saved instance state bundle in onSaveInstanceState
.
As you said, OS can recreates your fragment (across a configuration change or when OS need to reclaims memory), data will be lost. And you consider between using saveInstanceState and passing Bundle as fragment's argument.
Using bundle as fragment's argument is less complicated, easier to maintain. However, argument must be set before fragment is attached to activity, that means you can not change argument later. So, if your passing data is fix, argument bundle is the best choice
If your passing data can be changed while running, setter + saveInstanceState is the only way to go
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With