Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Using Setters Vs Passing Bundle in Fragments

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.

like image 452
sanju Avatar asked Jun 25 '16 09:06

sanju


Video Answer


2 Answers

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.

like image 56
Marcus Hooper Avatar answered Nov 03 '22 00:11

Marcus Hooper


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

like image 43
meaholik Avatar answered Nov 03 '22 01:11

meaholik