Bhaumik Vyas Bhaumik Vyas - 4 months ago 17
Java Question

Access global Method of Global Class in Static Method

I have created one Static Method in one of my class and in the same static method I want to access the method of my Global Class, if I am creating the class by -

final GlobalClass globaVariable = (GlobalClass)getApplicationContext();


then it is showing me error and suggesting me to make this object static and if I am making this object static then I am not getting the values from my global class and method as it's creating the fresh copy. Please suggest me that how can I get the access the global method in static method.

My Global Method is as bellow :

public class GlobalClass extends Application {

private int vMyToken;
private String vConCmpName;
private boolean vUserLoginMode;
private String vGlobalSessionID;
private String vglobalAccInternalID;


public int getToken() {

return vMyToken;
}

public void setToken(int myTokenVal) {

//Toast.makeText(GlobalClass.this, "", Toast.LENGTH_SHORT).show();

vMyToken = myTokenVal;
}

}

Answer

One solution would be to convert the instance variables in GlobalClass to static and also make the method in GlobalClass static. As the variables are static only a single copy will be maintained and the static method can access these variables.

private static int vMyToken;
private static String vConCmpName;
private static boolean vUserLoginMode;
private static String vGlobalSessionID;
private static String vglobalAccInternalID;
Comments