Amai Amai - 5 months ago 41
Android Question

Android global variable vs cannot resolve method getApplication()

I'm trying to create a global variable as shown in mutliple other stack answers, but when I follow all those instructions, I get "cannot resolve method getApplication()" when trying to get or set this variable in any other activity. What am I doing wrong and how do I then get/set this variable? Here's the 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 the another 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;
}
});
}
}

Answer

You need to implement it in Application custom class not in Activity. Something like this:

public class CustomApplication extends Application {

    private Tracker mTracker;

    public Tracker getDefaultTracker() {
        if (mTracker == null) {
            mTracker = new Tracker();
        }
        return mTracker;
    }
}

And get this from any Activity class like:

CustomApplication app = (CustomApplication) getApplication();
app.getDefaultTracker();

Or better use Singleton pattern to store global state and variables.