I've made a custom DialogPreference
which uses two NumberPicker
widgets on it to allow a user to select an hour of the day as well as another custom DialogPreference
which allows a user to select a time of day using a TimePicker
widget.
As long as the dialog is not open and I rotate the screen, everything works as desired. However, if the dialog is open and the screen is rotated then the entire app crashes. I've placed break points in the onSaveInstanceState
and onRestoreInstanceState
methods and have verified that everything that is needed to restore the DialogPreference
is in order, the onDialogClosed
method is even hit everytime along with all other custom code that I have in my custom DialogPreference
.
I'm building with the following:
- Minimum SDK: 16
- Target SDK: 20
- Compile SDK: 20
- Build Tools: 20.0.0
I'm running Android 4.4.3 (KitKat) on a Verizon Galaxy Nexus when this is happening.
Here is the stacktrace given:
java.lang.IndexOutOfBoundsException: setSpan (4 ... 4) ends beyond length 0
at android.text.SpannableStringBuilder.checkRange(SpannableStringBuilder.java:1016)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:592)
at android.text.SpannableStringBuilder.setSpan(SpannableStringBuilder.java:588)
at android.text.Selection.setSelection(Selection.java:76)
at android.widget.EditText.setSelection(EditText.java:87)
at android.widget.NumberPicker$SetSelectionCommand.run(NumberPicker.java:2123)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Method.java)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(NativeStart.java)
I found the solution to this problem here: https://code.google.com/p/android/issues/detail?id=22754#c5, which says the following:
This got rid of the error. However, the dialog doesn't stay open. But this seems to be the default functionality for all non-custom preferences, so I'm happy with it.
Here are the docs for the two methods used above:
setSaveFromParentEnabled
setSaveEnabled
And here are gists that I've posted of my final working custom Preferences: