Doesn't matter where i put if (savedInstanceState!=null){}


#1

Hi guys! Let me show you 2 examples of my code.

example 1:
    @Override
        protected void onCreate(Bundle savedInstanceState) {
        	 if (savedInstanceState != null){
             	mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, mCurrentIndex);
             };
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_quiz);

example 2:

@Override
    protected void onCreate(Bundle savedInstanceState) {        	 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quiz);
        if (savedInstanceState != null){
         	mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, mCurrentIndex);
         };

I’m wondering how come it doesn’t matter where do i put

if (savedInstanceState != null){
         	mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, mCurrentIndex);
         };

in my code. My hypothesis was that setContentView displays the current layout, which is different if mCrrentIndex is changed. So it would matter if I FIRST set the content view and THAN check what int does the mCurrentIndex have. Well it turned out thats not the case and i don’t know why. Could anyone explain?


#2

Set setContentView inflates the layout (view tree). From there, you can then pick off the child views within the tree by referencing them by their resource IDs. The mCurrentIndex is not used until the call towards the end of onCreate when it calls updateQuestion. Now, it does make a difference if you fail to call setContextView BEFORE attempting to access a child view within the layout. You’ll get the dreaded JavaNullPointerException in that case since the view and its child views have not been instantiated.