I noticed that there are three ways to get the value from Extras :

  someInt = getIntent().getIntExtra("KEY", 0); someInt = getIntent().getExtras().getInt("KEY"); someInt = (int) getIntent().getExtras().get("KEY"); 

What is the difference between these methods? If in the latter one can get anything, and here the difference is still clear, then what is the difference between the first and second method?

    1 answer 1

    If you go and see the sources, you can see the following code:

     public int getIntExtra(String name, int defaultValue) { return mExtras == null ? defaultValue : mExtras.getInt(name, defaultValue); } public Bundle getExtras() { return (mExtras != null) ? new Bundle(mExtras) : null; } 

    Both elements work with a mExtra object whose type is Bundle . The first option will return the default value if this object is not set, and the second copy of the mExtra object.

    The Bundle object's getInt(String key, int defaultValue) method getInt(String key, int defaultValue) has the following release.

     public int getInt(String key, int defaultValue) { unparcel(); Object o = mMap.get(key); if (o == null) { return defaultValue; } try { return (Integer) o; } catch (ClassCastException e) { typeWarning(key, o, "Integer", defaultValue, e); return defaultValue; } } 

    and the get(String key) method get(String key) follows:

     @Nullable public Object get(String key) { unparcel(); return mMap.get(key); } 

    Both of them work with the mMap object, only the first method immediately converts the result to an int or returns the default value, while the second returns the Object type, which you will have to manually cast.

    Based on the implementation of these methods, it is clear that the getIntExtra(String name, int defaultValue) is a shortcut relative to other methods. It is also safer, because you won't get a NullPointerException or ClassCastException