在Quiz游戏上使用SharedPreferences实现分数和高分

时间:2015-09-14 14:37:58

标签: android sharedpreferences android-sharedpreferences

所以我在这里使用Android Studio进行测验游戏。我在我的测验游戏中实施了this。如果答案是正确的,则分数与之前的分数相加,我认为很好,但是当我尝试打开HighScore Activity应用程序崩溃时。这是PlayQuizActivity中的代码:

public class PlayQuizActivity extends Activity implements View.OnClickListener {

//Initializing Variables
private static int QUESTIONS = 4;

private DBPref db;
private TextView tv_question;
private Button option_1;
private Button option_2;
private Button option_3;
private Button option_4;
private TextView tv_time;
private ImageView iv_question;
private Context context;
private TextView scoreText;

private SharedPreferences gamePrefs;
public static final String GAME_PREFS = "ArithmeticFile";

CountDownTimer Timer;
ProgressBar progressBar;
boolean timerHasStarted = false;

private Queue<Question> questions = new LinkedList<Question>();
private Question active_question;

public void clickhome (View view){
    CustomYesNoDialog cdd = new CustomYesNoDialog(PlayQuizActivity.this);
    cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    cdd.show();
}

@Override
protected void onDestroy() {
    super.onDestroy();
    Timer.cancel();
    setHighScore();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    Log.d("debug", "PlayActivity.onCreate");
    super.onCreate(savedInstanceState);

    //initiate shared prefs
    gamePrefs = getSharedPreferences(GAME_PREFS, 0);

    //Remove title bar
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    //Remove notification bar
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    this.setContentView(R.layout.activity_play_quiz);
    this.scoreText = (TextView)findViewById(R.id.score);

    if(savedInstanceState!=null){
        //saved instance state data
        int exScore = savedInstanceState.getInt("score");
        scoreText.setText("Score: "+exScore);
    }
    //timer 15000 = 15 secs
    Timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            tv_time.setText("" + millisUntilFinished / 1000);
            int progress = (int) (millisUntilFinished / 150);
            progressBar.setProgress(progress);

        }

        @Override
        public void onFinish() {
            progressBar.setProgress(0);
            timeUp(context);

            // Toast t =Toast.makeText(getApplicationContext(), "Out of Time!", Toast.LENGTH_LONG);
            // t.show();
        }
    }.start();
}

}

//Onclick event . In this you will define what will be the outcome if the buttons are being pressed
@Override
public void onClick(View view) {
        Button clicked = (Button) view;
        int exScore = getScore();

    if (clicked.getText().toString().equals(this.active_question.getAnswer()) ) {
        if (this.questions.size() > 0) {
                    setQuestion(questions.poll());
                    progressBar.setProgress(100);
                    scoreText.setText("Score: "+(exScore+1));

            if (!timerHasStarted) {
                        Timer.start();
                        timerHasStarted = true;
                    } else {
                        Timer.start();
                        timerHasStarted = false;
                    }

        } else {
            this.startActivity(new Intent(PlayQuizActivity.this, MoveSecondRandom.class));
            this.finish();
            Timer.cancel();
        }
    } else  {
        CustomGameOver cdd = new CustomGameOver(PlayQuizActivity.this);
        cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        cdd.show();
        setHighScore();
        scoreText.setText("Score: 0");

        Timer.cancel();
    }
}
//method retrieves score
private int getScore(){
    String scoreStr = scoreText.getText().toString();
    return Integer.parseInt(scoreStr.substring(scoreStr.lastIndexOf(" ")+1));
}
private void setHighScore(){
    int exScore = getScore();
    if(exScore>0){
        //we have a valid score
        SharedPreferences.Editor scoreEdit = gamePrefs.edit();
        DateFormat dateForm = new SimpleDateFormat("dd MMMM yyyy");
        String dateOutput = dateForm.format(new Date());
        //get existing scores
        String scores = gamePrefs.getString("highScores", "");
        //check for scores
        if(scores.length()>0){
            //we have existing scores
            List<Score> scoreStrings = new ArrayList<Score>();
            //split scores
            String[] exScores = scores.split("\\|");
            //add score object for each
            for(String eSc : exScores){
                String[] parts = eSc.split(" - ");
                scoreStrings.add(new Score(parts[0], Integer.parseInt(parts[1])));
            }
            //new score
            Score newScore = new Score(dateOutput, exScore);
            scoreStrings.add(newScore);
            //sort
            Collections.sort(scoreStrings);
            //get top ten
            StringBuilder scoreBuild = new StringBuilder("");
            for(int s=0; s<scoreStrings.size(); s++){
                if(s>=10) break;
                if(s>0) scoreBuild.append("|");
                scoreBuild.append(scoreStrings.get(s).getScoreText());
            }
            //write to prefs
            scoreEdit.putString("highScores", scoreBuild.toString());
            scoreEdit.commit();

        }
        else{
            //no existing scores
            scoreEdit.putString("highScores", ""+dateOutput+" - "+exScore);
            scoreEdit.commit();
        }
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    //save score and level
    int exScore = getScore();
    savedInstanceState.putInt("score", exScore);

    //superclass method
    super.onSaveInstanceState(savedInstanceState);
}

PlayQuizActivity中,我不包含所有代码,只包含一些代码。

以下是HighScores的代码:

public class HighScores extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_high);

    //get text view
    TextView scoreView = (TextView)findViewById(R.id.high_scores_list);
    //get shared prefs
    SharedPreferences scorePrefs = getSharedPreferences(PlayQuizActivity.GAME_PREFS, 0);
    //get scores
    String[] savedScores = scorePrefs.getString("highScores", "").split("\\|");
    //build string
    StringBuilder scoreBuild = new StringBuilder("");
    for(String score : savedScores){
        scoreBuild.append(score+"\n");
    }
    //display scores
    scoreView.setText(scoreBuild.toString());
}

}

希望你能帮助我。

0 个答案:

没有答案