public class GameActivity extends AppCompatActivity {
TextView txtTurn, txtScore, txtQuestion, txtQuestionNumber, txtTimer;
Button[] btnAnswers;
Player players[];
ArrayList<Question> questions;
Question currentQuestion;
CountDownTimer gameTime;
Boolean answered, timesup;
int score, turn, round;
final int TIMES = 11000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
txtTurn = (TextView)findViewById(R.id.txtTurnGame);
txtScore = (TextView)findViewById(R.id.txtScoreGame);
txtTimer = (TextView)findViewById(R.id.txtTimer);
txtQuestionNumber = (TextView)findViewById(R.id.questionNumber);
txtQuestion = (TextView)findViewById(R.id.txtQuestion);
btnAnswers = new Button[4];
btnAnswers[0] = (Button)findViewById(R.id.answer1);
btnAnswers[1] = (Button)findViewById(R.id.answer2);
btnAnswers[2] = (Button)findViewById(R.id.answer3);
btnAnswers[3] = (Button)findViewById(R.id.answer4);
answered = false;
timesup = false;
Intent intent = getIntent();
players = MainActivity.players;
turn = intent.getExtras().getInt("turn");
score = players[turn].getScore();
round = intent.getExtras().getInt("round");
questions = MainActivity.shuffledQuestionList;
currentQuestion = questions.get(round/2);
Integer[] randomAnswer = new Integer[4];
for (int i = 0; i < randomAnswer.length; i++) {
randomAnswer[i] = i;
}
Collections.shuffle(Arrays.asList(randomAnswer));
txtTurn.setText(TurnActivity.txtTurn1.getText());
txtScore.setText("Score : " + Integer.toString(score));
txtQuestion.setText(currentQuestion.getQuestion());
txtQuestionNumber.setText("QUESTION #" + Integer.toString(round/2+1));
for (int i = 0; i < randomAnswer.length; i++){
String[] answers = currentQuestion.getAnswersList();
btnAnswers[i].setText(answers[randomAnswer[i]]);
}
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
gameTime.start();
}
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
private void finishTurn(){
gameTime.cancel();
if(round+1 >= 10){
final Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
startActivity(intent);
finish();
}
else {
final Intent intent = new Intent(getApplicationContext(), TurnActivity.class);
new CountDownTimer(2000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//Toast.makeText(getApplicationContext(), "Player2 Time!", Toast.LENGTH_SHORT).show();
intent.putExtra("turn", turn);
intent.putExtra("round", round + 1);
startActivity(intent);
finish();
}
}.start();
}
}
So, I try to make a quiz game. There are 4 buttons as answer choices. When user click a(any) button, it refer to answerChoose method which stops the timer and make an intent to TurnActivity (finishTurn method). The timer displayed as a TextView and of course it stopped, the TextView not changed anymore (seems like the timer stopped)
public void answerChoose(View v){
if(!answered && !timesup){
answered = true;
gameTime.cancel();
Button btnPressed = ((Button) v);
//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
if(btnPressed.getText().equals(currentQuestion.getAnswer())){
btnPressed.setBackgroundColor(Color.GREEN);
players[turn].setScore(score+1);
}
else{
btnPressed.setBackgroundColor(Color.RED);
}
finishTurn();
}
}
But something happen really weird, after reached the TurnActivity, the timer doesn't seem to stop, the timer keeps running until reach the end and make a new intent to TurnActivity (once again). As you can see I called finishTurn method in onFinish method of CountDownTimer. So, the timer itself not stopped even the cancel method declared in answerChoose method.
gameTime = new CountDownTimer(TIMES, 1000){
public void onTick(long millisUntilFinished) {
if(!timesup)
txtTimer.setText("Time : " + millisUntilFinished / 1000 + "s");
}
public void onFinish() {
txtTimer.setText("Time's Up");
timesup = true;
finishTurn();
}
};
Problem solved. All I have to do is override the onStop method.
#Override
protected void onStop() {
super.onStop();
gameTime.cancel();
}
Related
My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
I am making a quiz app when I pressing the answer it was not showing the next question directly it was going to done activity where the score of the quiz will be displayed. Please tell me what to do and the changes i have to made for it. Please tell me in detail and which line the problem causes, because I am still learning, plz And also suggest me some improvements.
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 1000; // 1sec = 1000
final static long TIMEOUT = 7000; // 7000 = 7sec
int progressValue = 0;
CountDownTimer mCountDown;
int index = 0, score = 0, thisQuestion = 0, totalQuestion, correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA, btnB, btnC, btnD;
TextView txtScore, txtQuestionNum, question_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
//View
txtScore = (TextView) findViewById(R.id.txtScore);
txtQuestionNum = (TextView) findViewById(R.id.txtTotalQuestion);
question_text = (TextView) findViewById(R.id.question_text);
question_image = (ImageView) findViewById(R.id.question_image);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnA = (Button) findViewById(R.id.btnAnswerA);
btnB = (Button) findViewById(R.id.btnAnswerB);
btnC = (Button) findViewById(R.id.btnAnswerC);
btnD = (Button) findViewById(R.id.btnAnswerD);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
btnC.setOnClickListener(this);
btnD.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion) //still have question in List
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
//Choose correct answer
score += 10;
correctAnswer++;
showQuestion(++index); //next question
} else {
//Choose wrong answer
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
}
private void showQuestion(int index) {
if (index < totalQuestion) {
thisQuestion++;
txtQuestionNum.setText(String.format(Locale.getDefault(), "%d / %d", thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue = 0;
if (Common.questionList.get(index).getIsImageQuestion().equals("true")) {
//if is image
Picasso.get().load(Common.questionList.get(index).getQuestion()).into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.INVISIBLE);
} else {
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text,we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
btnC.setText(Common.questionList.get(index).getAnswerC());
btnD.setText(Common.questionList.get(index).getAnswerD());
mCountDown.start(); //Start timer
} else {
//If it is final question
Intent intent = new Intent(this, Done.class);
Bundle dataSend = new Bundle();
dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT, INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
There is no onClickListener within your Activity. I would recommend creating a "next()" function, and then, for each of the buttons, do something along the lines of:
btn.setOnClickListener(new View.OnClickListener(){
next()
})
I have made a quiz app and i want to save my options selected for questions and use them in my review activity, but I am not getting how to do that, see if anybody can help....
Here is my Quiz Activity code:
public class NumberSystem1Activity extends AppCompatActivity {
private RadioGroup radioGroup;
private NumberSystem1QuestionBank mNumberSystem1QuestionBank = new NumberSystem1QuestionBank();
private TextView mScoreView;
private TextView times;//For Timer in Quiz
private TextView mQuestionView;
private ImageView mQuestionImageView;
private RadioButton mButtonChoice1;
private RadioButton mButtonChoice2;
private RadioButton mButtonChoice3;
private RadioButton mButtonChoice4;
private String mAnswer;
private int mScore = 0;
private int mQuestionNumber = 0;
private int count_correct_answer =0;
private int count_wrong_answer=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testactivity1);
radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.clearCheck();
mScoreView = (TextView) findViewById(R.id.score);
mQuestionImageView = (ImageView)findViewById(R.id.image);
mQuestionView = (TextView) findViewById(R.id.question);
mButtonChoice1 = (RadioButton) findViewById(R.id.choice1);
mButtonChoice2 = (RadioButton) findViewById(R.id.choice2);
mButtonChoice3 = (RadioButton) findViewById(R.id.choice3);
mButtonChoice4 = (RadioButton) findViewById(R.id.choice4);
final Button go = (Button) findViewById(R.id.button2);
updateQuestion();
// Set the timer for Quiz
times = (TextView) findViewById(R.id.timers);
// method which will set the things up for our game
times.setText("00:02:00");
// A timer of 20 minutes to play for, with an interval of 1 second (1000 milliseconds)
NumberSystem1Activity.CounterClass timer = new NumberSystem1Activity.CounterClass(30000, 1000);
timer.start();
//Code Ends here
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mButtonChoice1.isChecked()) {
if (mButtonChoice1.getText() == mAnswer) {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = mScore + 3;
updateScore(mScore);
count_correct_answer++;
mButtonChoice1.setBackgroundColor(Color.GREEN);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Correct Answer", Toast.LENGTH_SHORT).show();
}
else {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = (mScore - 1);
count_wrong_answer++;
updateScore(mScore);
mButtonChoice1.setBackgroundColor(Color.RED);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Wrong Answer", Toast.LENGTH_SHORT).show();
}
} else if (mButtonChoice2.isChecked()) {
if (mButtonChoice2.getText() == mAnswer) {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = mScore + 3;
updateScore(mScore);
count_correct_answer++;
mButtonChoice2.setBackgroundColor(Color.GREEN);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Correct Answer", Toast.LENGTH_SHORT).show();
}
else {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = (mScore - 1);
count_wrong_answer++;
updateScore(mScore);
mButtonChoice2.setBackgroundColor(Color.RED);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Wrong Answer", Toast.LENGTH_SHORT).show();
}
} else if (mButtonChoice3.isChecked()) {
if (mButtonChoice3.getText() == mAnswer) {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = mScore + 3;
updateScore(mScore);
count_correct_answer++;
mButtonChoice3.setBackgroundColor(Color.GREEN);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Correct Answer", Toast.LENGTH_SHORT).show();
}
else {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = (mScore - 1);
count_wrong_answer++;
updateScore(mScore);
mButtonChoice3.setBackgroundColor(Color.RED);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Wrong Answer", Toast.LENGTH_SHORT).show();
}
} else if (mButtonChoice4.isChecked()) {
if (mButtonChoice4.getText() == mAnswer) {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = mScore + 3;
updateScore(mScore);
count_correct_answer++;
mButtonChoice4.setBackgroundColor(Color.GREEN);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Correct Answer", Toast.LENGTH_SHORT).show();
}
else {
//Post Question Delay Code
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
//Code Ends hers
updateQuestion();
}
};
handle.postDelayed(delay, 2000);
mScore = (mScore - 1);
count_wrong_answer++;
updateScore(mScore);
mButtonChoice4.setBackgroundColor(Color.RED);
//This line of code is optional
Toast.makeText(NumberSystem1Activity.this, "Wrong Answer", Toast.LENGTH_SHORT).show();
}
}
}
});
}
public void onClear(View v) {
/* Clears all selected radio buttons to default */
radioGroup.clearCheck();
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
Intent intent = new Intent(NumberSystem1Activity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("mScore", + mScore); // Your score
intent.putExtras(b); // Put your score to your next
Bundle c = new Bundle();
c.putInt("count_correct_answer", + count_correct_answer); // Your score
intent.putExtras(c); // Put your Correct Answer score to your next
Bundle d = new Bundle();
d.putInt("count_wrong_answer", + count_wrong_answer); // Your score
intent.putExtras(d); // Put your Wrong Answer score to your next
startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void updateQuestion(){
if (mQuestionNumber< 30) {
// if questions are not over then do this
mQuestionView.setText(mNumberSystem1QuestionBank.getQuestion(mQuestionNumber));
mQuestionImageView.setImageResource(mNumberSystem1QuestionBank.getQuestionImages(mQuestionNumber));
mButtonChoice1.setText(mNumberSystem1QuestionBank.getChoice1(mQuestionNumber));
mButtonChoice2.setText(mNumberSystem1QuestionBank.getChoice2(mQuestionNumber));
mButtonChoice3.setText(mNumberSystem1QuestionBank.getChoice3(mQuestionNumber));
mButtonChoice4.setText(mNumberSystem1QuestionBank.getChoice4(mQuestionNumber));
mAnswer = mNumberSystem1QuestionBank.getCorrectAnswer(mQuestionNumber);
radioGroup.clearCheck();
mQuestionNumber++;
//set all buttons Blue for next question
mButtonChoice1.setBackgroundResource(R.color.blue_light);
mButtonChoice2.setBackgroundResource(R.color.blue_dark);
mButtonChoice3.setBackgroundResource(R.color.blue_light);
mButtonChoice4.setBackgroundResource(R.color.blue_dark);
}
else {
// if over do this
Intent intent = new Intent(NumberSystem1Activity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("mScore", mScore); // Your score
intent.putExtras(b); // Put your score to your next
Bundle c = new Bundle();
c.putInt("count_correct_answer", + count_correct_answer); // Your score
intent.putExtras(c); // Put your Correct Answer score to your next
Bundle d = new Bundle();
d.putInt("count_wrong_answer", + count_wrong_answer); // Your score
intent.putExtras(d); // Put your Wrong Answer score to your next
startActivity(intent);
finish();
}
}
private void updateScore(int point){
mScoreView.setText("" + mScore);
}
Here is my Review Activity code:
public class ReviewActivity1 extends AppCompatActivity {
private NumberSystem1QuestionBank mNumberSystem1QuestionBank = new NumberSystem1QuestionBank();
private TextView mQuestionView;
private ImageView mQuestionImageView;
private TextView mExplanationView;
private ImageView mExplanationImageView;
private TextView mCorrectAnswer;
private int mQuestionNumber = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_review);
mQuestionView = (TextView) findViewById(R.id.question);
mQuestionImageView = (ImageView)findViewById(R.id.image);
mExplanationView = (TextView) findViewById(R.id.ExplanationText);
mExplanationImageView = (ImageView)findViewById(R.id.photo);
mCorrectAnswer = (TextView) findViewById(R.id.CorrectAnswerText);
final Button pre = (Button) findViewById(R.id.previous);
final Button next = (Button) findViewById(R.id.next);
updateQuestion();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mQuestionNumber<30){
mQuestionNumber++;
updateQuestion();
}
else {
Intent intent = new Intent(ReviewActivity1.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
//if you want to disable the back button on the first question
pre.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mQuestionNumber>0) {
mQuestionNumber--;
updateQuestion();
} else {
Toast.makeText(ReviewActivity1.this, "This is the First Question. No Previous One.", Toast.LENGTH_SHORT).show();
// you're at the first question => no previous one
}
}
});
}
private void updateQuestion() {
if (mQuestionNumber < 30) {
// if questions are not over then do this
mQuestionView.setText(mNumberSystem1QuestionBank.getQuestion(mQuestionNumber));
mQuestionImageView.setImageResource(mNumberSystem1QuestionBank.getQuestionImages(mQuestionNumber));
mExplanationView.setText(mNumberSystem1QuestionBank.getExplanations(mQuestionNumber));
mExplanationImageView.setImageResource(mNumberSystem1QuestionBank.getExplanationImages(mQuestionNumber));
mCorrectAnswer.setText(mNumberSystem1QuestionBank.getCorrectAnswer(mQuestionNumber));
} else {
Intent intent = new Intent(ReviewActivity1.this, MainActivity.class);
startActivity(intent);
finish();
}
}
#Override
public void onBackPressed(){
//Exit The Quiz Alert Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(ReviewActivity1.this);
builder.setMessage("Do you want to Exit the Review." );
builder.setCancelable(true);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(ReviewActivity1.this, MainActivity.class);
startActivity(intent);
Toast.makeText(ReviewActivity1.this, "Test Page Appeared.", Toast.LENGTH_SHORT).show();
finish();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
I have a 20 second countdown timer successfully working on my trivia game. I want to add a ProgressBar (not a ProgressDialog) to the screen. I found the developer guide for Android confusing. I googled lots of examples and tried to combine them into my code. Right now all that displays when I run a game is an empty bar with no "progress" made during each question of the game.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 20000;
long interval = 1000;
long points;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, pointCounter, questionNumber, timeCounter;
ArrayList<Question> queries;
Timer cdTimer;
ProgressBar bar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
pointCounter = (TextView)findViewById(R.id.timer);
questionNumber = (TextView)findViewById(R.id.timeElapsedView);
timeCounter = (TextView)findViewById(R.id.timeCounter);
cdTimer = new Timer(startTime, interval);
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false);
bar.setMax(9);
loadQuestion();
}
public void loadQuestion() {
bar.setProgress(i);
if(i == 10) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.start();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(1);
if(answer == 1) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(2);
if(answer == 2) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(3);
if(answer == 3) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
}
}
public ArrayList<Question> getQueries() {
return queries;
}
public void nextQuestion() {
score = score + points;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public void startCountdownTimer() {
}
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i >= 9) {
cdTimer.cancel();
endQuiz();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timeCounter.setText("Time remaining: " + (millisUntilFinished / 100));
points = (millisUntilFinished / 100) / 2;
pointCounter.setText("Points remaining: " + points);
if(i < 10) {
questionNumber.setText("Question " + (i + 1) + " of 10");
}
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
XML code
<ProgressBar
android:id="#+id/progressbar"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:visibility="visible"
style="#android:style/Widget.ProgressBar.Horizontal" />
What I am looking for is for the ProgressBar to slowly tick down until the 20 seconds the user is allotted for each question is gone.
New Answer
To do this let's add a new line to onTick():
bar.setProgress((int) Math.round(millisUntilFinished / 1000.0));
(You may need to tweak the data types, I am away from my compiler... Also I don't like the CountDownTimer class, it is inaccurate and often skips the second to last number. I wrote an alternate class here: android CountDownTimer - additional milliseconds delay between ticks)
Original Answer
I have a couple pointers:
Have you defined a maximum value for your ProgressBar?
bar.setMax(9);
I suggest loading i as the progress instead of the constant value of 10:
bar.setProgress(i);
If you still do not see any progress ensure that you are not in indeterminate mode:
bar.setIndeterminate(false);
(This assume that you are using a ProgressBar that can depict progress.)
Addition
Move this code into onCreate():
bar = (ProgressBar)findViewById(R.id.progressbar);
bar.setIndeterminate(false); // May not be necessary
bar.setMax(9);
Then move this line to loadQuestion():
bar.setProgress(i);
Otherwise the progress will never be updated since you only create one CountDownTimer and you never actually call startCountdownTimer().
I have a trivia game of 10 questions with a 10 second timer for each question. When the timer runs out, the question changes to the next but the timer never restarts. It stays at 0. I cannot seem to find where in code that keeps the timer from restarting when the next question is displayed.
Also, code structure suggestions is appreciated!
Thank you in advance.
QuestionView.java
public class QuestionView extends Activity {
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i = 0;
long score = 0;
long startTime = 10000;
long interval = 1000;
long timeElapsed;
boolean timerHasStarted = false;
String category;
Button answer1, answer2, answer3, answer4;
TextView question, timer, timeElapsedView;
ArrayList<Question> queries;
Timer cdTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
category = getIntent().getStringExtra("category");
queries = getIntent().getParcelableArrayListExtra("queries");
timer = (TextView)findViewById(R.id.timer);
timeElapsedView = (TextView)findViewById(R.id.timeElapsedView);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.cancel();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//Same code for button 1 for buttons 2 through 4.
}
}
public void nextQuestion() {
score = score + ((startTime / 100) - timeElapsed);
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
if(i == 9) {
cdTimer.cancel();
} else {
wrongAnswers++;
nextQuestion();
}
}
#Override
public void onTick(long millisUntilFinished) {
timer.setText("Time remaining: " + (millisUntilFinished / 100));
timeElapsed = 100 - ((startTime - millisUntilFinished) / 100);
timeElapsedView.setText("Points remaining: " + timeElapsed);
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
intent.putExtra("category", category);
startActivity(intent);
}
}
try the following and see if it helps. furthermore, calling cancel() inside the timer's own onFinish() method is unneeded since the timer would have already been cancelled to reach that method.
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
cdTimer.start(); //start timer here
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
cdTimer.cancel(); // end it when clicked.
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//Same code for button 1 for buttons 2 through 4.
}
}