What is wrong with this use of Application context in Android? -
i abstract model this:first there class userinfo
holds user information:
public class userinfo extends application{ private int userid; public void setuserid(int id) { userid=id; } public int getuserid() { return userid; } }
then in mainactivity:
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); ... userinfo=(userinfo)getapplication(); userinfo.setuserid(1354); .... intent intent=new intent(mainactivity.this,voteactivity.class); startactivity(intent); } public @override void onresume() { super.onresume(); textview text=(textview)mainactivity.this.findviewbyid(r.id.usernametext); text.settext(userinfo.getuserid()+" "); }
and in voteactivity:
@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_vote); userinfo=(userinfo)getapplication(); button back=(button)findviewbyid(r.id.backbutton); back.setonclicklistener(new onclicklistener(){ @override public void onclick(view arg0) { userinfo.setuserid(-100); intent intent=new intent(voteactivity.this,mainactivity.class); startactivity(intent); }}); }
the result is: when mainactivity first run, userid in userinfo 1354 ; , when voteactivity first run, userid in userinfo 1354 too.however when mainactivity voteacitivy userid remains 1354 should -100.what wrong use of application context?
you're starting new activity in onclick method :
intent intent=new intent(voteactivity.this,mainactivity.class); startactivity(intent);
and direct set id in mainactivity :
userinfo.setuserid(1354);
that's why (1354). should call finish in on click (instead of starting mainactivity).
the activity's stack : mainactivity - voteactivity - mainactivity
, think want : mainactivity
after pressed on button
@override public void onclick(view arg0) { userinfo.setuserid(-100); finish(); }});
Comments
Post a Comment