Making Quiz App in Android with Radio Buttons - java

I'm making a Quizz App for Android with 10 Questions, all of them with 4 Radio Buttons, and one button at the end to show the score. The problem is when I choose the correct answer it gives 5 points, but if I check another radio button the points will stay 5 and if I press again it sums 5. What is the best way to code this?
Here is the code:
package com.example.android.quizproject;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
points += 0;
break;
case R.id.questionOneB:
if (checked)
points += 0;
break;
case R.id.questionOneC:
if (checked)
points += 5;
break;
case R.id.questionOneD:
if (checked)
points += 0;
break;
}
}
public void showScore (View view) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(" " + points);
}
}

You can make use of a counter vvariable which checks if the question has been previousy answered or not. Modify part of your code to this
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
int count=0;
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneB:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneC:
if (checked){
points += 5;
count+=1;}
break;
case R.id.questionOneD:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
}
}

Actually, the way you described it, it's common sense. If you click the right answer once, it will set it to 5, but if you press any other it will add 0 to it.
In general, it will print out 5 since you got the answer correct once, and the other questions are set to 0. There's really nothing to fix here, it's kind of common sense that your variable wouldn't read other than 5. Just like Abhriya said, you could add a counter increment value as done in ( her / his ) example.

Related

Why is the text in TextViews changing two times when I am calling it only once at a time?

I know setText just changes the text only once but I can't seem to find the reason why the text in it changes before I move on to the next question in the quizActivity
What I have made is an app with one activity in it which has a quiz in it, a question is displayed along with 4 options. When the user selects an option, if that option is correct then it becomes green and red otherwise and additionally, I then open a dialog box showing whether the answer was right or wrong and then the question is changed when the user clicks Next on the dialog box.
But what is happening that when the user selects an option, in between the process of clicking the option and then clicking next on the dialog box, the text in the questions and the options changes and I can't seem to figure out why is that happening. In total, the question and options change two times when they should change only once, the unexpected change is when the user clicks on an option and the dialog box opens.
Here's the code:
#Override
public void onClick(View view) {
int selectedOption = 0;
switch (view.getId()) {
case R.id.option_1_tile:
selectedOption = 1;
break;
case R.id.option_2_tile:
selectedOption = 2;
break;
case R.id.option_3_tile:
selectedOption = 3;
break;
case R.id.option_4_tile:
selectedOption = 4;
break;
default:
}
checkAnswer(selectedOption, view);
}
Here's the function which checks the answer:
private void checkAnswer(int selectedOption, View view) {
if (selectedOption == selected_questions.get(quesNum).getAnswer()) {
//Right Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
quizReference.child(selected_questions.get(quesNum).getId()).child("correct_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getCorrect_attempts()) + 1));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
score++;
correctDialog();
} else {
//Wrong Answer
(view).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
quizReference.child(selected_questions.get(quesNum).getId()).child("total_attempts").setValue(String.valueOf(Integer.valueOf(selected_questions.get(quesNum).getTotal_attempts()) + 1));
switch (selected_questions.get(quesNum).getAnswer()) {
case 1:
options[0].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 2:
options[1].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 3:
options[2].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
case 4:
options[3].setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
break;
}
wrongDialog ();
}
}
Here's the function which changes the question:
private void changeQuestion() {
resetColor ();
if (quesNum < selected_questions.size() - 1) {
quesNum++;
playAnim(question, 0, 0);
playAnim(option1_text, 0, 1);
playAnim(option2_text, 0, 2);
playAnim(option3_text, 0, 3);
playAnim(option4_text, 0, 4);
qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(selected_questions.size()));
} else {
// Go to Score Activity
Intent intent = new Intent(quizActivity.this, scoreActivity.class);
intent.putExtra("SCORE", String.valueOf(score) + "/" + String.valueOf(selected_questions.size()));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Here's the function which sets the text and animation:
private void playAnim(final View view, final int value, final int viewNum) {
view.animate().alpha(value).scaleX(value).scaleY(value).setDuration(500)
.setStartDelay(100).setInterpolator(new DecelerateInterpolator())
.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
if (value == 0) {
switch (viewNum) {
case 0:
((TextView) view).setText(selected_questions.get(quesNum).getQuestion());
break;
case 1:
((TextView) view).setText(selected_questions.get(quesNum).getOption1());
break;
case 2:
((TextView) view).setText(selected_questions.get(quesNum).getOption2());
break;
case 3:
((TextView) view).setText(selected_questions.get(quesNum).getOption3());
break;
case 4:
((TextView) view).setText(selected_questions.get(quesNum).getOption4());
break;
}
if (viewNum != 0)
(view).setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#E99C03")));
playAnim(view, 1, viewNum);
}
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
Here's the code for the dialog boxes:
public void wrongDialog() {
final Dialog dialogWrong = new Dialog(quizActivity.this);
dialogWrong.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogWrong.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogWrong.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogWrong.setContentView(R.layout.dialog_wrong);
dialogWrong.setCancelable(false);
dialogWrong.show();
TextView wrongText = (TextView) dialogWrong.findViewById(R.id.wrongText);
Button buttonNext = (Button) dialogWrong.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogWrong.dismiss();
//reset the color of buttons back to white
resetColor();
//Change question
changeQuestion();
}
});
}
public void correctDialog() {
final Dialog dialogCorrect = new Dialog(quizActivity.this);
dialogCorrect.requestWindowFeature(Window.FEATURE_NO_TITLE);
if (dialogCorrect.getWindow() != null) {
ColorDrawable colorDrawable = new ColorDrawable(Color.TRANSPARENT);
dialogCorrect.getWindow().setBackgroundDrawable(colorDrawable);
}
dialogCorrect.setContentView(R.layout.dialog_correct);
dialogCorrect.setCancelable(false);
dialogCorrect.show();
TextView correctText = (TextView) dialogCorrect.findViewById(R.id.correctText);
Button buttonNext = (Button) dialogCorrect.findViewById(R.id.dialogNext);
//OnCLick listener to go next que
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//This will dismiss the dialog
dialogCorrect.dismiss();
//reset the color of buttons back to white
resetColor();
//it will increment the question number
changeQuestion();
}
});
}
I have tried to explain it to my best ability though I would be glad to answer any additional information/code you may want. Also, this is the link for the project if you have the time to run it and understand the problem better.
I have checked your code. you have placed an addValueEventListener in setUpdates method. When you select an option, you update the firestore database by setting fields like total attempts. As a result, eventListener gets triggered and "selectQuestionSet" function is called.
Hence, every time you select an option, selectQuestionSet function is called. You should make sure that its called only once at the start.

