I am creating an app to test the user on their knowledge on certain subjects. For each test they will get a score. There score is an int, (finalscore) but I am struggling to make it so that finalscore is visible in other activities. Any help would be much appreciated.
Asked
Active
Viewed 50 times
4 Answers
1
Try using a singleton extending your Application
.
public class GlobalVars extends Application {
private int finalscore = 0;
int getPoints() { return finalscore; }
void setPoints(final int newpoints) { finalscore = newpoints; }
...
}
So if you have to get or set values for that int
, just use:
GlobalVars globvars = ((GlobalVars) getApplicationContext());
globvars.setPoints(5);
This is "project-wide", so you can call it in any Activity
.

nKn
- 13,691
- 9
- 45
- 62
-
2Why would you do this vs passing an extra properly!? – Nick Cardoso Feb 04 '14 at 21:09
-
This is simpler in some ways. But there's no need to extend Application--any singleton class with static get and set methods would do. – Tenfour04 Feb 04 '14 at 21:10
-
Personally I'd use `SharedPreferences`. – Squonk Feb 04 '14 at 21:11
-
Those are valid approaches as well, probably the `SharedPreferences` is even easier. – nKn Feb 04 '14 at 21:13
1
You can pass the integer to the next activity by adding it as an extra :
Intent nextActivity = new Intent(CurrentActivity.this,NextActivity.class);
nextActivity.putExtra("finalscore",finalScore);
startActivity(nextActivity);
Then in the next activity, get the score by using :
int finalScore = getIntent().getIntExtra("finalscore", 0);
Notice that the string "finalscore" is the same in the two activities. You can use a constant to be sure not to make mistakes.

TheCopycat
- 401
- 2
- 6
1
You should be passing the int between activities
When you open a new activity
Intent intent = new Intent("MY ACTION");
intent.putExtra("MY_INT_KEY", intValue);
startActivity(intent);
And in onCreate of the next activity
getIntent().getExtras().getInt("MY_INT_KEY");

Nick Cardoso
- 20,807
- 14
- 73
- 124
0
To make some value visible to all activities from your app, you can also use SharedPreferences. These store key-value pairs.
Saving
//create prefs object, "myprefs" is just a file name where your values will be stored SharedPreferences prefs = getSharedPreferences("myprefs", Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); //store your integer editor.putInt("score", scoreValue); //save editor.commit();
Reading - can be done in any activity
//create prefs object, "myprefs" is just a file name where your values will be stored SharedPreferences prefs = getSharedPreferences("myprefs", Context.MODE_PRIVATE); //read the value for key "score", and assign to the variable int score = prefs.getInt("score", 0); //<------ 0 here is default value in case "score" key doesn't exist, you can replace it with any value
More info here.

Melquiades
- 8,496
- 1
- 31
- 46