-1

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.

4 Answers4

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

  1. 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();
    
  2. 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