After adding these lines, the application stopped running and the phone shows that there is a threat

Preservation

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("best_score", score); editor.commit(); 

Loading

 SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); if (sharedPreferences.contains("best_score")) { // we have a high score saved, load it... int bestscore = sharedPreferences.getInt("best_score", -1); scores.setText("Лучший : " + bestscore); // here you'd like to do something with the value, for example display it. } else { scores.setText("Лучший : 0"); // there is no high score value - you should probably hide the "best score" TextView } 

UPD: checked-checked and noticed that as soon as I add the line SharedPreferences.Editor editor = sharedPreferences.edit(); immediately the application stops running

  • what kind of "threat"? - pavlofff
  • @pavlofff may contain viruses - EvgeniyDodg
  • I had this when I created an application with an icon and a name from VKontakte and with com.vkontakte.hack. maybe you have something the same? - Flippy
  • @Flippy but before that it wasn’t .. I didn’t change the icons and the package - EvgeniyDodg
  • @Flippy just specially commented out all the lines related to SharedPreferences and it all worked - EvgeniyDodg

1 answer 1

To get SharedPreferences, you do not need to run the Editor . And checking .contains() also unnecessary, it slows down the loading time greatly, especially if the code is in onCreate() .

Do something like this:

 mSharedPref = getPreferences(Context.MODE_PRIVATE); int bestscore = mSharedPref.getInt(getString(R.string.best_score), 0); scores.setText("Лучший : " + bestscore); 

If best_score absent, the default value 0 will be used.