Hello, I am a novice developer and I create a game, and I need to save data when I lose, and then output this data to another activity depending on which button was pressed (which difficulty level was chosen) Here is my data retention code:

shar=getSharedPreferences("sohr",Context.MODE_PRIVATE); edit=shar.edit(); 

Loss method:

 void game_over(){ vz_texta(); final AlertDialog.Builder adb= new AlertDialog.Builder(MainActivity.this); adb.setTitle("Вы проиграли"); adb.setMessage("Вы за игру набрали:"+v+ "\n"+"Начать сначал?"); adb.setIcon(R.drawable.ic_launcher); adb.setCancelable(false); DialogInterface.OnClickListener negativeListener = new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { edit.putInt("sohr",v); edit.commit(); finish(); } }; DialogInterface.OnClickListener positiveListener = new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface p1, int p2) { mainTextView1.setText(""); soz_primer(); s=60; time.setText(""+s); rez.setText(""+0); adb.create(); } }; adb.setNegativeButton("Нет",negativeListener); adb.setPositiveButton("Да",positiveListener); AlertDialog alert = adb.create(); alert.show(); } 

But I do not know how then to transfer my constant to another activity and I don’t know how to make sure that the data is saved depending on the choice of complexity. Please help!

  • In another activity, create a new copy of the preferences with the same name and read from it on the keys to which you saved it in the first one. The name of the key and the name of the preferences is better to come up with different and more "talking" about the appointment. - pavlofff

1 answer 1

You can get the value in another activity like this:

 SharedPreferences shar = getSharedPreferences("sohr", Context.MODE_PRIVATE); //0 - значение, которое вернётся, если по ключу не будет найдено число. int a = shar.getInt("sohr", 0); 

The main thing is to transfer to the getSharedPreferences method the same file name to which you wrote the data, and not to make a mistake in the keys.