java - Trying to pass an int between two classes on Android platform -
java - Trying to pass an int between two classes on Android platform -
i'm trying pass int between 2 classes using bundle. have looked online , seems should easy do, not working me :( help much appreciated! trying pass int life 1 page in simple game.
here code first page passing
int life = 5; .... if(input.equalsignorecase(teststr)) { intent = new intent("com.name.pagetwo"); i.putextra("com.name.pagetwo.life", life); startactivity(i); mpbuttonclick.stop(); }
and on sec page, trying receive int
intent = new intent("com.name.pagetwo"); bundle extras = i.getextras(); int temp2 = extras.getint("life"); int life = temp2;
when seek run it, tries go on sec page , says application has unexpectedly stopped, when comment out code continues running normal, know putting in code here wrong somewhere. in advance!
you're creating brand new intent on sec page, of course of study doesn't have bundle. instead, need retrieve calling intent using getintent().
here's how sec page's code look:
int life = getintent().getextras().getint("life");
edit: looking @ code again, create sure key name of consistent on both ends. sure, utilize final variable this. in sec activity (let's it's activitytwo
), declare @ top (outside of oncreate()
):
final static public string extra_life = "life";
then in calling activity:
intent = new intent(this, activitytwo.class); i.putextra(activitytwo.extra_life, life); startactivity(i);
(you may have been constructing intent incorrectly; compare example).
and in sec activity, within of oncreate()
:
int life = getintent().getintextra(extra_life, 0);
(you can replace 0
want default value if doesn't exist.)
that way don't have worry typos , can rely on eclipse's suggestions create sure you're consistent.
java android
Comments
Post a Comment