Hi I am doing one app here. I\'m using global class varibles. It\'s working well, but if I\'m using more globalclass variables I\'m getting memory exceptions some times.
You can use like this
public class GlobalVar {
public int getMyVar() {
return myVar;
}
public void setMyVar(int myVar) {
this.myVar = myVar;
}
private int myVar = 0;
private static GlobalVar instance;
static {
instance = new GlobalVar();
}
private GlobalVar() {
}
public static GlobalVar getInstance() {
return GlobalVar.instance;
}
}
then you can call like
GlobalVar.getInstance().setMyVar(int);
You can also use Global Variable Activity class wise. As for example
public class SecondClass extends Activity {
String S1,S2,S3;
EditText edt1,Edt2,Edt3;
Button btn1,btn2,btn3;
//like this wat Declare all variable you want to use in your Present Activity Class
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
edt1= (EditText)findViewById(R.id.tv);
}
}
Take a look at the post Singletons vs. Application Context in Android?
There are a lot of discussion about Singletons vs Application objects in the forum. I'm personally inclined to Application object with properties. If you dont want to keep in memory a lot of objects use a LruCache (there is a pre v11 implementation in the compatibility package) to low your memory requirements.
Take into account you will eat the same amount of memory using Singletons than using the Application object, all objects will be keep in memory until you free them (remove any refrence to them and let the GC purge them from memory).
First thing, you dont need Static Variable to declare global variable in Application Class,
so Change your code to:
class GlobalClass extends Application {
public String myVal;
}
then whereever you need to access this data, get Application object by:
GlobalClass global=(GlobalClass)context.getApplication();
global.myVal="anything";