Question: Necessary to do extra check?


#1

We check the previously saved index by just checking for null.

if (savedInstanceState != null) { Log.d(TAG, "Retrieving saved index =>" + savedInstanceState.getInt(KEY_INDEX, 0)); mCurrentIndex = savedInstanceState.getInt(KEY_INDEX, 0); }

More safer to use this. Is the extra savedInstanceState.containsKey(KEY_INDEX) check not necessary at all?

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


#2

In this case, there is no need to check if the bundle contains KEY_INDEX or not because the default value (second parameter) in the call to savedInstanceState.getInt(KEY_INDEX, 0) matches the initial value of mCurrentIndex.

Calling containsKey is useful if the bundle has optional stuff in it and there is no meaningful default value.


#3

[quote=“almalkawi”]In this case, there is no need to check if the bundle contains KEY_INDEX or not because the default value (second parameter) in the call to savedInstanceState.getInt(KEY_INDEX, 0) matches the initial value of mCurrentIndex.

Calling containsKey is useful if the bundle has optional stuff in it and there is no meaningful default value.[/quote]

Don’t you think savedInstanceState will never be null as it will have views values?


#4

The savedInstanceState parameter will be null when the activity is first started.


#5

Understandable but what about when user rotate the device? I believe then the following code will take care of both the cases, which is mentioned by “usarthurchoi”

if (savedInstanceState!=null && savedInstanceState.containsKey(KEY_INDEX)) { }


#6

If savedInstanceState is not null, then onSaveInstanceState is guaranteed to have been called to stash the appropriate keys in the instance state bundle. So it is not necessary to check for the key, even in the case where the device has rotated.


#7

Thanks for the clarification.