首页 > 解决方案 > 如何从两层子活动中获取高分数据到android studio中的主要活动

问题描述

我正在尝试从子活动中获取高分数据(主要活动之前有两个子活动)。现在我有问题将高分数据从子活动转移到主要活动。附上请找到我的代码。如果您能帮助我解决这个问题,我将不胜感激。

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_QUIZ = 1;
    public static final String SHARED_PREFS = "sharedPrefs";
    public static final String KEY_HIGHSCORE = "keyHighscore";

    private TextView textViewHighScore;

    private int highscore;

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

        textViewHighScore = findViewById(R.id.text_view_high_score);
        loadHighscore();

        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQuiz();
            }
        });

    }

    private void startQuiz(){
        Intent intent = new Intent(MainActivity.this,Activity2.class);
        startActivityForResult(intent,REQUEST_CODE_QUIZ);
    }


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

        textViewHighScore = findViewById(R.id.text_view_high_score);
        loadHighscore();
    }*/

    /*public void buttonClicked (View v)
    {
        Intent intent = new Intent(this,Activity2.class);
        startActivity(intent);

    }*/

    public void buttonClicked2 (View view){

        Intent intent = new Intent (this,Activity2.class);
        startActivityForResult(intent,REQUEST_CODE_QUIZ);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == REQUEST_CODE_QUIZ){
            if(resultCode == RESULT_OK){
                int score = data.getIntExtra(Math2BActivity.EXTRA_SCORE, 0);
                if(score > highscore){

                    updateHighscore(score);
                }
            }
        }
    }

    private void loadHighscore(){
        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS,MODE_PRIVATE);
        highscore = prefs.getInt(KEY_HIGHSCORE,0);
        textViewHighScore.setText("High Score: " + highscore);
    }

    private void updateHighscore(int highscoreNew){
        highscore = highscoreNew;
        textViewHighScore.setText("High Score: " + highscore);

        SharedPreferences prefs = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(KEY_HIGHSCORE, highscore);
        editor.apply();
    }
}

标签: javaandroid

解决方案


推荐阅读