Search code examples
androidconstructorinitializationactivity-lifecycle

Android Activity: Where to initialize parameters?


I have some variables which must be initialized only once durign activity life-cycle. If I initialize them inside OnCreate method, like this:

ArrayList<Integer> numbers = new ArrayList<>();
protected void onCreate(Bundle savedInstanceState) {
    numbers.add(1);
    numbers.add(2);
    numbers.add(3);
}

initialization process happens every time which there are some configuration changes like screen rotation and etc since they will call OnCreate again and again.

I'm not going to disable configuration changes like screen rotation to fix this but I want to know where to place my initialization which initialization happens only once during activity life cycle.


Solution

  • initialization process happens every time which there are some configuration changes like screen rotation and etc since they will call OnCreate again and again.

    That is because it is a new activity instance. By default, any fields will be null if you do not initialize them.

    You are welcome to use the saved instance state Bundle, retained fragments, or other techniques to hold onto that data.