Я пытаюсь сделать мини-игру, как викторину. Если вы ответите правильно в указанное время c, ваш счет будет сохранен в sqlite db (если он выше, чем рекорд). В противном случае, если время истечет, появится диалоговое окно и сообщит, что время истекло. Проблема в том, что приложение вылетает, потому что время загрузки никогда не закрывается. Каким-то образом он работает в фоновом режиме и: 1. если я нахожусь в другом действии, приложение cra sh, потому что диалоговое окно не открыто в указанном действии (действие levelQuizOne) 2. Если я нахожусь в середине теста, диалоговое окно появляется, даже если время еще не истекло (поэтому я полагаю, что это последний таймер обратного отсчета, который активирует метод onFini sh ()).
Пожалуйста, помогите, если у вас есть идеи, я новичок в области программирования Android. Спасибо
public void onBackPressed() {
final AlertDialog.Builder builder = new AlertDialog.Builder(LevelQuizOneActivity.this);
builder.setMessage("Ești sigur că vrei să renunți? Tot progresul tău se va pierde");
builder.setPositiveButton("DA", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
timeRemaining = 0;
if(countDownTimer != null)
countDownTimer.cancel();
Intent intent1 = new Intent(LevelQuizOneActivity.this, LevelListActivity.class);
startActivity(intent1);
}
});
builder.setNegativeButton("NU", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setTitle("Renunț");
alertDialog.show();
}
Здесь я получаю вопросы из БД, запускаю тест и начинаю обратный отсчет
questionCountTotal = questionQuizOneList_levelOne.size();
Collections.shuffle(questionQuizOneList_levelOne); //amestecam interbarile inter ele ca sa nu fie mereu aceleasi
Collections.shuffle(answersList_levelOne);
showNextQuestion_levelOne();
startCountdown();
btn_next.setVisibility(View.GONE);
txt_op1.setClickable(true);
txt_op2.setClickable(true);
txt_op3.setClickable(true);
txt_op4.setClickable(true);
checkAnswers_levelOne();
btn_next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showNextQuestion_levelOne();
timeRemaining = 0;
countDownTimer.cancel();
}
});
private void showNextQuestion_levelOne() {
timeRemaining = COUNTDOWN_IN_MILLIS_LEVEL_ONE_QUIZ_ONE;
startCountdown();
updateCountdownText();
txt_op1.setClickable(true);
txt_op2.setClickable(true);
txt_op3.setClickable(true);
txt_op4.setClickable(true);
btn_next.setVisibility(View.VISIBLE);
img_answer.setAlpha(0f);
ArrayList<String> posibleAnswers = new ArrayList<>();
if (questionCounter < questionCountTotal) {
btn_next.setVisibility(View.GONE);
currentQuestion = questionQuizOneList_levelOne.get(questionCounter);
ArrayList<String> list = new ArrayList<>();
for (Answers item : answersList_levelOne) {
list.add(item.getText_raspuns());
}
list.remove(questionQuizOneList_levelOne.get(questionCounter).getCod_raspuns_corect());
posibleAnswers.add(list.get(0));
posibleAnswers.add(list.get(1));
posibleAnswers.add(list.get(2));
posibleAnswers.add(questionQuizOneList_levelOne.get(questionCounter).getCod_raspuns_corect());
Collections.shuffle(posibleAnswers);
if(currentQuestion.getDrawable_res().equals("o")){
img_quizHiragana.setImageResource(LevelQuizOneActivity.this.getResources().getIdentifier
(currentQuestion.getDrawable_res(), "drawable", LevelQuizOneActivity.this.getPackageName()));
} else if(currentQuestion.getDrawable_res().equals("i")){
img_quizHiragana.setImageResource(LevelQuizOneActivity.this.getResources().getIdentifier
(currentQuestion.getDrawable_res(), "drawable", LevelQuizOneActivity.this.getPackageName()));
} else
img_quizHiragana.setImageResource(LevelQuizOneActivity.this.getResources().getIdentifier
(currentQuestion.getDrawable_res() + "1", "drawable", LevelQuizOneActivity.this.getPackageName()));
txt_op1.setText(posibleAnswers.get(0));
txt_op2.setText(posibleAnswers.get(1));
txt_op3.setText(posibleAnswers.get(2));
txt_op4.setText(posibleAnswers.get(3));
questionCounter++;
txt_questionCount.setText("Întrebare: " + questionCounter + "/" + questionCountTotal);
} else {
finishQuiz();
}
}
private void startCountdown() {
countDownTimer = new CountDownTimer(timeRemaining, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeRemaining = millisUntilFinished;
updateCountdownText();
}
@Override
public void onFinish() {
//COUNTDOWN_IN_MILLIS_LEVEL_ONE_QUIZ_ONE = 0;
//timeRemaining = 0;
//finishQuiz();
final AlertDialog.Builder builder = new AlertDialog.Builder(LevelQuizOneActivity.this);
builder.setMessage("!!!!!!!!!!!!!!!!!!!!!!!!");
builder.setPositiveButton("!!!!!!!!!!!!!!", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
timeRemaining = 0;
if(countDownTimer != null)
countDownTimer.cancel();
Intent intent1 = new Intent(LevelQuizOneActivity.this, LevelListActivity.class);
startActivity(intent1);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.setTitle("!!!!!!!!!!!!!!!");
alertDialog.show();
}
};
countDownTimer.start();
}
private void updateCountdownText(){
int minutes = (int)(timeRemaining / 1000) / 60;
int seconds = (int) (timeRemaining / 1000) % 60;
String timeFormated = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
txt_time.setText(timeFormated);
if(timeRemaining < 10000) {
txt_time.setTextColor(Color.YELLOW);
} else {
txt_time.setTextColor(txtColor);
}
}
private void finishQuiz(){
int id;
if(LevelListActivity.level_type.equals("level1") && GameActivity.quiz_type.equals("quiz1")) {
int scoreDB = dbHelper.getScore(1, 1);
if (btn_next.getText().equals("Finish")) {
if (score > scoreDB) {
id = dbHelper.getScoreID(1, 1);
Score s = new Score(1, 1, score);
dbHelper.updateScore(s, String.valueOf(id));
}
}
timeRemaining = 0;
countDownTimer.cancel();
Intent intent = new Intent(LevelQuizOneActivity.this, LevelListActivity.class);
startActivity(intent);
}
}
private void checkAnswers_levelOne() {
txt_op1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn_next.setVisibility(View.VISIBLE);
if (txt_op1.getText().toString().equals(currentQuestion.getCod_raspuns_corect())) {
img_answer.setImageResource(R.drawable.correct);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
score += 10;
txt_score.setText("Punctaj: " + score);
} else {
img_answer.setImageResource(R.drawable.incorrect);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
}
showSolution();
}
});
txt_op2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn_next.setVisibility(View.VISIBLE);
if (txt_op2.getText().toString().equals(currentQuestion.getCod_raspuns_corect())) {
img_answer.setImageResource(R.drawable.correct);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
//
score += 10;
txt_score.setText("Punctaj: " + score);
} else {
img_answer.setImageResource(R.drawable.incorrect);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
}
showSolution();
}
});
txt_op3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn_next.setVisibility(View.VISIBLE);
if (txt_op3.getText().toString().equals(currentQuestion.getCod_raspuns_corect())) {
img_answer.setImageResource(R.drawable.correct);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
//
score += 10;
txt_score.setText("Punctaj: " + score);
} else {
img_answer.setImageResource(R.drawable.incorrect);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
}
showSolution();
}
});
txt_op4.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btn_next.setVisibility(View.VISIBLE);
if (txt_op4.getText().toString().equals(currentQuestion.getCod_raspuns_corect())) {
img_answer.setImageResource(R.drawable.correct);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
//
score += 10;
txt_score.setText("Punctaj: " + score);
} else {
img_answer.setImageResource(R.drawable.incorrect);
img_answer.setAlpha(1f);
txt_op1.setClickable(false);
txt_op2.setClickable(false);
txt_op3.setClickable(false);
txt_op4.setClickable(false);
}
showSolution();
}
});
}