Not looping through for loop - Java (android) - java

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

Related

Only 'else' is getting executed in the 'if else' statement in my Android app

Whenever I run the app, and type in 4 as the answer, it's still showing incorrect (from the else statement). ( I am relatively new to Android coding, and couldn't find an exact solution online.)
Here is my code:
public class MainActivity extends AppCompatActivity {
EditText answer;
ImageButton ttsBtn;
Button submitBtn;
TextToSpeech textToSpeech;
TextView txt;
int num;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
answer = (EditText)findViewById(R.id.answer);
ttsBtn = (ImageButton) findViewById(R.id.ttsButton);
submitBtn = (Button)findViewById(R.id.submitBtn);
txt = (TextView) findViewById(R.id.question);
String ans = answer.getText().toString();
if (!ans.isEmpty())
{num = Integer.parseInt(answer.getText().toString());}
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if(i!=TextToSpeech.ERROR){
// To Choose language of speech
textToSpeech.setLanguage(Locale.UK);
}
}
});
ttsBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newSpeech = "What is 2 multiplied by 2?";
textToSpeech.speak(newSpeech,TextToSpeech.QUEUE_FLUSH,null);
}
});
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (num == 4){
Toast.makeText(MainActivity.this, "Answer is Correct!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Answer is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});
}
}
Replace your submitBtn onclick with below code. Issue is that you are not assigning latest value of answer.
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num = Integer.parseInt(answer.getText().toString());
if (num == 4){
Toast.makeText(MainActivity.this, "Answer is Correct!", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Answer is Incorrect", Toast.LENGTH_SHORT).show();
}
}
});

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

Java global int

In an Android Studio app, I have following code:
boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
The idea is that when one of the 4 buttons is clicked, the int clicked is set to 1 and so the final button can only be clicked when it is 1.
But the code doesn't work like this; int clicked = 0; can't be accessed in other public void.
If one of the numbers 1,2,3,4 is clicked then final button can be clicked
The fix: Put public static boolean clicked = false;
under your public class YourClassName { line.
Reasoning: You need to learn how to scope your variables properly. You declared boolean clicked inside the onCreate() function, so the variable is gone after onCreate() is done running.
You should have put the clicked variable inside the class scope level, via public boolean clicked or public static boolean clicked so that even after the function returns, the value is saved.
I highly recommend a beginners java course or textbook before continuing on with your project(s).
Java does not have any concept of global variables. There is either an instance variable or a class variable. To define Global Variable you can make use of static Keyword.
static boolean clicked = true;
Button btnumb1 = (Button) this.findViewById(R.id.numb1);
Button btnumb2 = (Button) this.findViewById(R.id.numb2);
Button btnumb3 = (Button) this.findViewById(R.id.numb3);
Button btnumb4 = (Button) this.findViewById(R.id.numb4);
btnumb1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicked = false;
}
});
Button Start = (Button) this.findViewById(R.id.Start);
Start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (clicked == false) {
Random rand = new Random();
int n = rand.nextInt(4) + 1;
TextView textView = (TextView) findViewById(R.id.randOutput);
textView.setText("" + n);
}
else{
Toast.makeText(getApplicationContext(), "You have to choose a number", Toast.LENGTH_LONG).show();
}
}
});
Yes the variable int clicked = 0; has to be declared final before it is accessible in the other public void functions.
Try this declared a class say ClassClicked
public class ClassClicked {
int clicked;
public int getClicked() {
return clicked;
}
public void setClicked(int clicked) {
this.clicked = clicked;
}
}
Then changed
int clicked = 0;
to
final ClassClicked clicked = new ClassClicked();
clicked.setClicked(0);
And
clicked = 1;
to
clicked.setClicked(1);
Finally
clicked == 1
to
clicked.getClicked() == 1

How to Implement AsyncTask to delay on button

