我有两个活动。一个是HomeScreen,另一个是GridView。该应用程序打开 HomeScreen Activity,其SharedPreferences如下所示。
在我选择播放按钮并移动到下一个GridView活动并玩游戏后,它应该将分数添加到SharedPreferences但是当我按下后退按钮返回HomeScreen Activity 时,分数似乎没有除非我强制关闭并重新打开,否则会更新。调用onResume()方法将使分数加倍而不是一次。
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
addScores();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
play = (Button) findViewById(R.id.play_game);
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showMovieDialog();
}
});
}
public void addScores(){
final SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
totalCoins = app_preferences.getInt("Scores: ",0);
SharedPreferences.Editor editor = app_preferences.edit();
totalCoins = totalCoins + Bollywood.coins;
tCoins = (TextView)findViewById(R.id.totalCoins);
tCoins.setText("" + totalCoins);
editor.putInt("Scores: ", totalCoins);
editor.commit();
}