Search code examples
androidbundleandroid-savedstate

What is the second parameter in savedInstanceState.getInt?


I'd like to understand something from the following Android fragment docs: Android fragment docs

In the example at the end of the page, the mCurCheckPosition int is saved in a bundle as "curChoice":

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

However, at the start of the example, when checking for and possibly retrieving "curChoice", there is a second parameter '0' that is provided:

 if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }

What is this zero doing there? Surely the point of referencing "curChoice" is to retrieve the value that was saved under it in the first place?


Solution

  • What is this zero doing there?

    Quoting the documentation, it is the "value to return if [the] key does not exist".

    Surely the point of referencing "curChoice" is to retrieve the value that was saved under it in the first place?

    Yes, and in this case, the default value would seem to be superfluous. In general, the default value is for cases where the key is conditionally added to the Bundle, so the consumer of the Bundle can cleanly handle the case where the key was not added.