0

I'm trying to save a high score using SharedPreferences. I initialize currentScore and highestScore to zero at the very beginning of my main activity class.

public class MainActivity extends AppCompatActivity {
    int currentScore = 0;
    int highestScore = 0;
    ...
}

When I click on a button to begin a new run after a run has ended, currentScore replaces highestScore if it's higher. This part works well. However, I don't know where to create and use SharedPreferences, editor, putInt, and commit. Each time I close the app, highestScore is reset to zero.

public void newRun(View view){
    if(currentScore > highestScore){
        highestScore = currentScore;
    }
    ...
    //Store and commit highestScore here ?
    //Will it be reset since it is initialized to zero at the class beginning?
}
Jean Vitor
  • 893
  • 1
  • 18
  • 24
Cab
  • 3
  • 2
  • You need to have a persistent storage, like you mentioned `SharedPreference`. – Shaishav Aug 04 '16 at 17:53
  • 1
    Possible duplicate of [Android Shared preferences example](http://stackoverflow.com/questions/23024831/android-shared-preferences-example) – mbmc Aug 04 '16 at 17:54

2 Answers2

0

It is beacause your high score is getting intialized to zero everytime u open the app.... So what u can do is fetch the highest score value from shared preference and reset value of highestscore variable everytime u begin application

Moulesh
  • 2,762
  • 1
  • 22
  • 32
0

The value will be 0 until you create a SharePreferences instance and call getInt. Please refer to here. For example in your onCreate or onStart method retrieve the stored value:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
highestScore = settings.getInt("mTag", 0) 

and in your newRun helper method or onStop commit the value:

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("mTag", highestScore);
editor.commit();
Alexi V.
  • 143
  • 1
  • 2
  • 10
  • The app crashes when I use `SharedPreferences` before `onCreate()`. In `onCreate()`, fetching the `highestScore` with `getInt` to store it in `highestScore` variable makes it invisible to other functions (e.g. `newRun`) outside `onCreate()`. How can I access the variable from functions outside `onCreate()`? – Cab Aug 05 '16 at 13:18
  • @Cab I'm not sure I understand what you mean by invisible? It looks like your highestScore variable is a MainActivity member variable and therefore should be accessible within the scope of the entire class. So as long as your newRun helper method exists and is called from within the MainActivity class and you retrieve the data in onCreate is should work. You can also commit the data in onStop and retrieve it in onStart(). I will edit my answer to include more code and mention more specifically where to place it. – Alexi V. Aug 05 '16 at 22:50