Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Shared Preferences for High Score saving

Hell I am trying to make highscore for my project but my code is only saving last value not highest value How can I store only highest value? here is my code .

This is saving process ->

            SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            TextView outputView = (TextView)findViewById(R.id.textscore);
            CharSequence textData = outputView.getText();

            if (textData != null) {
               editor.putString(TEXT_DATA_KEY, textData.toString());
               editor.commit();
            } 

This is Reading process

  SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);

  String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");


            TextView outputView = (TextView) findViewById(R.id.textread); 
like image 660
Boldbayar Avatar asked Oct 01 '22 07:10

Boldbayar


2 Answers

You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest

E.g.

      if (textData != null) {
           int score = Integer.parseInt(textData.toString());

           if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
           {
               //editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
               editor.putInt(TEXT_DATA_KEY, score);
               editor.commit();
           }
        } 
like image 96
IAmGroot Avatar answered Oct 05 '22 10:10

IAmGroot


You need to store a new value only if the existing value in shared preferences is lesser than the new value.

You don't seem to be having this value check in your code

like image 22
Rajeev Avatar answered Oct 05 '22 12:10

Rajeev