Android global variable vs cannot resolve method getApplication() -
i'm trying create global variable shown in mutliple other stack answers, when follow instructions, "cannot resolve method getapplication()" when trying or set variable in other activity. doing wrong , how get/set variable? here's mainactivity code:
public class mainactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); toolbar toolbar = (toolbar) findviewbyid(r.id.toolbar); setsupportactionbar(toolbar); } private int globalvariable_move; public int getglobalvariable_move() { return globalvariable_move; } public void setglobalvariable_move(int value) { globalvariable_move = value; }
and here's activity code:
public class playactivity extends appcompatactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_play); gameview.setontouchlistener(new view.ontouchlistener(){ public boolean ontouch(view v, motionevent event){ int tempglobalvariablemove = ((mainactivity) this.getapplication()).getglobalvariable_move(); return true; } }); } }
you need implement in application custom class not in activity. this:
public class customapplication extends application { private tracker mtracker; public tracker getdefaulttracker() { if (mtracker == null) { mtracker = new tracker(); } return mtracker; } }
and activity class like:
customapplication app = (customapplication) getapplication(); app.getdefaulttracker();
or better use singleton pattern store global state , variables.
Comments
Post a Comment