ProgressBar with a countdowntimer - Android - java

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().

Related

preventing a user from entering multiple answer

i create a true/false quiz app. in that app i have 4 buttons i.e True,False,previous(to get back to previous question),next(to get the next question). i want to add a functionality when a user click on true or false button its get disable for that question so the user can click only once for one question.
i tried to disable the button by using button.setEnabled(false) but when i click on previous button or next button the true/false buttons enabled.i want that the user can click the answer only once it does not matter how much the user traverse the question.
i try to call the setEnabledButton() in previous on click button but it disable the button but it also disable whether the user click on answer or not.
Button btrue,bfalse,bnext,bprevious;
TextView tquestion;
int mCurrentIndex=0;
Questions[] questionbank;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btrue=findViewById(R.id.true_button);
bfalse=findViewById(R.id.false_button);
bnext=findViewById(R.id.next_button);
tquestion=findViewById(R.id.question_text);
bprevious=findViewById(R.id.previous_button);
questionbank = new Questions[]
{
new Questions(R.string.greater,false),
new Questions(R.string.Pm,true),
new Questions(R.string.capital,true),
new Questions(R.string.china,false),
new Questions(R.string.Richer,false),
new Questions(R.string.company,true),
new Questions(R.string.company1,false),
};
update();
bnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int s=questionbank.length;
if( mCurrentIndex<=s )
{
if (mCurrentIndex + 1 < questionbank.length) {
mCurrentIndex++;
}
else
{ Toast.makeText(getApplicationContext(),"not more question",Toast.LENGTH_SHORT).show();
}
update();
}
}
});
btrue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(true);
}
});
bfalse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(false);
}
});
bprevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mCurrentIndex > 0) {
mCurrentIndex = (mCurrentIndex - 1);
update();
}
else
{ Toast.makeText(getApplicationContext(), "cant go back", Toast.LENGTH_SHORT).show(); }
}
});
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
setButtonEnabled(true);
}
private void checkAnswer(boolean userPressedTrue)
{
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
private void setButtonEnabled(boolean enabled) {
btrue.setEnabled(enabled);
bfalse.setEnabled(enabled);
}
}
In Questions class you can create a method,
public class Questions {
boolean isQuestionAnswered;
public boolean isQuestionAnswered() {
return isQuestionAnswered;
}
public void setQuestionAnswered(boolean questionAnswered) {
isQuestionAnswered = questionAnswered;
}
}
private void checkAnswer(boolean userPressedTrue)
{
questionbank[mCurrentIndex].setQuestionAnswered(true);
boolean answerIsTrue =
questionbank[mCurrentIndex].ismTrueAnswer();
int messageResId = 0;
if (userPressedTrue == answerIsTrue) {
setButtonEnabled(false);
messageResId = R.string.correct_toast;
} else {
setButtonEnabled(false);
messageResId = R.string.incorrect_toast;
}
Toast.makeText(this, messageResId,
Toast.LENGTH_SHORT)
.show();
}
public void update()
{
int ques = questionbank[mCurrentIndex].getmTextResid();
tquestion.setText(ques);
if(questionbank[mCurrentIndex].isQuestionAnswered())
setButtonEnabled(false);
else
setButtonEnabled(true);
}
Try this out and check whether this solves your problem

How to loop in Java and Android Studio

