简体   繁体   中英

Android - Recreating an acivity - Bundle

Here is the code for recreating an activity.

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

Here,I have a doubt in the definition of putInt() method of bundle. When I looked for its definition, I got the following documentation -

public void putInt (String key, int value)
Added in API level 1
Inserts an int value into the mapping of this Bundle, replacing any existing value for the given key. Parameters
key: a String, or null
value: an int, or null

I don't understand what is being done with the String key ? I mean to say, is it like that. that every time key is used as a pointer to add matter to the bundle ? Moreover, is there any need of defining STATE_SCORE as "playerscore" ?

Nothing will be done to your string key. It is just like a hash map. I don't quite understand your last question, it is good manner to define the key as a constant.

Bundle works like a dictionary. In a dictionary you use a keyword to look for a meaning (or definition). That's the purpose of the String . Bundle use it to retrive the value linked to that key.

Moreover, is there any need of defining STATE_SCORE as "playerscore"

that's not strictly neccessary, but if you declare a constant for your keys, and use always the costant to store/retrieve values from bundle the probability of mispelling decrease near to zero (so more headcache due of intesive debuggin hours)

is there any need of defining STATE_SCORE as "playerscore". Ans is NO you can directly give the string

savedInstanceState.putInt("playerscore", mCurrentScore);

I don't understand what is being done with the String key

it is like a key value pair. when you do this

 savedInstanceState.putInt("playerscore", 1);

the value 1 is stores with the key "playerscore" and when you do a get

savedInstanceState.getInt("playerscore");

This will return 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM