I'm wondering how I would go about accessing the same int variable between all my Activity classes in my Android app. My situation is that I have a variable that represents a number of points and I've placed it in its own class and I want the value to be the same between every Activity that uses it.
When the user gets a point, it increases by 1 so let's say the user gets 12 points, I want it to be the same throughout all the Activitys.
STEP 1:
Extend all your Activitys from a common BaseActivity class.
STEP 2:
Put your int variable in BaseActivity and add the protected and static qualifiers to the int variable:
public class BaseActivity extends Activity{
....
....
protected static int points;
....
....
}
Now you can access the points variable in every Activity and it will have the same value.
There is no need to use a singleton here as the other answers are suggesting. Its much simpler to have a common static variable. Its programming 101.
Try this. This will work.
You can use a singleton object class. But it is a java elementary pattern.
public class MySingletonClass {
private static MySingletonClass instance;
public static MySingletonClass getInstance() {
if (instance == null)
instance = new MySingletonClass();
return instance;
}
private MySingletonClass() {
}
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
}
And you can use every where
MySingletonClass.getInstance().getInt;
and
MySingletonClass.getInstance().setInt(value);
It's not the fastest mode, but it's one of the best. In fact you can add how many var you want, and you can access from everywhere, also in not-Activity class
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With