I'm trying to extract an int from an Intent I created, but the second one throws up an error "Cannot convert java.lang.String to int", while the first one does not. Why does this happen?
Thanks
to get an int
value you need to use
getIntent().getIntExtra("x", 0)
or
getIntent().getExtras().getInt("x")
The first one is:
(Integer)getIntent().getExtras().get(x)
This retrieves an Object
based on the key x
and attempts to cast that to be an Integer
. If get()
returns something else, you crash at runtime with a ClassCastException
.
The second one is:
(Integer)getIntent().getStringExtra(x)
This retrieves a String
based on the key x
and attempts to cast that as an Integer
. It is possible that an Object
might be an Integer
, which is why the first one compiles but might fail at runtime. It is not possible that a String
is an Integer
. Hence, this fails at compile time.
The right answer, as Mr. Oleg notes, is to call getIntExtra()
on the Intent
or getInt()
on the Bundle
returned by getExtras()
.
It's all about casting.
getIntent().getExtras().get(x) returns an Object type.
While (Integer)getIntent().getStringExtra(x) returns an String type Object.
If you recall(or just learning), every Java Class
extends Object by default and thos get it's mehtods such as toString()
.
This is why you can try to cast Object to ANY class. try - but if it fails you will know it only at run-time.
On the other hand, a String
is a class that already extends Object
and has nothing to do with Integer
and it's own values and properties.
So, when you try to cast from a String
to a Integer
you get an error.
The best solution was already published.
I'll just add that you can still do this:
getInteger(getIntent().getStringExtra(x));
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.