如何将SAVED值“ highscore”加载到MainActicity中?

时间:2019-01-15 00:30:30

标签: java android sharedpreferences

在我的Game.class中,我已经为highscore保存了一个值,并且在同一活动中加载它时,它可以很好地工作。

这里的问题是,当我想在highscore中显示MainActivity时,它会显示默认值0。

然后,当我继续游戏并正确显示它时,因为一旦运行Game.class Activity,它就会加载保存的值。

但是,如果我关闭该应用程序并重新启动,则再次显示默认值0。 打开应用程序后,如何加载保存的值而不是默认值?

public class MainActivity extends AppCompatActivity {

    TextView hsTxt;  //highscore View

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        hsTxt = findViewById(R.id.hs_main);

        hsTxt.setText(String.valueOf(game.highscore));
    }
}


public class game extends AppCompatActivity {
    TextView hsTxt;
    TextView scTxt;

    int counter_int;  //contador tomado del textView
    String result;
    String counter_string;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_game);

        hsTxt = findViewById(R.id.highscoreTxt);
        scTxt = findViewById(R.id.scoreTxt);

        SharedPreferences pref = getSharedPreferences("HighScore", Context.MODE_PRIVATE);
        highscore = pref.getInt("HS", 0);   //HERE IS THE DEFAULT VALUE
    }

    public void TapShape(View view) {

        counter_string = counterLayout.getText().toString();
        counter_int = Integer.parseInt(counter_string);
        counter_int += 10;  //CONTADOR AUMENTA DE 10 SIEMPRE
        score = counter_int;

        result = String.valueOf(counter_int);
        counterLayout.setText(result);    //SCORE IS INCREMENTED PER TAP


        if (score > highscore) {
            highscore = score;

            //HERE I SAVED THE HIGHSCORE
            SharedPreferences pref = getSharedPreferences("HighScore", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit(); //se edita el archivo 'HighScore'
            editor.putInt("HS", highscore);
            editor.commit();

        }
    }

1 个答案:

答案 0 :(得分:0)

我解决了通过这种方式加载保存的数据的问题。

SharedPreferences pref = getSharedPreferences("HighScore",Context.MODE_PRIVATE); //this file was previously created, I just loaded it.
 int hs = pref.getInt("HS",0);
 hsTxt.setText(String.valueOf(hs));