I have made an alarm clock app however, I am trying to make a homepage where the user can see all the alarms they have set. I want to infinitely run a block of code that updates the homepage of my app, but the methods I have found have not worked (i.e using a timer loop, while, and for loop). Any suggestion would help me a lot, also any critique to the code would help to, Thanks everyone!
I have tried
Timers, Do-While, While, and For Loops
The While loop that is in there currently cause an error and the app does not even run.
All the code I need help with is in the While Loop.
I think this is the error
(I/zygote64: Rejecting re-init on previously-failed classjava.lang.Class: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/view/View$OnUnhandledKeyEventListener;)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarms);
final Button selectAlarm1 = (Button) findViewById(R.id.selectAlarm1);
final Button selectAlarm2 = (Button) findViewById(R.id.selectAlarm2);
final Button selectAlarm3 = (Button) findViewById(R.id.selectAlarm2);
selectAlarm1.setVisibility(View.INVISIBLE);
selectAlarm2.setVisibility(View.INVISIBLE);
selectAlarm3.setVisibility(View.INVISIBLE);
final TextView textView = (TextView) findViewById(R.id.textView);
final Button createAlarm = (Button) findViewById(R.id.createAlarm);
final Button createAlarm2 = (Button) findViewById(R.id.createAlarm2);
final Button createAlarm3 = (Button) findViewById(R.id.createAlarm3);
createAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
createAlarm2.bringToFront();
}
});
createAlarm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity2();
createAlarm3.bringToFront();
}
});
createAlarm3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMain3Activity();
}
});
selectAlarm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity();
}
});
selectAlarm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMainActivity2();
}
});
selectAlarm3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openMain3Activity();
}
});
while(true){
if (Global.intHour1 != 0 && Global.intMinute1 != 0) {
textView.setVisibility(View.GONE);
selectAlarm1.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute1 <= 9) {
selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":0" + Global.intMinute1);
} else {
selectAlarm1.setText("Alarm 1 is set for " +
Global.intHour1 + ":" + Global.intMinute1);
}
} else if (Global.intHour1 == 0 && Global.intMinute1 == 0) {
textView.setVisibility(View.VISIBLE);
}
if (Global.intHour2 != 0 && Global.intMinute2 != 0) {
selectAlarm2.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute2 <= 9) {
selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":0" + Global.intMinute2);
} else {
selectAlarm2.setText("Alarm 1 is set for " +
Global.intHour2 + ":" + Global.intMinute2);
}
} else {
}
if (Global.intHour3 != 0 && Global.intMinute3 != 0) {
selectAlarm3.setVisibility(View.VISIBLE);
//fixing minute format
if (Global.intMinute3 <= 9) {
selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":0" + Global.intMinute3);
} else {
selectAlarm3.setText("Alarm 1 is set for " +
Global.intHour3 + ":" + Global.intMinute3);
}
}
else {
}
if (selectAlarm1.getVisibility() == View.INVISIBLE &&
selectAlarm2.getVisibility() == View.INVISIBLE &&
selectAlarm3.getVisibility() == View.INVISIBLE) {
textView.setVisibility(View.VISIBLE);
}
else
{
}
}
}
public void openMainActivity () {
Intent openAlarm = new Intent(this, MainActivity.class);
startActivity(openAlarm);
}
public void openMainActivity2 () {
Intent openAlarm2 = new Intent(this, MainActivity2.class);
startActivity(openAlarm2);
}
public void openMain3Activity () {
Intent openAlarm3 = new Intent(this, Main3Activity.class);
startActivity(openAlarm3);
}
public void makeTextVisible () {
}
}
I want the code to recognize when the intHour1-3 and intMinute1-3 are changed and change the visibility state of a button so that when the user returns to the homepage they can see which alarms are set.

CountDownTimer keep running even declared cancel()

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();
}

Timer class not restarting timer - Android

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.
}
}

Not looping through for loop - Java (android)

