Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DialogFragment and configuration changes

Tags:

android

I'm having some trouble understanding how to make a simple DialogFragment to edit a (complex) object, say a Person, with first and last name, and a list of e-mail addresses each consisting of an enum (Work, Home, etc) and the address.

First of all, how do I properly pass the Person object to a DialogFragment? My current solution has a setPerson(Person person) method, that's called after my DialogFragment is created, but before dialog.show(). This works ok, until a configuration change happens (user rotates the screen). The DialogFragment gets recreated and the reference to my Person object is null. I know I can save the instance using onSaveInstanceState, but the object is complex and expensive, and persisting a large object this way seems wasteful.

I've also tried disabling configuration change in the activity that uses my dialog, and that fixes the problem, but I want the dialog to be reuseable and requiring all the activities that use it to disable configuration changes seems wrong.

Third option would be to save the reference to Person in a static variable, but again, I want the dialog to be reuseable and able to support multiple instances.

How do other people handle their expensive and complex objects in reuseable dialogs?

like image 585
kalithlev Avatar asked Nov 10 '11 19:11

kalithlev


1 Answers

Well, there are several solutions, none of which are fantastic or failsafe if you are completely unable to serialize the object you're editing.

I don't recommend ever using android:configChanges="orientation" unless it's absolutely, 100% unavoidable. There are other configuration changes, and your app will still break with the others if you resort to using that solution.

But a simple solution that will work in the vast majority of cases is to call setRetainInstance(true) on the DialogFragment. This will prevent your Fragment from being destroyed and re-created on a configuration change. There is an edge-case where this might not work, though. There are other reasons besides configuration changes where the OS will attempt to put an activity or app 'on ice', for example to save memory. In this case, your object will be lost.

like image 180
Avi Cherry Avatar answered Sep 19 '22 03:09

Avi Cherry