I have a small activity with an EditText and an imageview and a button. When you press the button it launches camera for result, and when it returns it changes the imageview to the picture you've just taken.
But when the orientation changes, the imageview resets back to the default one on the layout.
What I tried doing was setting a boolean called custom, and when you take a picture it sets it to true. I overrid onConfigurationChanged() and if custom is set to true I restore the image.
My problem now is the EditText becomes erased -- How can I restore the EditText after configuration change? My first attempt was storing it's content into a String onPause() and then restoring it, but it always comes up blank.
Usually when UI view does not keep its state, first thing to check is that this UI view has id assigned. Without this id views cannot restore their state.
<EditText android:id="#+id/text" ... />
If this doesn't help, you need to save and restore state yourself. Take a look at Handling Runtime Changes. It pretty much explains what you should do:
To properly handle a restart, it is important that your Activity restores its previous state through the normal Activity lifecycle, in which Android calls onSaveInstanceState() before it destroys your Activity so that you can save data about the application state. You can then restore the state during onCreate() or onRestoreInstanceState(). To test that your application restarts itself with the application state intact, you should invoke configuration changes (such as changing the screen orientation) while performing various tasks in your application.
You should override onSaveInstanceState() and save your Acitivity state when its called:
#Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putString("textKey", mEditText.getText().toString());
}
And then restore state in onCreate() or onRestoreInstanceState():
public void onCreate(Bundle savedInstanceState)
{
if(savedInstanceState != null)
{
mEditText.setText(savedInstanceState.getString("textKey"));
}
}
If this is still not sufficient, you can override onRetainNonConfigurationInstance() and return any custom Object that will be passed to new activity object, when its recreated. More details about how to use it can be found in Handling Runtime Changes. But this function is deprecated in Android 3.0+ (specifically for FragmentActivity where its final). So this cannot be used together with Fragments (which is fine, they have their mechanism to retain objects accross configuration changes).
And final one - never use android:configChanges. You must have very good reasons to use it, and usually these are performance reasons. It wasn't meant to be abused the way it is now: just to prevent UI state reset. If this attribute is used, then yes, Activity UI will not be re-set on config change, but Activity state still will be reset when destroyed and re-created later.
The documentation explains this option pretty well:
Note: Handling the configuration change yourself can make it much more
difficult to use alternative resources, because the system does not
automatically apply them for you. This technique should be considered
a last resort and is not recommended for most applications
You can force your activity not to reload after orientation changed by adding android:configChanges="orientation" to your activity line in manifest.
Related
I came across two ways to prevent the activity from redrawing whenever the screen is rotated.
One is saveInstanceState + restoreInstanceState combo, which I still haven't been able to successfully implement.
The other one was to declare configChanges attribute in the activity tag of the manifest file to orientation
I'm curious as to what is the difference between the two.
In one scenarios you are handling all the
Related configuration changes without activity getting restarted.. while in second you are just taking care of your desired user state variables ie saving and restoring them.
When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with android:configChanges attribute will prevent the activity from being restarted. Instead, the activity remains running and its onConfigurationChanged() method is called, handling configuration changes your self is a complex task and should be avoided..
It is not recommended to handle configuration changes yourself due to the hidden complexity of handling the configuration changes.
However, if you are unable to preserve your UI state using the preferred options (onSaveInstanceState(), ViewModels, and persistent storage) you can instead prevent the system from restarting your activity during certain configuration changes. Your app will receive a callback when the configurations do change so that you can manually update your activity as necessary.
[Reference link]
I'm curious as to what is the difference between the two.
The difference between saveInstanceState + restoreInstanceState combo and configChanges is that configcahnges attribute in the manifest will prevent the activity from being destroyed when the specified change(s) occurred. In Android when you rotate the device or when the screen size change, the activity will be destroyed and recreated.
saveInstanceState + restoreInstanceState combo will not prevent the activity from being destroyed and recreated. In fact, they will just help you pass the data from the destroyed activity to the one which will be recreated.
Inside saveInstanceState you save all the data you want into a bundle object. Then, inside restoreInstanceState you get these data and use them in the recreated activity.
For example, if I use this attribute inside an activity tag in the Manifest file:
android:configChanges="orientation|screenSize"
Now, this activity won't be destroyed when the screen rotates and all the data of the activity will stay as is because it will not be destroyed.
saveInstanceState + restoreInstanceState combo, which I still haven't been able to successfully implement.
Here is how saveInstanceState + restoreInstanceState combo work:
Let's say I have a global variable called userScore holding the user scores in a game. Now, I did not use the attribute android:configChanges="orientation|screenSize" in my activity tag, so it will be destroyed if the user rotates the screen and the scores will be lost. To prevent them from being lost I will use saveInstanceState + restoreInstanceState like so:
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putInt("Score", userScore); // saving the userScore value
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
userScore = savedInstanceState.getInt("Score"); // restoring the userScore value
super.onRestoreInstanceState(savedInstanceState);
}
Both of the solutions have to do with data persistence during the lifecycle of your activity. Please read here more regarding LifeCycle
The basic difference is that when your app dies, with the save/restoreInstance combo (there are many different ways to do this) is that you can save the state of your app and when your activity is recreated after it was previously destroyed, you can recover your saved instance state from the Bundle that the system passes to your activity.
configChanges
Lists configuration changes that the activity will handle itself. When a configuration change occurs at runtime, the activity is shut down and restarted by default, but declaring a configuration with this attribute will prevent the activity from being restarted. source
Generally speaking i would suggest to NOT lock orientation in your app with the configChanges attr to prevent your activity from dying. Just save its state and restore through LifeCycle
I have the following security requirement for my app :
Verify that the app removes sensitive data from views when backgrounded.
My question is, Does Android remove data from views when backgrounded ?
What i know as per android documentation is that :
By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText widget).
One solution is that i can clear all views then use below approach to save state
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
} else {
// Probably initialize members with default values for a new instance
}
// ...
}
But i have no idea of whether Android os clears data in views.Any help will be appreciated.
Thanks
Android does not automatically recycler your view as soon as your application moves to background.
The system kills processes when it needs to free up RAM; the likelihood of the system killing a given process depends on the state of the process at the time.
It just recycle views if it decided to kill them or if it's in need for memory. Or upon a configuration change.
A user expects an activity’s UI state to remain the same throughout a configuration change, such as rotation or switching into multi-window mode. However, by default the system destroys the activity when such a configuration change occurs, wiping away any UI state stored in the activity instance.
Overall I think you had the right approach.
And just use onStop() (and not onPause() because of some Dialogs and other intercations that removes focus from your Activity) to clear your views if you want to.
Take a look at the android activity lifecycle https://developer.android.com/guide/components/activities/activity-lifecycle
One way to make sure all your data is cleared is to override the onPause function and clear your data manually. onPause is called when your application moves to the background.
No, it does not remove data because, according to the lifecycle of Android, when you do background the views, onPause() and onResume() is called and your views and its instances are in onCreate() method.
So, by launching the views from background, it does not remove your data of views.
What is the significance of:
super.onCreate(null);
instead of
super.onCreate(savedInstanceState);
With this change, I am able to avoid many problems that otherwise plague my Activitys each time a configuration change occurs (rotation, locale shift, permission toggle). It seems that with this change, the Activity is started afresh whenever a configuration change triggers it to restart. And I don't seem to lose any data or process state by doing this: all my Activitys are restored exactly to their former state.
My question is, can I do this with impunity henceforth, or am losing something in the bargain? I don't really understand why this works, whether it is safe or not, and what unintended effects it may have on my app.
I chanced upon this trick here.
Related Questions:
Calling super.onCreate() with null parameter?
Will 'Bundle savedInstanceState' be alive after Application is being killed?
Activity state instance - insights?
Activity's instance state: what is automatically stored and restored
onCreate() call first when activity is about to create, Also Android System manage activity lifecycle and can kill the activity with saving its instanceState, in case if acitvity out of focus for user for long time and system is on low memory situation.
An activity has essentially four states
super.onCreate(null) : Would always create activity as it is creating fisrt time , even Android system provide its savedInstanceState, and does't matter what orientation configurations are.
super.onCreate(savedInstanceState) : Activity can use 'savedInstanceState' to reset its state or component where it was last.
To achive this, acitivty's instance state need to be persist before activity lost user attention( that could be onStop or onDestroy)
savedInstaceState can also be important to handle if activity configuration got changed, Please check acitvity life cycle behavior on Configuration change
am losing something in the bargain?
Only if you are working with Fragments. see Calling super.onCreate() with null parameter?
Yes, onCreate(...) is necessary to start an Activity, but passing Bundle as an argument is required when you are working with fragments.
What did you infer from that?
The argument savedInstanceState is anyway null by default. So you aren't really losing anything in a bargain.
But wait, we usually use Bundles to maintain orientation change, right?
the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:
<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="#string/app_name">
Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.
the following onConfigurationChanged() implementation checks the current device orientation:
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
But Remember: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().
As far as I know a lot of data is saved in the bundle savedInstanceState.
E.g. all the views' states in your current layout, such as the current content of any EditText or CheckBox.
You could also look up some official sources to check whether you need to keep some data.
Here's a nice article about it
Basically it says that all View class implements the methods onRestoreInstanceState and onSaveInstanceState, which are saving and restoring any temporary states they were in before the state change.
The savedInstanceState is a reference to a Bundle object that is passed into the onCreate method of every Android Activity. Activities have the ability, under special circumstances, to restore themselves to a previous state using the data stored in this bundle.
It is very important to use savedInstantState to get values from Intent which is saved in the bundle.
All your data stored in class variables or local variables is lost whenever you change rotation of device, but in your activity it looks like you have not stored any data as long as user enters any data, but instead you are perhaps reading data on click of a button or something like that, your activity will behave and work normally, and all user inputs like text inside EditText will be restored by Android itself, because it identifies "IDs" (android:id="#+id/anyID") allotted to each view and can restore by itself all the values inserted by user.
I hope this this helps you...
Happy coding :)
How does android restart an activity or fragment when rotating the app?
I'm interested in the methods or flags it uses in the process. Thx
When any configuration changes, such as device orientation takes place the activity will be destroyed and recreated that is unless you've modified this process inside the manifest file. As #Lazai mentioned, if you change activity configuration changes functionality, you must handle manually loading any new resources required for the new orientation, that includes, styles, themes, drawables, and layouts inside of the callback Activity.onConfigurationChanged(Configuration newConfig).
Note: if you don't indicate inside of the manifest file that you'd like to manually handle configuration changes, you will never received a call to Activity.onConfigurationChanged(Configuration newConfig).
Android exports recommend not handling the configuration changes yourself and letting the OS handle itself. So how to know when orientation changes are taking place when you don't get calls to onConfigurationChanged(Configuration newConfig)? Well if you're are targeting above API Level 11, their is a handy method on the Activity class that indicates if activity is experiencing the a configuration change, called Activity.isChangingConfigurations(). This method will always return false until the activity is preparing to be destroyed. It will have a valid value prior to the call Activity.onPause(), that you can check and determine if your device is rotating and your app should perform some special optimizations or state saving procedures.
I personally recommend letting the system handling the config changes and checking if the orientation is changing, because in a large app or complex activity it can get very tedious reloading the necessary resources and assets just to prevent an activity from discarding a simple object or during rotations.
When your orientation changes all the fragments and activities are destroyed , and the views are re-created again ; unless you change the config settings :
<activity android:name=".SampleActivity"
android:configChanges="orientation|keyboardHidden">
So basically the key here is onStop() and onDestroy() , you should save the states of your tasks when rotating in the onStop() method (or even onPause()) to restart them again when the views are loaded (onResume()).
See more here link
When Activities and Fragments rotate, they are destroyed (with onDestroy()) then they go through the same lifecycle as they were created.
in your fragment override onconfigurationchanged method
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
// reload your views here
}
When orientation of screen changes, I have read many a times that in order to save data of edit text and text view or any of the radio button I have to use onSaveInstanceState() method.
But when I'm changing the screen orientation my data of edit text, text view and radio button are not getting erased.
So what is the main purpose of using onSaveInstanceState() method. Why do we have to use it if my data are preserved safely ?
Some Views/properties may be handled by default. You could go rooting through the docs to find out exactly which ones and how they are taken care of but...
I would recommend that you take manual control of these save/loads though to ensure that things are handled as you want them to be to avoid edge case bugs and also so you can then persist certain settings/properties/states if need be.
It really depends on the complexity and contents of your Activity/Fragment/Layout/View/Preference etc etc and if you even really need to remember the state things were a few moments ago.
onSaveInstanceState(Bundle outState)
This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state.
Do not confuse this method with activity lifecycle callbacks such as onPause, which is always called when an activity is being placed in the background or on its way to destruction, or onStop which is called before destruction. One example of when onPause and onStop is called and not this method is when a user navigates back from activity B to activity A: there is no need to call onSaveInstanceState on B because that particular instance will never be restored, so the system avoids calling it. An example when onPause is called and not onSaveInstanceState is when activity B is launched in front of activity A: the system may avoid calling onSaveInstanceState on activity A if it isn't killed during the lifetime of B since the state of the user interface of A will stay intact.
onRestoreInstanceState(Bundle savedInstanceState)
This method is called after onStart() when the activity is being re-initialized from a previously saved state.
Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).
On the default handling of your views with this pair of methods:
The default implementation takes care of most of the UI per-instance state for you by calling View.onSaveInstanceState() on each view in the hierarchy that has an id, and by saving the id of the currently focused view (all of which is restored by the default implementation of onRestoreInstanceState). If you override this method to save additional information not captured by each individual view, you will likely want to call through to the default implementation, otherwise be prepared to save all of the state of each view yourself.