2017-04-05 18 views
0

嗨我遇到麻烦sharedpreferences并保存为int的数据,我尝试了一切,但我无法弄清楚。麻烦与共享偏好,节省了int变量

我使用两个独立活动的getExtra将数据提取到主要活动,然后将这些变量添加到一起给我一个总数。我试图做到这一点,当离开主要活动,所有的变量保持不变,更新时,其他两个活动被改变。

这是与sharedpreferences

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(); 
} 

}的主要活动

这是IM如何传递数据

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

你好,请尝试这样

SharedPreferences topic = getSharedPreferences("topicfun", MODE_PRIVATE); 
SharedPreferences.Editor topiccom = topic.edit(); 
topiccom.putInt("topicname",10); 
topiccom.commit(); 
0

您可以简单地添加以下代码,您计算totalGradeTxt后:

SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", 
                MODE_PRIVATE); 
SharedPreferences.Editor editor = totalScorePref 
              .edit() 
              .putInt("TotalScoreY1",pTotalScore) 
              .apply(); 

注:我已经使用申请(),而不是提交()

+0

感谢回答,只是尝试这样做仍然不工作,感觉它不应该这么难。 我在“scoreTotal = year1Score + year2Score”下移动了“editor = totalscorepref” 但仍然得到相同的结果,不保存变量,因为textview未被保存。 – Cambino