java - 如何从两层子活动中获取高分数据到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();
}
}
解决方案
推荐阅读
- java - 由于 PoolingClientConnectionManager.setMaxTotal 和 setDefaultMaxPerRoute 增加,内存利用率和线程数较高
- javascript - 如果目标值项在数组中
- javascript - 使用正则表达式和 Javascript 查找括号中的数字
- odata - 智能过滤器 Go 按钮返回错误消息
- android - 关闭另一个类的自定义对话框
- twitter-bootstrap - 如何在小屏幕中隐藏 col 并在大屏幕中显示?
- c++ - UWP/C++ 中的 OpenCV DNN 人脸检测:结果不佳
- python - 如何将变量从一个函数传递到python中的另一个函数
- r - 使用蒙特卡罗模拟的错误传播数据帧
- sql-server - 使用回溯记录计算自定义时间