0

I have a simple quiz app and I want to save the high score automatically and load it automatically in the onCreate() method. I have seen other questions on stack overflow as well but they load it using a button. the integer i want to save is mHighScore here is the code

package com.kurddevelopers.quizApp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Random;

public class MainActivity extends Activity {

// TODO: Declare member variables here:
int mIndex;
ProgressBar progressBar;
TextView textView;
TextView tvScore;
TextView tvHighScore;
Button btnFalse;
Button btnTrue;
Random randomGenerator;
TrueFalse trueFalse;
int question;
int mScore;
int mHighScore;
// TODO: Uncomment to create question bank
private TrueFalse[] mQuestionBank = new TrueFalse[] {
        new TrueFalse(R.string.question_1, true),
        new TrueFalse(R.string.question_2, true),
        new TrueFalse(R.string.question_3, true),
        new TrueFalse(R.string.question_4, true),
        new TrueFalse(R.string.question_5, true),
        new TrueFalse(R.string.question_6, false),
        new TrueFalse(R.string.question_7, true),
        new TrueFalse(R.string.question_8, false),
        new TrueFalse(R.string.question_9, true),
        new TrueFalse(R.string.question_10, true),
        new TrueFalse(R.string.question_11, false),
        new TrueFalse(R.string.question_12, false),
        new TrueFalse(R.string.question_13,true)
};
// TODO: Declare constants here
final int PROGRESS_BAR_INCREAMENT =(int) Math.ceil(100.0 / mQuestionBank.length);


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

    progressBar = (ProgressBar)findViewById(R.id.progress_bar);
    btnFalse = (Button)findViewById(R.id.false_button);
    btnTrue = (Button)findViewById(R.id.true_button);

    tvScore = (TextView)findViewById(R.id.score);
    tvHighScore = (TextView)findViewById(R.id.textView);
    textView = (TextView)findViewById(R.id.question_text_view);

    randomGenerator = new Random();
    trueFalse = new TrueFalse(R.string.question_1, true);

    question = mQuestionBank[mIndex].getQuestion();
    textView.setText(question);

    // click Listeners
    btnFalse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(false);
            updateQuestion();
        }
    });
    btnTrue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            checkAnswer(true);
            updateQuestion();
        }
    });


}
public  void updateQuestion(){
    mIndex = (mIndex + 1) % mQuestionBank.length;
    question = mQuestionBank[mIndex].getQuestion();
    textView.setText(question);
    progressBar.incrementProgressBy(PROGRESS_BAR_INCREAMENT);
    if (mIndex == 0){
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.setTitle("یاریەکە تەواو بوو !");
        alert.setCancelable(false);
        alert.setMessage("توانیت " + mScore +"خاڵ بەدەست بێنیت ");
        alert.setPositiveButton("دەرچوون", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alert.show();
    }

}
private void checkAnswer(boolean userSelection){
    boolean correctAnswer = mQuestionBank[mIndex].isTrueOrfalse();
    if (userSelection == correctAnswer){
        Toast.makeText(this,R.string.correct_toast,Toast.LENGTH_SHORT).show();
        mScore++;
        tvScore.setText(mScore + " /13");
    }else{
        Toast.makeText(this,R.string.incorrect_toast,Toast.LENGTH_SHORT).show();
    }
    if (mScore > mHighScore){
        tvHighScore.setText("بەرزترین خاڵ : " + mScore);
    }else if (mScore < mHighScore){
        tvHighScore.setText(mHighScore);
    }
    readFile();
    saveFile();

}

private void saveFile(){
    int highScoreTextView = mHighScore;
    SharedPreferences sharedPref = getSharedPreferences("MY_FILE", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("HIGH SCORE = ", highScoreTextView);
    editor.commit();
    Toast.makeText(this,"SAVED",Toast.LENGTH_SHORT).show();

}
private void readFile(){
    SharedPreferences sharedPref = getSharedPreferences("MY_FILE", Activity.MODE_PRIVATE);
    int name = sharedPref.getInt("name", -1 );
    tvHighScore.setText("بەرزترین خاڵ :"+ name);
}

}

  • I am having trouble with the saveFile() and readFile().
litelite
  • 2,857
  • 4
  • 23
  • 33

2 Answers2

0

Use sharedPreferences like this

SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_WORLD_WRITEABLE); 
Editor editor = pref.edit();
Editor editor = sharedpreferences.edit();
editor.putString("highschore", value);
editor.commit();
phpdroid
  • 1,642
  • 1
  • 18
  • 36
0

Inside your onCreate() method just call your readFile() method somewhere (make sure you call it after you initialise your tvHighScore).

Override onDestroy() method inside your Activity class and call your saveFile() method inside it:

@Override
protected void onDestroy() {
    super.onDestroy();
    saveFile();
}

Since onDestroy() is called when your Activity is destroyed, your saveFile() will be called there and you don't need any buttons for that.

Sergey Emeliyanov
  • 5,158
  • 6
  • 29
  • 52
  • onDestroy() method is not always called unless you call finish(). Here is a [link](https://stackoverflow.com/questions/4449955/activity-ondestroy-never-called) or you can try it yourself. It's not right thing to do call essential methods inside onDestroy(). That's why all registering/unregistering or adding removing stuff happens in onStart() and onStop(). – Thracian Sep 20 '17 at 18:04
  • You're right, but in this particular case it does not matter. You see, the onDestroy() might not get called. It is not a problem, since onCreate() method will not be called by any chance unless the activity was destroyed and onDestroy() method was called. – Sergey Emeliyanov Sep 20 '17 at 18:09
  • when i call my read file in the onCreate the app crashes. I called it after tvHighScore . – iTs iCreazYY Sep 20 '17 at 21:46