Unable to start activity: invalid int [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Please guys I am writing this android app, but I'm getting a run time error in the logCat : java.lang.RuntimeException: Unable to start activity: java.lang.NumberFormatException: Invalid int: ""
public class MainActivity extends Activity{
EditText et;
Button guess, randomize;
TextView tv1, tv2;
int num1;
int num2;
int userAns;
int answer;
final Random rand = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
et = (EditText) findViewById(R.id.editText1);
tv1 = (TextView) findViewById(R.id.textView1);
tv2 = (TextView) findViewById(R.id.textView2);
guess = (Button) findViewById(R.id.btnSubmit);
randomize = (Button) findViewById(R.id.button1);
randomize(rand);
tv2.setText(num1 + " + " + num2);
userAns = Integer.parseInt(et.getText().toString());
guess.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
answer = num1 + num2;
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
}
});
randomize.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
randomize(rand);
}
});
}
private void randomize(final Random rand) {
num1 = 1 + rand.nextInt(50);
num2 = 1 + rand.nextInt(50);
}
}

numberFormatException is usually caused by a string to int conversion going wrong. I'm suspecting this line.
userAns = Integer.parseInt(et.getText().toString());
since it's not initialized with text yet.
wrap it in a try/catch
EDIT:
How to fix
I would recommend moving
userAns = Integer.parseInt(et.getText().toString());
inside guess.setOnClickListener like so:
guess.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
answer = num1 + num2;
try {
userAns = Integer.parseInt(et.getText().toString());
if (userAns == answer) {
tv1.setText("Correct... The Answer is " +answer);
} else {
tv1.setText("wrong");
}
} catch(Exception e) {
// output error that 'et' field is emtpy or doesnt contain a number
}
}
});

et is empty unless you set it to a default value. As such, et.getText will return "", which is not a valid number so parseInt will throw an exception. You need to wait to get that text until the user has pressed the guess button and get it then.

Related

How to finish array question, it always repeating

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.

Java/Android : First tiny app answer always "false"

I try to create my first tiny app but i have a problem.
My tiny math app always say my answer is false.I don't understand why.
This is my first app, i don't know where i'm wrong.
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
Answer always "False"
I'm a new student in the dev world.
The problem with code is that you are comparing string with integer, that's why it always returns false as java is strictly typed language.
problem code:
if(str.equals(result)){...}
possible solutions:
if( str.equals(""+result)){...}
or
str.equals(String.valueof(result)) // best solution
or
if(result==Integer.parseInt(str)){...}
Here is corrected code:
private TextView problem;
private EditText question;
private Button button;
private TextView reponse;
private int aleatoire = new Random().nextInt(61) + 20;
private int aleatoire2 = new Random().nextInt(48) + 20;
private int result = aleatoire + aleatoire2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
problem = (TextView) findViewById(R.id.problem);
question = (EditText)findViewById(R.id.editText);
button = (Button)findViewById(R.id.button);
reponse = (TextView)findViewById(R.id.resultat);
problem.setText("Result = "+aleatoire+"+"+aleatoire2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String str=question.getText().toString();
if (str.equals(""+result)) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}
}
});
As azurefrog comment says, you're comparing a String to an int. You will need to transform str to an int or result to a String. You can for example do:
String str=question.getText().toString();
if (str.equals(String.valueOf(result))) {
reponse.setText("True !");
} else {
reponse.setText("False !");
}

App Score from checkboxes

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.

Set empty edittext value to zero

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.

Program crashes with empty text field

I need help trying to fix my code. I thought it was simple (probably is) but I can't get it. I am have a simple adding calculator. It works fine, but if I leave 1 or both Number text fields empty, the program crashes.
I have my if statement, but apparently I am not telling it to do the right thing.
public class MainActivity extends Activity {
Double firstNum, secondNum, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.txtFirst);
final EditText second = (EditText) findViewById(R.id.txtSecond);
final TextView answer = (TextView) findViewById(R.id.txtAnswer);
Button calc = (Button) findViewById(R.id.btnCalc);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// convert pulled info to double using variable names
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
if (first == null || second == null)
{
Toast.makeText(MainActivity.this, "Please Enter value", Toast.LENGTH_SHORT).show();
}
else {
// add numbers
answerNum = (firstNum + secondNum);
//set format
DecimalFormat total = new DecimalFormat ("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}
You have exception because of line: Double.parseDouble(second.getText().toString()), it cannot parse empty string to double, so you should add some validation code.
If you want to validate edittext means try this following code it will work fine.
public class MainActivity extends Activity {
double firstNum = 0;
double secondNum = 0, answerNum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText first = (EditText) findViewById(R.id.editText1);
final EditText second = (EditText) findViewById(R.id.editText2);
final TextView answer = (TextView) findViewById(R.id.textView1);
Button calc = (Button) findViewById(R.id.button1);
calc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (first.getText().toString().equals("")
|| second.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please Enter value",
Toast.LENGTH_SHORT).show();
} else {
firstNum = Double.parseDouble(first.getText().toString());
secondNum = Double.parseDouble(second.getText().toString());
answerNum = (firstNum + secondNum);
DecimalFormat total = new DecimalFormat("###,###,###.##");
answer.setText("Answer is " + total.format(answerNum));
}
}
});
}
}

Categories