Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the same variable between Activities in Android

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.

like image 552
Kayden Rice Avatar asked Dec 05 '22 20:12

Kayden Rice


2 Answers

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.

like image 145
Y.S Avatar answered Dec 22 '22 01:12

Y.S


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

like image 23
ZanoOnStack Avatar answered Dec 22 '22 00:12

ZanoOnStack