0

Alright guys, homework related question here. No, I don't need you to write code, but I'm hoping someone can help me understand why this works.

Inside my onCreate() function, I have this code

    boolean layout = getResources().getConfiguration().orientation == 1;
    TextView lo = findViewById(R.id.layout);
    if (layout) {
        lo.setText(R.string.port);
    } else {
        lo.setText(R.string.land);
    }

It works correctly, and changes the string in the TextView as I expected it would on screen orientation change, but therein lays my problem. I thought (I'm guessing incorrectly) that each time you rotated the device, it was firing onCreate again, redrawing the screen.

Going ahead with this model in my mind that I found here, and looking to expand on it, I decided to set an int in the main activity, then increment it in onCreate(), and a TextView that would update each time the screen rotated as below.

    TextView oc = findViewById(R.id.count);
    num++;
    oc.setText(valueOf(num));

to my dismay, it never increments past one, no matter how many times I rotate, while the orientation portion always fires.

Hopefully someone can educate me as to why the orientation fires on each rotate, but the other portion does not. Thanks ahead of time, flame away!

Chris Peragine
  • 158
  • 2
  • 8
  • Correct, it will never increment past 1, as you have a new instance of the `Activity` - suggest you use `SharedPreferences` to set/get a incremented value each time. – Mark Dec 15 '17 at 01:26
  • so it is reloading, just further down the rabbit hole more or less, thanks! – Chris Peragine Dec 15 '17 at 01:28
  • On an orientation change android tears down the `Activity` instance - one of the reasons for its lifecycle events. `onCreate()` does suggest, well, its "created" - each time its a new instance, with all new instance variables at default values, or default initialised values. – Mark Dec 15 '17 at 01:30
  • you can save your activity data in bundle onSavedInstanceState and get it using onRestoreInstanceState – yashkal Dec 15 '17 at 05:42

2 Answers2

0

Trying to explain it my way, it'll not increment because the data (your int) is not saved anywhere and is lost when orientation changes. If you wish to achieve the same, you may override the onSavedInstanceState().

cht
  • 319
  • 3
  • 13
0

Each time the orientation changes your activity is recreated, it means that you are getting a new instance of your activity class, so any nonstatic field will be recreated. Also if you make your field static it is not guaranty that your process will not be terminated when your old activity is destroyed(However likely it won't be terminated).

If you want to prevent your activity from being destroyed on orientation changes add those lines to manifest:

android:configChanges="orientation|screenSize"
Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216