onCreate called whenever I the screen autorotates - android

In my app, I use the onCreate() method to initialize various variables. However, whenever I rotate the device, and the screen auto-rotates, onCreate() is called again, which re-initialize my variables. Is that how it's supposed to work? Where should I put code that I only want to be run once, when I start the app?

The above answers will lock your Activity into a specific orientation, which is generally not proper behavior for an Android app.
What you should be doing is storing your activity's state so when it gets recreated you can repopulate the UI with the stored values.
protected void onSaveInstanceState (Bundle outState) {
super.onSaveInstanceState(outState);
// put your values in the Bundle
outState.putString("TextView1Text", textView1.getText()); // for example;
}
Then in your onCreate() method you can restore the values
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
textView.setText(savedInstanceState.getString("TextView1Text"));
}
}
This will also work when the user leaves the app via the home button or other means.

In the manifest put this line in all the activities that you want PORTRAIT
android:screenOrientation="portrait"

Related

When is an activity forcefully recreated?

The Android docs say that configuration changes can force an activity to be recreated, the most common change being a rotation. Now, there are some methods that can determine whether an activity is being destroyed to be recreated but all(?) of these methods are called after onStop() and aren't guaranteed or recommended for data saving purposes.
To give an example, there is an EditText activity which autosaves what they have written/updated if the user navigates away from the app via back button, app switch, e.t.c. However, the user might not want to save their changes when there is a configuration change so I need to be prepared for those cases.
When an activity is destroyed by the system because of configuration change onSaveInstanceState is called.
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
Store data that you want to persist in outState bundle.
Then you'll receive the stored data in onCreate and onRestoreInstanceState.
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
Use it to retrieve data you had stored in onSaveInstanceState earlier.
By default System saves the state of few widgets (EditText , TextView) on it's own and this magic happens in super.onSaveInstanceState().
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
So if you do not want to save the text in EditText , just do editText.setText("") before calling super.onSaveInstanceState().
Hope this helps.

Android save state on orientation change

I've got an Android application which maintains state regarding distance traveled, time elapsed, etc. This state I can conveniently store in an object and store a reference to that object in the Bundle when Android calls onDestroy() when the user changes the screen orientation, then restore the state in onCreate(Bundle savedBundle). However, I also have some state in the Buttons and EditText objects on the screen that I want to persist through screen orientations. For example, in onStart(Bundle savedBundle) I call:
_timerButton.setBackgroundColor(Color.GREEN);
_pauseButton.setBackgroundColor(Color.YELLOW);
_pauseButton.setEnabled(false);
Then throughout the operation of my app, the colors/enabled status of these buttons will be changed. Is there a more convenient way to persist the state of user interface items (EditText, Button objects, etc) without having to manually save/restore each attribute for each button? It feels really clumsy to have to manually manage this type of state in between screen orientations.
Thanks for any help.
Add android:configChanges in the Manifest file
<activity name= ".MainActivity"
android:configChanges="orientation|screenSize"/>
By default, this does not work because changing the orientation causes the onCreate method to be called again and redraws the view.
However, if this parameter is included, the framework will handle preserving the state of the screen or layout if the orientation is changed.
Refer following official documentation for more info:
Activity Lifecycle
Handling configuration changes
To save your variable or values you should use onSaveInstanceState(Bundle); and when orientation changes then should recover values should use onRestoreInstanceState() as well, but not very common. (onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().
Use the put methods to store values in onSaveInstanceState()
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putLong("param", value);
}
And restore the values in onCreate():
public void onCreate(Bundle icicle) {
if (icicle != null){
value = icicle.getLong("param");
}
}

Android Activity life cycle, print methods, save and restore

Im really new to android and i have a little problem that i dont know how to solve.
Im having a small application that prints out the Activity lifes circles methods like this:
protected void onCreate(){
super.onStart()
print("onStart was called"); //this is a void and its only printing a text
}
protected void onStart(){
super.onStart()
print("onStart was called");
}
and so on...
While im i portrait mode the app is showing all the methods on the screen but when i switch to landscape the activity object is of course destroyed and it creates the first three methods again.
Im using onSaveInstanceState an onRestoeeInstaceState to try to save printed order on the screen while i switch from portrait to landscape.
How can i make it work?
example of app output in portrait mode:
onCreate was called
onStart was called
onResume was called
onPause was called
onStop was called
onRestart was called
onStart was called
onResume was called
i want theese prints to stay even if i switch to landscape.
This is onSaveInstanceState and onRestoreInstanceState i dont really know how to solve the problem here.
#Override
protected void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
}
If you go to the manifest I believe you are able to edit it to allow portrait and landscape displays and also have it recall the savedInstanceState. Sorry I can't give you a more detailed answer at the moment.

confused about android example code

I'm looking over some code on the android developer's site and have a quick question about the example show here - http://developer.android.com/guide/components/fragments.html
In particular, I'm looking at this piece of code -
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
What is the point of the second if statement -
if (savedInstanceState == null) {
I can't find any situation where this if statement wouldn't be true. I've tested this code by adding an else statement and setting a breakpoint in it. I could not get to that breakpoint no matter I tried. So why even bother with an if statement? Why not leave it out all together?
There are situations in which your Activity is stopped by the Android operating system. In those cases, you get a chance to save the state of your Activity by a call to [onSaveInstanceState](http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle). If after this, your Activity is started again, it'll be passed the Bundle you created so that you can restore the state properly.
You have to look at the complete example code. With this part it makes sense.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
If you start your Activity the first time the Bundle savedInstanceState will be null and the body of the if statement will be executed. If onSaveInstanceState is called, because you navigated away from the Activity, the Bundle isn't null anymore and the if body will be not executed.
If your app was paused/killed, etc and you saved state by onSaveInstanceState then
savedInstanceState will contain the state of your app that you saved. Otherwise it will be null.
Apparently this was added to the example for future expansion on this code. While it has absolutely no functionality as it stands right now, if this activity were to launch another activity and get killed while the new activity had focus, this code would rebuild the activity when the user hits the back button, rather than rebuilding from scratch.

android: save error state on change orientation

I make a login form with dynamic field validation. I have 3 fields username, email & password & all of these field are required. When field length = 0, I set error
editText.setError( getText(R.string.cannot_be_blank) );
and this code works fine, but when I change the orientation, all the errors disappear
How to save error state?
Thanks.
When the orientation is changed the framework will recreate the Activity by calling onCreate(Bundle savedInstanceState). Before the switch in orientation the onSaveInstanceState(Bundle outState) method will be called if it is overridden in your Activity.
You can save the state of your errors in the Bundle passed into the onSaveInstanceState method. This bundle is passed to your onCreate() method as the savedInstanceState Bundle.
Therefore you need to override the onSaveInstanceState method in your Activity as follows (saving the state of your errors):
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putBoolean("errorOccurred", errorState);
super.onSaveInstanceState(outState);
}
Then in your onCreate method check if the savedInstateState Bundle is null or not. If not, you can retrieve the values out of it with the following code:
boolean errorOccurred = false;
if (savedInstanceState != null) {
errorOccurred = savedInstanceState.getBoolean("errorOccurred");
}
When the orientation is changed the Android framework destroys the Activity and then creates a new one for the new orientation. So all your state is lost.
Use SharedPreferences to store and restore your state and TextEdit values.
What happens when you turn the device is that your Activity runs through its lifecycle in order to deal with the fact that the layout must change from portrait to landscape.
You should take a look at the developer docs on how to Handle Runtime Changes.

Categories

Resources