I am building a little quiz app and let's say on Question 1, I select option B, then submit and the quiz gives me the next question. However for question 2 if I try to select B, the RadioButton quickly unchecks itself and it is completely uncheckable, until I select another radio button and then try B again. The pattern is, whatever option I selected in the previous question, is uncheckable in the next question unless I click on a different radiobutton and then try again. I'm attaching my code. Any help please?
public class MainActivity extends AppCompatActivity {
QuestionBank allQuestions = new QuestionBank();
String pickedAnswer = "", correctAnswer = "";
final int numberOfQuestions = allQuestions.list.size();
int questionNumber = 0;
boolean noSelection = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextQuestion();
}
private void nextQuestion() {
if (questionNumber <= numberOfQuestions - 1) {
TextView questionLabel = (TextView) findViewById(R.id.question_text_view);
String fullQuestion = allQuestions.list.get(questionNumber).questionSet.get("question").toString();
fullQuestion += "\n\na) " + allQuestions.list.get(questionNumber).questionSet.get("a");
fullQuestion += "\nb) " + allQuestions.list.get(questionNumber).questionSet.get("b");
fullQuestion += "\nc) " + allQuestions.list.get(questionNumber).questionSet.get("c");
fullQuestion += "\nd) " + allQuestions.list.get(questionNumber).questionSet.get("d");
correctAnswer = allQuestions.list.get(questionNumber).questionSet.get("answer").toString();
questionLabel.setText(fullQuestion);
questionNumber++;
} else {
restart();
}
}
public void getSelectedAnswer() {
RadioButton radio_1 = (RadioButton) findViewById(R.id.option1_button);
RadioButton radio_2 = (RadioButton) findViewById(R.id.option2_button);
RadioButton radio_3 = (RadioButton) findViewById(R.id.option3_button);
RadioButton radio_4 = (RadioButton) findViewById(R.id.option4_button);
if (radio_1.isChecked()) {
pickedAnswer = "a";
radio_1.setChecked(false);
} else if (radio_2.isChecked()) {
pickedAnswer = "b";
radio_2.setChecked(false);
} else if (radio_3.isChecked()) {
pickedAnswer = "c";
radio_3.setChecked(false);
} else if (radio_4.isChecked()) {
pickedAnswer = "d";
radio_4.setChecked(false);
} else {
noSelection = true;
}
}
public void submitAnswer(View view) {
getSelectedAnswer();
if (noSelection) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Please select an answer!");
a_builder.show();
noSelection = false;
} else {
checkAnswer();
nextQuestion();
}
}
public void checkAnswer() {
if (correctAnswer == pickedAnswer) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Right Answer!");
a_builder.show();
} else {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Wrong Answer!");
a_builder.show();
}
pickedAnswer = "";
correctAnswer = "";
}
public void restart() {
questionNumber = 0;
//Collections.shuffle(allQuestions.list);
nextQuestion();
}
}
call setChecked(false) on all the buttons after submitting or before showing next question
Related
Hi everyone I need help.
I have this code
I have 50 question string and I want if already 10 question appears then the game finish. thank you for your help
private Question mQuestion = new Question();
private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore );
updateQuestion(r.nextInt(mQuestionLenght));
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer4.getText() == mAnswer){
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
} else {
gameOver();
}
}
});
}
private void updateQuestion(int num){
question.setText(mQuestion.getQuestion(num));
answer1.setText(mQuestion.getChoice1(num));
answer2.setText(mQuestion.getChoice2(num));
answer3.setText(mQuestion.getChoice3(num));
answer4.setText(mQuestion.getChoice4(num));
mAnswer = mQuestion.getCorrectAnswer(num);
}
private void gameOver(){
}
i have 50 question i want if user already answer 10 question game stop and show score. in that code it cant stop if they wrong answer game can stop but if user always right game load all question
In your Acitivty, add a counter attribute
private int numberOfQuestionsAsked = 0;
After each question asked, add 1 to your counter
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
numberOfQuestionsAsked++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
}
After the user answered a question, check if the counterhas reached 10, if yes, go to gameOver
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
In gameOver, reset the counter so the game can restart
numberOfQuestionsAsked = 0;
Your code should look like
private Question mQuestion = new Question();
private String mAnswer;
private int mScore = 0;
private int mQuestionLenght = 5 ;
private int numberOfQuestionsAsked = 0;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
r = new Random();
answer1 = (Button) findViewById(R.id.answer1);
answer2 = (Button) findViewById(R.id.answer2);
answer3 = (Button) findViewById(R.id.answer3);
answer4 = (Button) findViewById(R.id.answer4);
score = (TextView) findViewById(R.id.score);
question = (TextView) findViewById(R.id.question);
score.setText("Score: " + mScore );
updateQuestion(r.nextInt(mQuestionLenght));
answer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(answer4.getText().equals(mAnswer)){ //note : use .equals() and not == !
mScore++;
score.setText("Score: " + mScore);
updateQuestion(r.nextInt(mQuestionLenght));
numberOfQuestionsAsked++;
} else {
gameOver();
}
if(numberOfQuestionsAsked <= 10) {
gameOver();
}
}
});
}
private void updateQuestion(int num){
question.setText(mQuestion.getQuestion(num));
answer1.setText(mQuestion.getChoice1(num));
answer2.setText(mQuestion.getChoice2(num));
answer3.setText(mQuestion.getChoice3(num));
answer4.setText(mQuestion.getChoice4(num));
mAnswer = mQuestion.getCorrectAnswer(num);
}
private void gameOver(){
numberOfQuestionsAsked = 0;
}
Add a counter in your code like this :
Int counter = 0;
if(counter <= 10 ){
updateQuestion(r.nextInt(mQuestionLenght));
counter++;
} else {
gameOver();
}
Add this and check, hope it will work.
First of all, I would use:
View.OnClickListener listener = new View.onClickListener() {
#Override
public void onClick(View view) {
if(view instanceOf (TextView) && ((TextView)view).getText().toString().equals(mAnswer)){
mScore++;
score.setText("Score: " + mScore);
if(mScore >= 10) {
gameCompleted();//ToDo
} else {
updateQuestion(r.nextInt(mQuestionLenght));
}
} else {
gameOver();
}
}
};
Then, use this listener in every answer.
Futhermore, your random number may fail because it can be higher than 50 and can be a repeated answer and your text comparison is not recommended, you could use an object which assigns an id to the text.
Enjoy coding.
I'm almost new to android and trying to write a calculator code.
It's almost done but I want to try some other options for that
when I repeat clicking on equal button,I want to repeat last calculation entered.for example 3+5=8 then if I click on exe button again it would be 13(3+5+5)
and so on(18,23,...)
Also I have problem with entering more than two numbers.for example when I enter (4+5+6)and then click equal the answer will appear 11 and just calculates last two numbers entered.I want it to show the result of first two numbers then get other numbers.example:for(2+3*4-5/)->the output will be equal to (5->20->15)
Here is my code;If any one can help,I will be grateful! :) thanks
package com.example.sony.calculator;
public class MainActivity extends AppCompatActivity {
Float firstNumber,secondNumber,result;
Float thirdNumber;
TextView display;
Button one,two,three,four,five,six,seven,eight,nine,zero,exe,clear,multiply,divide,sum,minus;
boolean isSum,isMinus,isMultiply,isDivide,isEqual;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.khali);
one = (Button) findViewById(R.id.adade1);
two = (Button) findViewById(R.id.adade2);
three = (Button) findViewById(R.id.adade3);
four = (Button) findViewById(R.id.adade4);
five = (Button) findViewById(R.id.adade5);
six = (Button) findViewById(R.id.adade6);
seven = (Button) findViewById(R.id.adade7);
eight = (Button) findViewById(R.id.adade8);
nine = (Button) findViewById(R.id.adade9);
zero = (Button) findViewById(R.id.adade0);
multiply = (Button) findViewById(R.id.zarb);
divide = (Button) findViewById(R.id.taghsim);
sum = (Button) findViewById(R.id.jam);
minus = (Button) findViewById(R.id.menha);
exe = (Button) findViewById(R.id.mosavi);
clear = (Button) findViewById(R.id.pak);
final Button[] operators = new Button[5];
operators[0] = multiply;
operators[1] = divide;
operators[2] = sum;
operators[3] = minus;
operators[4] = exe;
final Button[] numbers = new Button[10];
numbers[0] = zero;
numbers[1] = one;
numbers[2] = two;
numbers[3] = three;
numbers[4] = four;
numbers[5] = five;
numbers[6] = six;
numbers[7] = seven;
numbers[8] = eight;
numbers[9] = nine;
for (int a = 0; a < 10; a++) {
final int finalA = a;
numbers[a].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText(display.getText().toString() + String.valueOf(finalA));
}
});
}
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText("");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
display.setText("");
return;
}
else{
firstNumber = parseFloat(display.getText().toString());
isSum=true;
display.setText("");
return;
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
display.setText("");
}else {
firstNumber = parseFloat(display.getText().toString());
isMinus = true;
display.setText("");
}
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText()==""){
Toast Error1=Toast.makeText(MainActivity.this,"Error;Please enter right format",Toast.LENGTH_SHORT);
Error1.show();
}else {
firstNumber = parseFloat(display.getText().toString());
isMultiply = true;
display.setText("");
}
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == "") {
Toast Error1 = Toast.makeText(MainActivity.this, "Error;Please enter right format", Toast.LENGTH_SHORT);
Error1.show();
} else {
firstNumber = parseFloat(display.getText().toString());
isDivide = true;
display.setText("");
}
}
});
exe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
isEqual=true;
if (display.getText() == "") {
display.setText("");
}
else {
secondNumber = parseFloat(display.getText().toString());
if (isSum == true) {
result = firstNumber + secondNumber ;
display.setText(String.valueOf(result));
isSum=false;
return;
}
if (isMinus == true) {
result = firstNumber - secondNumber;
display.setText(String.valueOf(result));
isMinus = false;
return;
}
if (isDivide == true) {
result = firstNumber / secondNumber;
display.setText(String.valueOf(result));
isDivide = false;
return;
}
if (isMultiply == true) {
result = firstNumber * secondNumber;
display.setText(String.valueOf(result));
isMultiply=false;
return;
}
}
}
});
}
}
This code right here is a random math questionnaire and I want to know how to be able to transfer the amount of questions answered right and wrong to a separate stats page after each time they answer a question. I want the stats page to save the numbers so that if the user exits the program and then goes back on later they can still look at their total right answered questions and wrong answered questions. Ive been looking all over the internet and cant find a good way to learn this. If anyone has some advice I would really appreciate it. btw this is pretty much all the code in the main page; I didn't add the stats page code (because it has pretty much nothing.)
Pushme1-4 are the buttons and the AdditionEasyRight and AdditionEasyWrong are the number counts that are displayed on the main page.
public class AdditionEasy extends AppCompatActivity {
int countCNumAddE = 0;
int countWNumAddE = 0;
boolean hasAnswered;
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addition);
final TextView count = (TextView) findViewById(R.id.Count);
final TextView count2 = (TextView) findViewById(R.id.Count2);
Button homeButton = (Button) findViewById(R.id.homeButton);
super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
final TextView textOne = (TextView) findViewById(R.id.textView);
final TextView textTwo = (TextView) findViewById(R.id.textView2);
final Button pushMe1 = (Button) findViewById(R.id.button1);
final Button pushMe2 = (Button) findViewById(R.id.button2);
final Button pushMe3 = (Button) findViewById(R.id.button3);
final Button pushMe4 = (Button) findViewById(R.id.button4);
final Button begin = (Button) findViewById(R.id.begin);
begin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
hasAnswered = false;
pushMe1.setEnabled(true);
pushMe2.setEnabled(true);
pushMe3.setEnabled(true);
pushMe4.setEnabled(true);
begin.setVisibility(View.INVISIBLE);
pushMe1.setVisibility(View.VISIBLE);
pushMe2.setVisibility(View.VISIBLE);
pushMe3.setVisibility(View.VISIBLE);
pushMe4.setVisibility(View.VISIBLE);
pushMe1.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.BLACK);
pushMe1.setTextSize(20);
pushMe2.setTextSize(20);
pushMe3.setTextSize(20);
pushMe4.setTextSize(20);
textTwo.setText("");
String randGenChoice1 = "";
String randGenChoice2 = "";
String randGenChoice3 = "";
String randGenChoice4 = "";
String randText2 = "";
String randText3 = "";
Random RandomNum = new Random();
int randChoice1 = RandomNum.nextInt(40) + 1;
int randChoice2 = RandomNum.nextInt(40) + 1;
int randChoice3 = RandomNum.nextInt(40) + 1;
int randChoice4 = RandomNum.nextInt(40) + 1;
int rando2 = RandomNum.nextInt(20) + 1;
int rando3 = RandomNum.nextInt(20) + 1;
int pick = RandomNum.nextInt(4);
randGenChoice1 = Integer.toString(randChoice1);
randGenChoice2 = Integer.toString(randChoice2);
randGenChoice3 = Integer.toString(randChoice3);
randGenChoice4 = Integer.toString(randChoice4);
randText2 = Integer.toString(rando2);
randText3 = Integer.toString(rando3);
int value1;
int value2;
value1 = Integer.parseInt(randText2);
value2 = Integer.parseInt(randText3);
final int value = value1 + value2;
String line = randText2 + " + " + randText3;
textOne.setText(line);
final String answer;
answer = Integer.toString(value);
pushMe1.setText(randGenChoice1);
pushMe2.setText(randGenChoice2);
pushMe3.setText(randGenChoice3);
pushMe4.setText(randGenChoice4);
Button[] choice = {pushMe1, pushMe2, pushMe3, pushMe4};
Button display = choice[pick];
display.setText(answer);
pushMe1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe1.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.GREEN);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe1.setTextColor(Color.RED);
pushMe1.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe1.setEnabled(false);
}
}
});
pushMe2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe2.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.GREEN);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe2.setTextColor(Color.RED);
pushMe2.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe2.setEnabled(false);
}
}
});
pushMe3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe3.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.GREEN);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe4.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe3.setTextColor(Color.RED);
pushMe3.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe3.setEnabled(false);
}
}
});
pushMe4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int buttonAnswer = Integer.parseInt(pushMe4.getText().toString());
if (buttonAnswer == value) {
begin.setVisibility(View.VISIBLE);
textTwo.setText("Correct!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.GREEN);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyRight = Integer.toString(++countCNumAddE);
count.setText(AdditionEasyRight);
hasAnswered = true;
}
begin.setText("New Question");
begin.setTextSize(20);
pushMe1.setVisibility(View.INVISIBLE);
pushMe2.setVisibility(View.INVISIBLE);
pushMe3.setVisibility(View.INVISIBLE);
pushMe1.setEnabled(false);
pushMe2.setEnabled(false);
pushMe3.setEnabled(false);
pushMe4.setEnabled(false);
}else{
textTwo.setText("Wrong!");
textTwo.setTextColor(Color.BLACK);
pushMe4.setTextColor(Color.RED);
pushMe4.setTextSize(30);
if (hasAnswered != true) {
String AdditionEasyWrong = Integer.toString(++countWNumAddE);
count2.setText(AdditionEasyWrong);
hasAnswered = true;
}
pushMe4.setEnabled(false);
}
}
});
}
});
homeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent homepage = new Intent(AdditionEasy.this , Menu.class);
startActivity(homepage);
}
});
}
}
So I'm new to java and I'm trying to make quiz app as exercise. I kinda made one but it doesn't work:
public class QuizActivity extends AppCompatActivity {
TextView QuestionText;
Button button1;
Button button2;
Button button3;
Button button4;
ArrayList<Question> listOfQuestions;
int currentQuestion = 0;
Context context = this;
int NumberOfQuestions;
GameCreator game;
String totalCorrect = "";
String totalWrong = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuestionText = (TextView) findViewById(R.id.textJautajums);
button1 = (Button) findViewById(R.id.buttonOpcija1);
button2 = (Button) findViewById(R.id.buttonOpcija2);
button3 = (Button) findViewById(R.id.buttonOpcija3);
button4 = (Button) findViewById(R.id.buttonOpcija4);
NumberOfQuestions = Integer.parseInt(context.getString(R.string.JautajumuSkaits).toString());
game = new GameCreator(NumberOfQuestions);
listOfQuestions = game.makeQuestions();
Resources r = getResources();
int px1 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 165, r.getDisplayMetrics());
button1.setWidth(px1);
button2.setWidth(px1);
button3.setWidth(px1);
button4.setWidth(px1);
Resources e = getResources();
int px2 = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 125, r.getDisplayMetrics());
button1.setHeight(px2);
button2.setHeight(px2);
button3.setHeight(px2);
button4.setHeight(px2);
if (currentQuestion == 0){
setQuestion(listOfQuestions.get(0));
}
button1.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button1.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button2.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button2.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button3.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button3.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
button4.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View V){
gajiens(button4.getText().toString(), listOfQuestions.get(currentQuestion));
currentQuestion++;
}
}
);
}
public void gajiens(String answer, Question thisQuestion){
if (currentQuestion < 14){
if (answer.equals(thisQuestion.getAnswer())){
totalCorrect += "Question: " + thisQuestion.getQuestion() + "\nYour Answer: " + answer + "\n";
} else {
totalWrong += "Question: " + thisQuestion.getQuestion()) + "\nYour Answer: " + answer + "\n";
}
currentQuestion++;
setQuestion(listOfQuestions.get(currentQuestion));
} else {
Intent intent = new Intent(this, EndActivity.class);
intent.putExtra("correct", totalCorrect);
intent.putExtra("wrong", totalWrong);
startActivity(intent);
}
}
public void setQuestion(Question kursh){
QuestionText.setText(kursh.getJautajums());
button1.setText(kursh.getOption1());
button2.setText(kursh.getOption2());
button3.setText(kursh.getOption3());
button4.setText(kursh.getOption4());
}
object Question is:
public Question(String Question, String Option1, String Option2, String Option3,String Option4, String correctAnswer){
Question = Question;
Option1 = Option1;
Option2 = Option2;
Option3 = Option3;
Option4 = Option4;
correctAnswer = correctAnswer;
}
Basically the problem is that App doesn't count the right answers. For some reason it most of the time uses the original text of TextView as ''correctAnswer''. Anyone has any idea what to do? I suspect since this isn't working properly this isn't particularly best approach so maybe someone can suggest a better one?
to compare the value of a TextView with a String you can do this as below
TextView tvAnswer = (TextView) findViewById(R.id.tvAnswer);
String correctAnswer = "Correct Answer";
if(correctAnswer.equals(tvAnswer.getText.toString()) )
{
//do something
}
else{
//do something
}
I'm developing a quiz. I got an error while showing my toast message. The error is, if the user taps the correct answer, toast says it is the wrong answer even if I tap the correct choice. Help is really appreciated! Here is the code:
public class Question2 extends Activity {
/** Called when the activity is first created. */
TextView question, items = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioGroup answers = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review = false;
Button next = null;
int score = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startquiz);
try {
score = getIntent().getIntExtra("score",0);
items = (TextView)findViewById(R.id.displayitems);
question = (TextView) findViewById(R.id.displayquestion);
answer1 = (RadioButton) findViewById(R.id.option1);
answer2 = (RadioButton) findViewById(R.id.option2);
answer3 = (RadioButton) findViewById(R.id.option3);
answers = (RadioGroup) findViewById(R.id.QueGroup1);
next = (Button) findViewById(R.id.selected);
next.setOnClickListener(nextListener);
selected = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[Question1.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0, review);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex, boolean review) {
try {
JSONObject aQues = Question1.getQuesList().getJSONObject(
qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.BLACK);
answer2.setTextColor(Color.BLACK);
answer3.setTextColor(Color.BLACK);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("", selected[qIndex] + "");
if (selected[qIndex] == 0)
answers.check(R.id.option1);
if (selected[qIndex] == 1)
answers.check(R.id.option2);
if (selected[qIndex] == 2)
answers.check(R.id.option3);
setText();
if (quesIndex == (Question1.getQuesList().length() - 1))
next.setEnabled(false);
if (quesIndex < (Question1.getQuesList().length() - 1))
next.setEnabled(true);
if (review) {
Log.d("review", selected[qIndex] + "" + correctAns[qIndex]);
;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
Log.d("", Arrays.toString(selected));
Log.d("", Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
{
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
quesIndex++;
try {
if (quesIndex >= Question1.getQuesList().length())
quesIndex = Question1.getQuesList().length() - 1;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
showQuestion(quesIndex, review);
}
};
private void setText() throws JSONException {
this.setTitle("Question " + (quesIndex + 1) + " out of "
+ Question1.getQuesList().length());
items.setGravity(250);
}
public void reload() {
setAnswer();
Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
overridePendingTransition(0, 0);
startActivity(intent);
}
Your If() condition should be like this:-
if ((correctAns[i] != -1) && (correctAns[i].equalsIgnoreCase(selected[i]))) {
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
It seems like you can change your condition. Are users be able to select multiple answers?
And try that thin with condition like
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i].euqalsIgnoreCase(selected[i]))){
score++;
Toast.makeText(getApplicationContext(), "Your answer is correct!", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Your answer is wrong...", Toast.LENGTH_SHORT).show();
}
}
Try this and let me know that it works or not.