java共享首选项有问题,保存int变量
嗨,我在SharedReferences和保存int的数据方面遇到了问题,我已经尝试了所有方法,但我无法解决
我使用两个独立活动的getExtra将数据拉到主活动中,然后将这些变量相加,得到一个总数。我正在努力使它在离开主活动时,所有变量保持不变,并在其他两个活动更改时更新
这是SharedReferences的主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YearOneActivityButton();
YearTwoActivityButton();
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", MODE_PRIVATE);
scoreTotal = totalScorePref.getInt("TotalScoreY1", 0);
Intent totalGradeValueY1 = getIntent();
Intent totalGradeValueY2 = getIntent();
int year2Score = totalGradeValueY2.getIntExtra("totalYearValueY2", 0);
int year1Score = totalGradeValueY1.getIntExtra("totalYearValueY1", 0);
scoreTotal = year1Score + year2Score;
numberScore = (TextView)findViewById(R.id.number_score_txt);
numberScore.setText(String.valueOf(year1Score));
numberScore1 = (TextView)findViewById(R.id.number_score_1_txt);
numberScore1.setText(String.valueOf(year2Score));
totalGradeTxt = (TextView)findViewById(R.id.total_grade_txt);
totalGradeTxt.setText(String.valueOf(scoreTotal));
Log.d("SCORETOTAL", String.valueOf(scoreTotal));
}
@Override
public void onPause(){
int pTotalScore = scoreTotal;
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", 0);
SharedPreferences.Editor editor = totalScorePref.edit();
editor.putInt("TotalScoreY1", pTotalScore);
editor.commit();
super.onPause();
}
}
这就是我传递数据的方式
public void SubmitMainActivity() {
ButtonSubmit = (Button) findViewById(R.id.button_submit);
ButtonSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int totalGradeValueY1 = totalAllSpinnerValuesY1;
Intent year1ScoreIntent = new Intent(YearOneActivity.this, MainActivity.class);
year1ScoreIntent.putExtra("totalYearValueY1", totalGradeValueY1);
startActivity(year1ScoreIntent);
}
});
}
# 1 楼答案
在计算完TotalGrade TXT后,只需添加以下代码即可:
# 2 楼答案
嗨,请像这样试试