Android: switch case & random number code in the case

Android, java, studio 4.0.1
Trying to code by my own, I am facing an issue which I do not understand from the compiler statements.
Basically, when you click a radio button, a random number is generated in the textview field.
My problem is that the random code written in the case of the clicked radio button is not accepted by the compiler.
Here is the code:
package com.example.random;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
int random;
int random2;
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
random = getRandomNumber(0,1);
MytextView.setText(random.toString());
break;
case R.id.radioButton1to6:
if (checked)
// 1 to 6 code
random2 = getRandomNumber(1,6);
MytextView.setText(random2.toString());
break;
}
}
private int getRandomNumber(int min,int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
}
I presume that the 2 lines 'Int random;' are wrong, but the compiler seems to want to have them here.
I would have understood that the line 'random = getRandomNumber(0,1);' would have be sufficient in the case part of the code, but the compiler marks 'random' in red.
So far, the compiler says: 'error: int cannot be dereferenced in the MytextView.setText(random.toString());' of the //0 or 1 code part.
I would like to understand what I am missing here. Thanks in advance.
(Or asked simpler: how does one code a random function in a switch/case ?)
ok I found the solution. A possible working code is:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
final Random rnd = new Random();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
MytextView.setText(String.valueOf(rnd.nextInt(3-0) + 0));
break;
case R.id.radioButton1to6:
if (checked)
// Dice 1 to 6 code
MytextView.setText("1 to 6");
break;
case R.id.radioButton1to10:
if (checked)
// 1 to 10 code
MytextView.setText("1 to 10");
break;
}
}
And the 'private int getRandomNumber' at the end can be deleted. No need of it.

Preventing a second click on RadioButton if it was already checked

