GameActivity というクラスでアクティビティを再作成するたびに、スコアを保持するための値を保存しようとしています。onCreate()
メソッドに次のコードを挿入します。
SharedPreferences settings = getSharedPreferences("Score", 0);
int lastscore = settings.getInt("Score", 0 );
score=lastscore;
mScoreView.setText("Score: "+ score);
mScoreView
アクティビティが再作成されるたびに現在のスコアで更新されると想定される TextView オブジェクトでscore
あり、インスタンス変数です。各ゲームの最後にポップアップするボタンがあり、ユーザーはアクティビティを再作成してプレイを続けることができます。そのボタンのクリックリスナーは次のとおりです。
private class MyButtonListener2 implements OnClickListener {
public void onClick(View v) {
State player = mGameView.getCurrentPlayer();
Bundle myBundle=new Bundle();
firstGame=false;
if (player == State.WIN) {
if(player==State.WIN){
SharedPreferences scoreSaved = getSharedPreferences("Score",0);
SharedPreferences.Editor edit = scoreSaved.edit();
edit.putInt("Score", score++);
edit.commit();
//onCreate(myBundle);
}
else{
myBundle.putInt("score1", 0);
//onCreate(myBundle);
}
GameActivity.this.recreate();
onCreate(myBundle);
}}
スコアは、人間のプレイヤーが勝利してゲームが終了するたびに 1 ずつ増加すると想定されています (State.WIN)。ただし、スコアは正しく更新されません。エラーをキャッチするのに問題があります