I've made a search screen that has one tab for keywords, filters, and a search button, and three optional tabs for the different types of results (each containing a ListView
with an ArrayAdapter
). When starting the activity, the developer can optionally pass in the results as an extra Parcelable[]
if the search has already been performed. In the onCreate()
method I'm creating each of the three tabs for the Parcelable[]
passed through.
When I call a search from the button on the filter tab, I clear the tabs and recreate them with the new results, which works perfectly. The problem is that when you rotate the device, it appears that Android's automatic orientation switching support recreates the entire activity, calling onCreate()
. This means that my search results are reset to the Parcelable[]
passed through when starting the activity.
The only solution I've had so far is to call finish()
then startActivity()
to essentially restart the activity with the new results. I'm sure there must be a much simpler solution and that I've done something extremely noobish.
Is there a better way to do this?
Notice that Android does not call onCreate and onDestroy because we retained the Fragment; nor does it call the constructor, because the same Fragment instance will be used after the orientation change.
Prevent Activity to recreated Another most common solution to dealing with orientation changes by setting the android:configChanges flag on your Activity in AndroidManifest. xml. Using this attribute your Activities won't be recreated and all your views and data will still be there after orientation change.
We do not call the onCreate() method ; it is called automatically when you start an Activity from intent.
OnCreate is only called once.
Of cource there is. Just add configChanges attribute to your AndroidManifest.xml, like that:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden" />
Activity restart on rotation Android How do I disable orientation change on Android? http://developer.android.com/guide/topics/manifest/activity-element.html#config
What you describe is the default behavior. You have to detect and handle these events yourself by adding:
android:configChanges
to your manifest and then the changes that you want to handle. So for orientation, you would use:
android:configChanges="orientation"
and for the keyboard being opened or closed you would use:
android:configChanges="keyboardHidden"
If you want to handle both you can just separate them with the pipe command like:
android:configChanges="keyboardHidden|orientation"
This will trigger the onConfigurationChanged
method in whatever Activity
you call.
If you override the method you can pass in the new values.
Hope this helps.
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