I am creating a small quiz app. As the question suggests, how do I prevent a second click without disabling the button? When I click twice on a radio button it adds 2 points instead of 1. Very much appreciated!
Here's a picture of my app:
public void question1 (View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question1_9:
if (checked) {
scoreForRadioButtons += 1;
}
case R.id.question1_8:
if (checked) {
break;
}
case R.id.question1_7:
if (checked) {
break;
}
}
}
SOLVED
This is what I did: just add 'break;' on the correct answer.
public void question1 (View view) {
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.question1_9:
if (checked) {
pointForQ1 = 1;
break;
}
case R.id.question1_8:
if (checked) {
pointForQ1 = 0;
}
case R.id.question1_7:
if (checked) {
pointForQ1 = 0;
}
}
}
Short Answer:
You can set the clickable attribute to false for the RadioButton after it is clicked if you really want to using the following:
myRadioButton.setClickable(false);
Long Answer:
Don't use radio buttons for this. Users should be able to click a radio button as many times as they want without anything happening like incrementing the score in your case. It's a standard convention of a radio button that once selected, no new code is executed if it is selected again and again. Note this is only if the state of the radio button hasn't changed during selections (state meaning whether it's selected or not).
The way your app is using (or wants to use) RadioButtons is not correct. I'd recommend using buttons for this, where you could do the following:
myButton.setEnabled(false);
Edit:
If you want to make it visible to the user that they clicked a button, you can do a few things (change it's text, change the background colour). For this example, you can change the background colour with this:
myButton.setBackgroundColor(Color.GREEN); // or whatever colour you choose
If you want to do this add the following to your imports:
import android.graphics.Color
If you just don't want to click that radio button two times, After radio button is clicked,
add view.setEnabled(false);or
view.setClickable(false); to prevent it click again
To prevent the second click on a checked radio button, make that radio disabled
radioButton.setEnabled(false);
Disable a clicked button and enable it when another is checked
public void question1 (View view) {
//will enable all buttons
Integer[] buttons = {R.id.question1_9, R.id.question1_8, R.id.question1_7};
for (int i = 0; i < buttons.length; i++) {
findViewById(buttons[i]).setEnabled(true);
}
RadioButton button = (RadioButton) view;
if (button.isChecked()){
switch (view.getId()) {
case R.id.question1_9:
scoreForRadioButtons ++;
//will disable clicked button
button.setEnabled(false);
break;
case R.id.question1_8:
break;
case R.id.question1_7:
break;
}
}

How do I prevent my submit button in android from giving me multiple scores when clicked multiple times?

Whenever I answer a question and hit the submit button, a score of 1 should show but on hitting submit button again, it keeps adding 1 to the score and more hits on the submit button keeps adding more 1 to the score. I actually don't want 1 to be added to the score every time the submit button is clicked. I do not want the score to be updated based on the number of times I hit the submit button.
package com.example.android.generalknowledge;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
int baseScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void submitResult(View view) {
RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
boolean answerIsLargestRailwayStation = largestRailwayStation.isChecked();
RadioButton insects = (RadioButton) findViewById(R.id.insects);
boolean answerIsInsects = insects.isChecked();
CheckBox physicsChemistry = (CheckBox) findViewById(R.id.physics_chemistry);
boolean physicsChemistryIsAnswer = physicsChemistry.isChecked();
CheckBox physiologyMedicine = (CheckBox) findViewById(R.id.physiology_medicine);
boolean physiologyMedicineIsAnswer = physiologyMedicine.isChecked();
CheckBox literature = (CheckBox) findViewById(R.id.literature);
boolean literatureIsAnswer = literature.isChecked();
CheckBox peaceEconomics = (CheckBox) findViewById(R.id.peace_economics);
boolean peaceEconomicsIsAnswer = peaceEconomics.isChecked();
RadioButton naziParty = (RadioButton) findViewById(R.id.nazi_party);
boolean answerIsNaziParty = naziParty.isChecked();
RadioButton allOfTheAbove = (RadioButton) findViewById(R.id.all_of_the_above);
boolean answerIsAll = allOfTheAbove.isChecked();
RadioButton filmFinance = (RadioButton) findViewById(R.id.film_finance);
boolean answerIsFilmFinance = filmFinance.isChecked();
EditText enterNameHere = (EditText) findViewById(R.id.name_view);
String name = enterNameHere.getText().toString();
EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
String answer = enterAnswerHere.getText().toString();
if (enterAnswerHere.getText().toString().equals("Africa")) {
baseScore += 1 ;
}
int finalScore = calculateTotalScore(answerIsLargestRailwayStation, answerIsInsects, physicsChemistryIsAnswer,
physiologyMedicineIsAnswer, literatureIsAnswer, peaceEconomicsIsAnswer, answerIsNaziParty, answerIsAll, answerIsFilmFinance);
Toast.makeText(MainActivity.this,
name + " " + "\n" + "You have a Total Score of " + " " + finalScore + " " + "/10", Toast.LENGTH_LONG).show();
}
/**
* This method is called when any of the radio buttons in question one is selected
*/
public void onRadioButtonClickedOne(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.largest_railway_station:
if (checked)
// This is the correct answer
break;
case R.id.highest_railway_station:
if (checked)
// Wrong answer
break;
case R.id.longest_railway_station:
if (checked)
// Wrong answer
break;
case R.id.none_of_the_above:
if (checked)
//Wrong answer
break;
}
}
/**
* This method is called when any of the radio buttons in question two is selected
*/
public void onRadioButtonClickedTwo(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.behaviour_of_human_beings:
if (checked)
// Wrong answer
break;
case R.id.insects:
if (checked)
// This is the correct answer
break;
case R.id.origin_history:
if (checked)
// Wrong answer
break;
case R.id.rock_formation:
if (checked)
// Wrong answer
break;
}
}
/**
* This method is called when the checkboxes for question three are clicked
*/
public void onCheckboxThreeClicked(View view) {
//Is the button now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox is clicked
switch (view.getId()) {
case R.id.physics_chemistry:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.physiology_medicine:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.literature:
if (checked)
// One of the Correct answers
break;
}
switch (view.getId()) {
case R.id.peace_economics:
if (checked)
// One of the Correct answers
break;
}
}
/**
* This method is called when any of the radio buttons in question four is selected
*/
public void onRadioButtonClickedFour(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.labour_party:
if (checked)
// Wrong answer
break;
case R.id.nazi_party:
if (checked)
// This is the correct answer
break;
case R.id.leading_party:
if (checked)
// Wrong answer
break;
case R.id.democratic_party:
if (checked)
// Wrong answer
break;
}
}
/**
* This method is called when any of the radio buttons in question six is selected
*/
public void onRadioButtonClickedSix(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.develop_telescope:
if (checked)
// Wrong answer
break;
case R.id.discovered_jupiter:
if (checked)
// Wrong answer
break;
case R.id.movement_of_pendulum:
if (checked)
// Wrong answer
break;
case R.id.all_of_the_above:
if (checked)
// This is the correct answer
break;
}
}
/**
* This method is called when any of the radio buttons in question seven is selected
*/
public void onRadioButtonClickedSeven(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch (view.getId()) {
case R.id.foreign_finance:
if (checked)
// Wrong answer
break;
case R.id.film_finance:
if (checked)
// This is the correct answer
break;
case R.id.federation_football:
if (checked)
// Wrong answer
break;
case R.id.none:
if (checked)
// Wrong answer
break;
}
}
private int calculateTotalScore(boolean questionOneAnswer, boolean questionTwoAnswer, boolean questionThreeAnswer1,
boolean questionThreeAnswer2, boolean questionThreeAnswer3, boolean questionThreeAnswer4,
boolean questionFourAnswer, boolean questionSixAnswer, boolean questionSevenAnswer) {
if (questionOneAnswer) {
baseScore += 1 ;
}
if (questionTwoAnswer) {
baseScore += 1 ;
}
if (questionThreeAnswer1) {
baseScore += 1 ;
}
if (questionThreeAnswer2) {
baseScore += 1 ;
}
if (questionThreeAnswer3) {
baseScore += 1 ;
}
if (questionThreeAnswer4) {
baseScore += 1 ;
}
if (questionFourAnswer) {
baseScore += 1 ;
}
if (questionSixAnswer) {
baseScore += 1 ;
}
if (questionSevenAnswer) {
baseScore += 1 ;
}
// EditText enterAnswerHere = (EditText) findViewById(R.id.answer_here);
// String answer = enterAnswerHere.getText().toString();
// {
// if (answer == "Africa") {
// baseScore = baseScore + 1;
// }
// }
return baseScore;
}
}
We can achieve by 2 ways,
You can diable the button by button.setEnable(false); once user click for for time
In your case if you don't have button object so you can use one global boolean and make that as false default and once user click for first time do the process and make that boolean as true, from next time check if the boolean is true just return it.
private boolean mIsSubmited = false;
public void submitResult(View view) {
if(mIsSubmited) {
return;
}
mIsSubmited = true;
RadioButton largestRailwayStation = (RadioButton) findViewById(R.id.largest_railway_station);
// Remaining code..
}
You can disable the submit button once it is clicked. For eg:
onclick() {
submitbutton.setEnabled(false);
}
Prevent user to click on submit again and again.
You can enable it back using:
submitbutton.setEnabled(true);
You can declare a Boolean globally and set it to false at first.
then on button click you can turn its value to true.
on the button click you can check if its false then only to increase the score.
You can use handler for this may be there is better solution then this.
Handler mHandler=new Handler();
//now in your click listener
mHandler.removeCallbacks(mRunnable);//
mHandler.postDelayed(mRunnable, 500);
Runnable mRunnable =new Runnable() {
#Override
public void run() {
//calculate it
}
};
//Wait for half sec before calculating the result if user clicked before then stop runnable from calcualting and again go for calculation.
Hope it helps.

