I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.
Related
I have a Quiz app sourcecode with multiple radioGroups in a recyclerView and I want everytime a correct radioButton in a certain position (radioGroup) is selected, it should update a score correct++ and send it to an activity as below.
#Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
int position = getAdapterPosition();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
This works but only on one radioGroup, as in if I select another radioButton from a different position, the score correct is always 1 probably because it is reset to default before onClick funtion is executed again.
My possible solution would be a loop i <= arrayList.size() to contain if (checked) to prevent score correct from being reset to default = 0, but I don't know where to place it and what to contain, because it's not mandatory for the user to select from each radioGroup (unless for the simplest scenario it's a requirement).
How can I update the score for every radioButton of the radioGroup/position the selected?
Adding the for loop solved everything
#Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
int position = getAdapterPosition();
for (int i = 0; i <= position; i++) {
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
}
"goClicked" function is a onClick function to the button "Go" but it is not executing when I click on the button "Go"( I am able to say this because the toast is not appearing ) until I comment the while loop in "goClicked" function. I am pasting the code for only 2 functions "goClicked" and "countdown" because they are the only functions that alter the variable "counterRunning".
public void goClicked(View view) {
afterGoPressed();
countDown();
correctCount = 0;
totalCount = 0;
TextView time = (TextView) findViewById(R.id.time);
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
}
public void countDown() {
counterRunning = true;
final TextView time = (TextView) findViewById(R.id.time);
final Button tryAgain = (Button) findViewById(R.id.tryAgain);
final TextView result = (TextView) findViewById(R.id.result);
final TextView score = (TextView) findViewById(R.id.score);
int secondsLeft = 30;
time.setText(secondsLeft+"");
CountDownTimer countDownTimer = new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
time.setText(millisUntilFinished/1000 + "");
}
#Override
public void onFinish() {
tryAgain.setVisibility(View.VISIBLE);
result.setText("Your score: " + score.getText());
result.setVisibility(View.VISIBLE);
counterRunning = false;
}
}.start();
}
It is because you're using an infinite loop with the following code:
while (counterRunning) {
int sum = generateQuestion();
pickOption = generateOptions(sum);
}
the code will blocking all other instruction until it found the counterRunning is changed to false inside the while block. But it never happened. Hence the infinite loop.
I am creating a quiz app where in it asks a question and gives users options.For options I have used RadioButton So what I want is that once the user clicked any one of the options it should not allow any other options to be clicked but the problem is that it can be still clicked.if possible please write the code.Thanks!
private int Question_no=0;
private Boolean Boolean_Var=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
String[] Question_Array = getResources().getStringArray(R.array.Question1);
TextView Questions = (TextView) findViewById(R.id.Question);
Questions.setText(Question_Array[Question_no]);
String[] Radio_Button1_Array = getResources().getStringArray(R.array.Option_1);
RadioButton Radio_Button1 = (RadioButton) findViewById(R.id.radioButton1);
Radio_Button1.setText(Radio_Button1_Array[Question_no]);
String[] Radio_Button2_Array = getResources().getStringArray(R.array.Option_2);
RadioButton Radio_Button2 = (RadioButton) findViewById(R.id.radioButton2);
Radio_Button2.setText(Radio_Button2_Array[Question_no]);
findViewById(R.id.MenuButton).setVisibility(View.INVISIBLE);
findViewById(R.id.NextButton).setVisibility(View.INVISIBLE);
}
public void On_RadioButton1_Click (View view)
{
if (Boolean_Var == false) {
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_1);
String Answer = Answer_Array[Question_no];
if (Answer.equals(CorrectAns)) {
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton1);
Right_Ans.setTextColor(Color.GREEN);
AnswerSubmitted();
} else {
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton1);
Wrong_Ans.setTextColor(Color.RED);;
GreenTick();
AnswerSubmitted();
}
}
Boolean_Var = true;
}
public void On_RadioButton2_Click(View view)
{
if(Boolean_Var==false)
{
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_2);
String Answer = Answer_Array[Question_no];
if(Answer.equals(CorrectAns))
{
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton2);
Right_Ans.setTextColor(Color.GREEN);
}
else
{
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton2);
Wrong_Ans.setTextColor(Color.RED);
GreenTick();
}
}
Boolean_Var=true;
AnswerSubmitted();
}
public void GreenTick()
{
String[] Answer1_Array = getResources().getStringArray(R.array.Option_1);
String Answer1 = Answer1_Array[Question_no];
String[] Answer2_Array = getResources().getStringArray(R.array.Option_2);
String Answer2 = Answer2_Array[Question_no];
String[] Answer3_Array = getResources().getStringArray(R.array.Option_3);
String Answer3 = Answer3_Array[Question_no];
String[] The_CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String The_CorrectAnsIs = The_CorrectAns_Array[Question_no];
if(The_CorrectAnsIs.equals(Answer1))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton1);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer2))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton2);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer3))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton3);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton4);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
}
public void AnswerSubmitted()
{
findViewById(R.id.MenuButton).setVisibility(View.VISIBLE);
findViewById(R.id.NextButton).setVisibility(View.VISIBLE);
}
}
try this after click on radiobutton :
yourradioButtonId.setClickable(false);
You can use setClickable(false);.For this:
yourradiobutton.setClickable(false);
If I'm understanding correctly, you want to disable the RadioGroup once a certain RadioButton is clicked. Just add an OnCheckedChangedListener and if the id of the RadioButton clicked is the right one, then disable the group by using setEnabled(false). Of course, you can't reenable the RadioGroup unless you have some other logic in your code that will do the re-enabling.
RadioGroup radioGroup = (RadioGroup)findViewById (R.id.radioGroup1);
radioGroup.setOnCheckedChangedListener (new OnCheckedChangedListener(){
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if (checkedId == R.id.radio0)
group.setEnabled(false);
}
});
Edit: It seems that setEnabled() doesn't work, so you should try changing your code so it loops through each RadioButton upon checking radio0:
if (checkedId == R.id.radio0){
for(int i = 0; i < group.getChildCount(); i++){
((RadioButton)rg1.getChildAt(i)).setEnabled(false);
}
}
I have created a simple program to try to figure out how to do this. it has two edit text fields (input type number decimal), a text view and a button. I want the sum of the two input fields to be displayed in the text view when the user hits the button. can someone tell me how to set the value of one edit text field to zero if the user left it blank? I have tried many ways but nothing worked.
Edit: i want to achieve this while keeping the hint of edit text as before (without changing the value to zero like " setText("0"); ".
here's my java code (tell me what to add)
package com.example.android.testedittexttozero;
import...
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void calculate(View v) { //the button
final EditText number1 = (EditText) findViewById(R.id.numberFirst);
EditText number2 = (EditText) findViewById(R.id.numberSecond);
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
Do you know that in java if you dont initialize a variable with a default value, it's default value be 0?
in short:
try {
int a;//by default, it will be 0;
int b = Integer.parseInt(number2.getText().toString());//let it be 2
int sum = a + b;
total.setText("" + sum);//Ans will be 2 only
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
If you don't enter any value in a, it will be set to as 0. Like if you leave a blank, and enter 2 in second edittext, the ans will be two nevertheless..
public void ZeroingEmpytEditText() {
int f= 0; // Zeroing Factor
if (number1.getText().toString().length() > 0) {
a = Integer.parseInt(number1.getText().toString());
} else {
a=f;
}
if (number2.getText().toString().length() > 0) {
b = Integer.parseInt(number2.getText().toString());
} else {
b=f;
}
int sum = a + b ;
total.setText(sum + "");
}
you can set value 0 of edit text in oncreate method.
like,
public class MainActivity extends AppCompatActivity {
EditText number1,number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.numberFirst);
number2 = (EditText) findViewById(R.id.numberSecond);
number1.settext("0");
number2.settext("0");
}
public void calculate(View v) { //the button
TextView total = (TextView) findViewById(R.id.totalTV);
try {
int a = Integer.parseInt(number1.getText().toString());
int b = Integer.parseInt(number2.getText().toString());
int sum = a + b;
total.setText("" + sum);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "One or more field is empty", Toast.LENGTH_LONG).show();
}
}
}
its helpfull for you.
Im trying to make a currency converter homework (i am new to programming)
made everything but the radio button is keeped pressed and isnt doing nothing
(not puting text into the TextView and the radio buttons is locked on "pressed" mode
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
mResult = (TextView) findViewById(R.id.result);
mToConvert = (EditText) findViewById(R.id.toConvert);
mRadioGroup = (RadioGroup) findViewById(R.id.radioG);
mDollar = (RadioButton) findViewById(R.id.dollar);
Meuro = (RadioButton) findViewById(R.id.euro);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
switch (mRadioGroup.getCheckedRadioButtonId())
{
case R.id.dollar:
Double dollarConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double price = dollarConvert * 1.28;
mDollar.setChecked(true);
Meuro.setChecked(false);
String result = mToConvert.getText().toString();
mResult.setText(result + price);
break;
case R.id.euro:
Double euroConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double value = euroConvert * 1.28;
mDollar.setChecked(false);
Meuro.setChecked(true);
String result1 = mToConvert.getText().toString();
mResult.setText(result1 + value);
break;
default:;
}
}
});
}
}
you will need to set RadioGroup.setoncheckedchangelistener for RadioGroup to do some Action when check changes event fire.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
//do your code here
}
});