Fix crash on configuration changes in DatePickerFragment #1431
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #1201. When you tab in and out of other apps or rotate your screen, the
DatePickerFragment
won't cause crashes anymore.Let me explain how the fix works:
Fragment
s must have a public, no arguments constructor. Any data you want to pass to them must be put in aBundle
for Android to be able to persist it across configuration changes (like the situations above).FragmentManager.setFragmentResultListener()
on the activity/fragment that receives the callback andFragmentManager.setFragmentResult()
on the one that sends the callback. The callback data must fit in aBundle
.In the original code, the date picker directly sets the target text field. Here, the code for setting the text field is put in a callback received by the host activity, and the date picker fragment's only responsibility is receiving input data (the
Date
objects) and sending output data (the pickedDate
). To know which text field to set, I pass in an "identifier" (which conveniently is theLoyaltyCardField
enum that's already used in the "display date picker" method, so I don't have to create a new enum or something.)