Rolling a dice based on number of sides

EDIT: See included error log.
I am trying to create a simple app to roll different sided dice in Android Studio.
This is my code so far:
MainActivity.java
package com.example.thomb.tutorialspoint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonRoll);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int roll = RollDice(sidesChosen);
TextView tv1 = (TextView)findViewById(R.id.textView);
tv1.setText(roll);
setContentView(tv1);
}
});
}
public int sidesChosen;
public int RollDice(int sides) {
Random r = new Random();
return r.nextInt(sides)+1;
} //method
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButtonD4:
if (checked)
sidesChosen = 4;
break;
case R.id.radioButtonD6:
if (checked)
sidesChosen = 6;
break;
case R.id.radioButtonD8:
if (checked)
sidesChosen = 8;
break;
case R.id.radioButtonD10:
if (checked)
sidesChosen = 10;
break;
case R.id.radioButtonD12:
if (checked)
sidesChosen = 12;
break;
case R.id.radioButtonD20:
if (checked)
sidesChosen = 20;
break;
} //switch
} //method
} //class
This is how the layout looks like:
http://i.imgur.com/IeIbMlz.png
The app crashes when i click the roll button, but I've no idea why. The ID's are all correct and the radio buttons works as expected.
I am using API level 25. I am fairly new to Java, but I am quite familiar with C#, so the problem may lie in the code syntax, although Android Studio reports no errors. Let me know if you need to see the XML for the layout as well.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thomb.tutorialspoint, PID: 5029
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4310)
at android.view.ViewGroup.addView(ViewGroup.java:4146)
at android.view.ViewGroup.addView(ViewGroup.java:4087)
at android.view.ViewGroup.addView(ViewGroup.java:4060)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:279)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:145)
at com.example.thomb.tutorialspoint.MainActivity$1.onClick(MainActivity.java:25)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
setText() is a overloaded method with two types: one that takes in a String, the other an int. The int here should be string resource ID. This is where your error is. In the code below you're using setText(int) but not passing a valid string resource ID.
int roll = RollDice(sidesChosen);
...
tv1.setText(roll);
Do setText(String.valueOf(roll) to convert it to a String first
EDIT after log post:
The cause of your error is that you're passing 0 to the nextInt() method. This might happen because you've never selected a RadioButton (sidesChosen is 0 by default) or that even after selecting a RadioButton, none of the cases of the switch is entered.
EDIT after second log post: (...)
Remove setContentView(tv1); This is used to attach a layout to an activity. Why are you using it here?
It seems, that you pass 0 to the Random.nextInt() method, which is not allowed.
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
This happens, if none of your case branches is reached. So it seems, there is something wrong with how you handle the radio button clicks.

Categories

Resources