spacemalbar
spacemalbar

Reputation: 29

Android - Global Variable keeping its value between all activities

I need to find a way to keep the value of a variable between various activities. It is infact an integer value which is the counter which would be incremented on each click event. Thus the value should be keep on incrementing if the right button is clicked. The problem that i am having is that the value of this variable does not remain the same (For example if it was 1 on Activity A and the right button has been clicked it should become 2 on Activity B). Could you please help me out? I have tried the singleton Class but to no avail. I have also used the intent getExtras which i am having difficulties in dealing with this part.

                 Intent mIntent = getIntent();
         int ScoreCount = mIntent.getIntExtra("intScoreCount", 0);

Instead of the value 0 what value can be added so that it retains the value of ScoreCount?

Thank you so much

Upvotes: 0

Views: 3963

Answers (2)

gulyan
gulyan

Reputation: 662

You should use the Application class to do this. It's the same in all the activities.

Have a look at this post to see how to use it: http://coding-dump.blogspot.ro/2013/01/global-variables-in-android.html

Basically, you extend the Application class and you put your variable there. You can access the instance of this class and increment you counter.

Upvotes: 0

kungfoo
kungfoo

Reputation: 597

Based off your responses. Use SharedPreferences to store/count and reset the count to 0 on app startup. So, either in your Application class or your first Activity, reset the count to 0 so that you are starting over.

Upvotes: 1

Related Questions