The program works and comes up. When I click start on the main menu it brings up a question (textview) and 4 answers (buttons). Text is assigned to the textview and the 4 buttons with the for-loop. It is never looping through after clicking a button. Nothing happens when clicking a button.
I have tried putting in a "break" and changing to a while loop and just can't get it working. I think this is a simple fix that I just cannot find.
Any other code structure or advice is appreciated and needed!
public class QuestionView extends Activity {
Quiz quiz = new Quiz();
ArrayList<Question> queries = quiz.getRandom10();
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
TextView question = (TextView)findViewById(R.id.question);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
Button answer3 = (Button)findViewById(R.id.answer3);
Button answer4 = (Button)findViewById(R.id.answer4);
for(int i = 0; i < 10; i++) {
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());
answer = queries.get(i).getCorrectAnswer();
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 0) {
correctAnswers++;
} else {
wrongAnswers++;
}
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 1) {
correctAnswers++;
} else {
wrongAnswers++;
}
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 2) {
correctAnswers++;
} else {
wrongAnswers++;
}
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 3) {
correctAnswers++;
} else {
wrongAnswers++;
}
}
});
}
}
}
The onCreate method is running only when the Activity is created. What you want to do is break out the following code into a separate method and call that method from the onClickLiestener() for the different buttons:
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());
Since this solution wouldn't include a loop, you would have to make sure that the index (in this case 'i') is increased for every click.
EDIT: Suggested solution
public class QuestionView extends Activity {
Quiz quiz = new Quiz();
ArrayList<Question> queries = quiz.getRandom10();
int correctAnswers = 0;
int wrongAnswers = 0;
int answer = 0;
int i=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
Button answer3 = (Button)findViewById(R.id.answer3);
Button answer4 = (Button)findViewById(R.id.answer4);
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 0) {
correctAnswers++;
} else {
wrongAnswers++;
}
reloadQuestion();
}
});
answer2.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 1) {
correctAnswers++;
} else {
wrongAnswers++;
}
reloadQuestion();
}
});
answer3.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 2) {
correctAnswers++;
} else {
wrongAnswers++;
}
reloadQuestion();
}
});
answer4.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if(answer == 3) {
correctAnswers++;
} else {
wrongAnswers++;
}
reloadQuestion();
}
});
reloadQuestion();
}
private void reloadQuestion(){
TextView question = (TextView)findViewById(R.id.question);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
Button answer3 = (Button)findViewById(R.id.answer3);
Button answer4 = (Button)findViewById(R.id.answer4);
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());
answer = queries.get(i).getCorrectAnswer();
i++;
}
}
You could probably optimize the code in different ways, but this suggestion should solve your problem.
What your program does is just ten times assign different texts from "queries" ArrayList to the bunch of TextView objects. Also it assigns the same onClickListener objects to the same textView objects over and over again. And it all happens when the activity is created. So at the moment when you are actually able to see your activity, the loop is over and all the textView items have the last (10th) values.
When you click the button, the program does exactly what you have asked it to do: increases one of the counters.
I believe this is not what you have in your mind. And what you really want to do is:
Make only one onClickListener object and assign it in the onCreate() method to all your textView items.
Inside the onClickListener check the view that was clicked (determine which textVIew was clicked) and compare it with the correct answer. Update counters accordingly. Read next set of question-answer data and update the UI.
Here is an example of what I am talking about:
public class QuestionView extends Activity {
Quiz quiz = new Quiz();
ArrayList<Question> queries = quiz.getRandom10();
private int correctAnswers;
private int wrongAnswers;
private char mCurrentAnswer;
private char mNextQuestion;
private View.OnClickListener clickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v.getId() == getCurrentAnswer()) {
++correctAnswers;
} else {
++wrongAnswers;
}
readNextQuestion();
}
};
private int getCurrentAnswer() {
return mCurrentAnswer;
}
private void readNextQuestion() {
question.setText(queries.get(mNextQuestion).getQuery());
answer1.setText(queries.get(mNextQuestion).getA1());
answer2.setText(queries.get(mNextQuestion).getA2());
answer3.setText(queries.get(mNextQuestion).getA3());
answer4.setText(queries.get(mNextQuestion).getA4());
mCurrentAnswer = queries.get(mNextQuestion).getCorrectAnswer();
++mNextQuestion;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
TextView question = (TextView)findViewById(R.id.question);
Button answer1 = (Button)findViewById(R.id.answer1);
Button answer2 = (Button)findViewById(R.id.answer2);
Button answer3 = (Button)findViewById(R.id.answer3);
Button answer4 = (Button)findViewById(R.id.answer4);
//You can also assign it in the xml (I guess)
answer1.setId(1);
answer1.setOnClickListener(clickListener);
answer2.setId(2);
answer2.setOnClickListener(clickListener);
answer3.setId(3);
answer3.setOnClickListener(clickListener);
answer4.setId(4);
answer4.setOnClickListener(clickListener);
readNextQuestion();
}
}

Categories

Resources