Listing 3.7 Overriding onStateInstanceState


Hi everyone!

Going through the Android book right now and I had a specific question about listing 3.7.
On the code it says to put

if(savedInstanceState!= null){ mCurrentIndex = savedInstanceState.getInt(KEY_INDEX,0); }
I looked up Bundle.getInt() and this is what it says:

[code]public int getInt (String key, int defaultValue)
Returns the value associated with the given key, or defaultValue if no mapping of the desired type exists for the given key.

key a String
defaultValue Value to return if key does not exist[/code]

I am wondering why we need to call if-else if it already returns its default value if the key does not exist. However I did try it without the if function and it didn’t compile. :open_mouth: Thanks!


Because the if is not checking if a new value for that key exists in the Bundle object or not. It checks if the bundle is null or not. Without the if as shown, there will be a path that tries to access a potentially null savedInstanceState object, hence the compile error.

PS: if is not a function, it’s just a statement.