Search code examples
javaandroidinheritancestaticcode-reuse

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.


Solution

  • 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.