How to merge following code with Async Task . I see lots of tutorials and make changes in code but unable to do completely. This code is completely fine and working proper but some one advise me to make it Async Task so that when i press button it will take some time to start. so please someone add async task code in it so that its work proper.
Code:-
public class QuestionActivity extends Activity implements OnClickListener{
private Question currentQ;
private GamePlay currentGame;
private CountDownTimer counterTimer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
processScreen();
}
/**
* Configure current game and get question
*/
private void processScreen()
{
currentGame = ((CYKApplication)getApplication()).getCurrentGame();
currentQ = currentGame.getNextQuestion();
Button nextBtn1 = (Button) findViewById(R.id.answer1);
nextBtn1.setOnClickListener(this);
Button nextBtn2 = (Button) findViewById(R.id.answer2);
nextBtn2.setOnClickListener(this);
Button nextBtn3 = (Button) findViewById(R.id.answer3);
nextBtn3.setOnClickListener(this);
Button nextBtn4 = (Button) findViewById(R.id.answer4);
nextBtn4.setOnClickListener(this);
Button nextBtn5 = (Button) findViewById(R.id.answer5);
nextBtn5.setOnClickListener(this);
/**
* Update the question and answer options..
*/
setQuestions();
}
/**
* Method to set the text for the question and answers from the current games
* current question
*/
private void setQuestions() {
//set the question text from current question
String question = Utility.capitalise(currentQ.getQuestion());
TextView qText = (TextView) findViewById(R.id.question);
qText.setText(question);
//set the available options
List<String> answers = currentQ.getQuestionOptions();
TextView option1 = (TextView) findViewById(R.id.answer1);
option1.setText(Utility.capitalise(answers.get(0)));
TextView option2 = (TextView) findViewById(R.id.answer2);
option2.setText(Utility.capitalise(answers.get(1)));
TextView option3 = (TextView) findViewById(R.id.answer3);
option3.setText(Utility.capitalise(answers.get(2)));
TextView option4 = (TextView) findViewById(R.id.answer4);
option4.setText(Utility.capitalise(answers.get(3)));
int score = currentGame.getScore();
String scr = String.valueOf(score);
TextView score1 = (TextView) findViewById(R.id.score);
score1.setText(scr);
counterTimer=new CountDownTimer(15000, 1000) {
public void onFinish() {
if(currentGame.getRound()==20)
System.exit(0);
currentGame.decrementScore();
processScreen();
}
public void onTick(long millisUntilFinished) {
TextView time = (TextView) findViewById(R.id.timers);
time.setText( ""+millisUntilFinished/1000);
}
};
counterTimer.start();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onClick(View arg0) {
//Log.d("Questions", "Moving to next question");
if(arg0.getId()==R.id.answer5)
{
new AlertDialog.Builder(this).setMessage("Are you sure?").setCancelable(true).setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
finish();
}
}).setNegativeButton("No", null).show();
}
else
{
if(!checkAnswer(arg0)) return;
/**
* check if end of game
*/
if (currentGame.isGameOver()){
//Log.d("Questions", "End of game! lets add up the scores..");
//Log.d("Questions", "Questions Correct: " + currentGame.getRight());
//Log.d("Questions", "Questions Wrong: " + currentGame.getWrong());
Intent i = new Intent(this, EndgameActivity.class);
startActivity(i);
finish();
}
else
{
Intent i = new Intent(this, QuestionActivity.class);
finish();
startActivity(i);
}
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK :
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* Check if a checkbox has been selected, and if it
* has then check if its correct and update gamescore
*/
private boolean checkAnswer(View v) {
Button b=(Button) v;
String answer = b.getText().toString();
counterTimer.cancel();
b.setBackgroundResource(R.drawable.ans);
b.setEnabled(false);
//Log.d("Questions", "Valid Checkbox selection made - check if correct");
if (currentQ.getAnswer().equalsIgnoreCase(answer))
{
b.setBackgroundResource(R.drawable.ansgreen);
//Log.d("Questions", "Correct Answer!");
currentGame.incrementScore();
}
else{
b.setBackgroundResource(R.drawable.ansred);
//Log.d("Questions", "Incorrect Answer!");
currentGame.decrementScore1();
}
return true;
}
}
Hope Anyone Can Help me.
Thanks in Advance
Use Runnable :
private static final int START_AFTER_SECONDS = 10;
...
Runnable mRunnable;
Handler mHandler = new Handler();
mRunnable = new Runnable() {
#Override
public void run() {
//DELAYED CODE HERE
}
};
mHandler.postDelayed(mRunnable, START_AFTER_SECONDS * 1000);
AsyncTask is not the right tool for this job. Try this
getHandler().postDelayed(
new Runnable {
void run()
{
methodToCall();
}
}, delayTimeInMilliseconds);

ProgressBar with a countdowntimer - Android

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

Categories

Resources