嗨,我遇到了共享偏好和保存int数据的问题,我已经尝试了一切,但我无法弄明白。
我使用来自两个单独活动的getExtra将这些数据提取到主要活动,然后将这些变量添加到一起以给我一个总计。我试图做到这一点,以便在离开主要活动时,所有变量保持不变,并在其他两个活动发生变化时更新。
这是共享偏好的主要活动
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);
}
});
}
答案 0 :(得分:0)
嗨,请尝试这样
SharedPreferences topic = getSharedPreferences("topicfun", MODE_PRIVATE);
SharedPreferences.Editor topiccom = topic.edit();
topiccom.putInt("topicname",10);
topiccom.commit();
答案 1 :(得分:0)
您可以在计算 totalGradeTxt 后添加以下代码:
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref",
MODE_PRIVATE);
SharedPreferences.Editor editor = totalScorePref
.edit()
.putInt("TotalScoreY1",pTotalScore)
.apply();
注意:我使用了apply()而不是commit()