6

i read document about getInt() method :

public int getInt (String key)

Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.

Parameters:

key a string

return:

an int value

but i can't get it that what it exactly return.

the ID of key that is in R.java or no something else???

hamid_c
  • 849
  • 3
  • 11
  • 29
  • 2
    the value of the key for example {"data":1}, getInt("data") = 1 – Proxytype Jul 03 '15 at 15:31
  • 1
    what it returns depends on the parameter you send (as the description explains). If you have a set {{"one", 1},{"two",2}} "one" will return 1, "two" will return 2, and "three" will return 0 – Stultuske Jul 03 '15 at 15:31
  • @Proxytype the parameter is a string, and what about { key = "possition" ; } ??? – hamid_c Jul 03 '15 at 15:33
  • 1
    @hamid_c: the "data" in his example is a String. if the key = "possition", in Proxytype's example it would return 0, since he has no element with that key in his set. – Stultuske Jul 03 '15 at 15:34
  • i believed it will throw exception or zero.. – Proxytype Jul 03 '15 at 15:34
  • Exception of zero? what do you mean by that? it will return 0 (not throw an Exception) because there is no element with key "possition". and, the method is designed to return "0 if no mapping of the desired type exists for the given key." – Stultuske Jul 03 '15 at 15:49

2 Answers2

5

It returns whatever you've put in that bundle with the same key.

Bundle bundle = new Bundle();
bundle.putInt("KEY", 1);
int value = bundle.getInt("KEY"); // returns 1

It's simply a map/dictionary datatype where you map a string value with something else. If you have other datatypes, you should use the appropriate put/get-methods for that datatype.

Patrick
  • 17,669
  • 6
  • 70
  • 85
4

Nothing better that with an example

Suppose you have two activities: Activity1 and Activity2 and you want to pass data beetwen then:

Activity1

private static final String MY_KEY = "My Key"
Intent intent = new Intent(Activity1.this, Activity2.class);
Bundle b = new Bundle();

b.putInt(MY_KEY, 112233);

intent.putExtras(b);

startActivity(intent);

Activity 2

private static final String MY_KEY = "My Key"
Bundle b = getIntent().getExtras();

int value = b.getInt(MY_KEY , 0);

//value now have the value 112233

What means "Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key." in this example?

Using Bundle you're sending the value 112233 from Activity 1 to Activity 2 using the key "MY_KEY". So, "MY_KEY" is associated with 112233.

As you can see there is a second parameter “0”.

It is the default value. In situation when Bundle doesn’t contains data you will receive “0” (default value).

Jorge Casariego
  • 21,948
  • 6
  • 90
  • 97