Define Global Variable in Android
When we talk about global variable in java its not that the technique java has for that you have to make a single instance of a class.
How its done in android?
For this you have to create a Class named is as GlobalVariable.java,then extends the class with Application so that we can create only one instance of the class.
import android.app.Application;
public class GlobalVariable extends Application {
//add this variable declaration:
public static String global_variable;
//Generate getter and setter
public static String getgobal() {
return global_variable;
}
public static void setglobal(String global_variable) {
GlobalVariable.global_variable = global_variable;
}
private static GlobalVariable singleton;
public static GlobalVariable getSingleton() {
return singleton;
}
public static void setSingleton(GlobalVariable singleton) {
GlobalVariable.singleton = singleton;
}
public static GlobalVariable getInstance() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
}
Usage is
GlobalVariable.setglobal("Android");
If you do Log.d("string stored is",GlobalVariable.getglobal());
You find Out in your LogCat the Android is printed.
Comments
Post a Comment