I am trying to make a quiz app, so there are 5 radio buttons with possible answers, and only 1 is correct. Then there's a submit button, which has an onClick="clickMethod" to process the submission.
My clickMethod looks like this:
public void clickMethod(View v){
RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1);
int selected = group1.getCheckedRadioButtonId();
RadioButton button1 = (RadioButton) findViewById(selected);
if (button1.getText()=="Right Answer")
Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
else
Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
}
However I can't get the IF statement to work no matter what. If I try to make the toast with
"button1.getText()" as parameter it does print the "Right Answer" string, but for some reason inside the IF statement it's not working, and the ELSE is always executed even when I check the right answer.
Does anyone know what might be happening or a better way to do this?
You're not comparing strings correctly.
The == operator is used when we have to compare the String object
references. If two String variables point to the same object in
memory, the comparison returns true. Otherwise, the comparison returns
false. Note that the ‘==’ operator does not compare the content of the
text present in the String objects. It only compares the references
the 2 Strings are pointing to.
Read here: http://www.javabeginner.com/learn-java/java-string-comparison
You should use the equals String method for String comparison:
public void clickMethod(View v){
RadioGroup group1 = (RadioGroup) findViewById(R.id.radioGroup1);
int selected = group1.getCheckedRadioButtonId();
RadioButton button1 = (RadioButton) findViewById(selected);
if ("Right Answer".equals(button1.getText())) {
Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
}
}
In Java you can't compare Strings with == you have to use equals():
if (button1.getText().equals("Right Answer"))
If you want to compare objects in Java you have to use equals() method and not the == operator
..
if (button1.getText().toString().equals("Right Answer")) {
Toast.makeText(this,"Correct!",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Incorrect.",Toast.LENGTH_SHORT).show();
}
Related
I am trying to create a boolean from an Edit Text field.
I've already converted it into a string but need to make a boolean from the answer. I want to assign the correct answer as 1 and 2 as the wrong answer. If you can give me a tip how to make sure they enter only 1 or 2 that would be great!
This is what i have so far:
public void EnterAnswer(Editable insertAnswer) {
EditText enterAnswer = (EditText) findViewById(R.id.editText_question_six);
String answer = enterAnswer.getText().toString().trim();
}
First and foremost, using an EditText, there is really no way of specifying the values a user can input. Best you can do is to use the input type attribute by setting the input type to "number" as shown below. This way, a user would only be able to input numbers.
android:inputType="number"
You can also use the setError() method of the EditText to display an error if the user inputs a value that is neither 0 nor 1. This is illustrated below:
if(!(editText.getText().toString().equals("0") || editText.getText().toString().equals("1"))){
editText.setError("Wrong input, you can only input 0 or 1");
}
Follow this procedure:
Get the text from your textview
Check whether the text is one or two
assign a value to your boolean variable based on the result above.
Illustration:
public boolean EnterAnswer(Editable answerView){
boolean result = false;
String answer = answerView.getText().toString().trim();
if(answer.equals("1")){
result = true;
}
return result;
}
Following the logic above, the method will only return true if the answer (from the EditText) is one.
I hope this helps... Merry coding!
Basically I need to check that the user input from inputET (an EditText) is equal to the integer, correctAnswer. The problem I'm getting is that "" (which is the text in the EditText field) cannot be converted to an int. Is there any other ways of achieving this or catching the error, I've tried the following code which to my understanding asks if the string in the EditText is not equal to "". Am i going the right way about this or is there an easier way?
// check the input
if (inputET.getText().toString() != "") {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
if the user inputs the same int as the correctAnswer integer then the EditText text is reset to "".
Thanks for any help.
try this:
if (!inputET.getText().toString().equals("")) {
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
Used .equals() method for String comparison.
Based on your requirement I think using TextUtil class will be right way to go for checking the edittext is empty or not.
if(!TextUtils.isEmpty( inputET.getText().toString())){
if (correctAnswer == Integer.parseInt(inputET.getText()
.toString())) {
inputET.setText("");
newSum();
}
}
rather tha doing if (inputET.getText().toString() != "") have a try with
if (!inputET.getText().toString().equals(""))
print the "inputET.getText().toString()" to console and see what it returns. I would hope you need to check the following
String str = inputET.getText().toString()
if (null!=str && str.trim().equals("")) {
if(inputET.getText().toString()!=null&&!(inputET.getText().toString().isEmpty())){
//code for mot null
}else{
//code for null
}
can someone please help making pairs game and using this if statement can someone tell me if theres a bracket or semi colon missing cant see whats missing (pic2.getTag() == beck) is underlined have 4 buttons want to pair or reset them the buttons start with set tag name (boots) this works but no good for non match
This works
if (pic2.getTag() == pic1.getTag()){
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);}
THis doesnt
pic1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
pic1.setTag(beck);
pic1.setBackgroundResource(R.drawable.becks);
if (pic2.getTag() == beck) {
pic1.setVisibility(View.INVISIBLE);
pic2.setVisibility(View.INVISIBLE);
}
}
});
The problem is in the compare operator ==. View tags are Objects (most probably Strings), so you need to compare them with equals.-
if (pic2.getTag().equals(pic1.getTag()))
and
if (pic2.getTag().equals(beck))
This question already has answers here:
How do I compare strings in Java?
(23 answers)
comparison of two Strings doesn't work in android [duplicate]
(4 answers)
Closed 9 years ago.
I am working on a login page in an Android App.
As you know, the app must check if the username and password are valid, and then grant the user access to the application.
I have used the following code:
...
EditText un = (EditText) findViewById(R.id.username1);
EditText pw = (EditText) findViewById(R.id.password1);
String u = un.getText().toString();
String p = pw.getText().toString();
String myUser = "user1";
String myPass = "pass1";
//////// Now on the click of the Login Button:
public void onClickL (View view){
if ( (u == myUser) && (p == myPass)) /////// move to a new activity
else ///////Display a warning message: Try again
}
I entered the correct strings in both editText fields, however i always get the warning message.
I don't understand what is wrong with it.
Please help :)
You should use the equals() method of the String class to compare Strings. The == comparison only compares object references.
if (p.equals("Password")) {
//Do stuff
}
So what you have should be changed to:
if ((u.equals(myUser)) && (p.equals(myPass))) {
// do stuff
}
See here for a lot more information about this often-mixed-up topic: How do I compare strings in Java?
== will do an object comparison between the strings in this situation, and although the value may be the same of the String objects, the objects are not the same. Hence why we use String.equals(string); to compare the value of two string objects.
So
if(u.equals(string)) and p.equal(string)are probably what you are looking for.
Always use String.equals(string) to compare strings. == will compare if the references are equal which doesn't work the way you want for strings.
Since java doesn't have a few modern features, == does not work on strings. Instead, it is a little more complicated.
To check if two string are equal, in the if statement put:
String.equals(otherString)
To compare lengths, use the .length method to compare them, and you could use ==.
Thanks.
I have a method that checks for a null value from an editText on a click of a button like so:
public void myClickHandler09(View chv){
if (text9.equals("")){
text9.setText("0");
}else{
converter(text9);
}}
The
converter(text9);
method is as shown:
public void converter(View view){
switch (view.getId()) {
case R.id.Button09:
RadioButton RadioButtons = (RadioButton) findViewById (R.id.RadioButton901);
float inputValue = Float.parseFloat(text9.getText().toString());
if (RadioButtons.isChecked()) {
text9.setText(String
.valueOf(convertRadioButtons(inputValue)));
}
break;
}}
private double convertRadiobuttons(float inputValue){
return inputValue * 6.4516;
}
The method is larger but here i've only called one radiobutton to shorten it.
Right now though the if statement seems to do absolutely nothing and so non of the rest of the code works. If i remove the method and rename
converter(View view){
to
myClickHandler09(View view){
then the code works and until you enter a null value into the EditText (then it crashes)
What am I doing wrong exactly here?
NOTE: the method name "myClickHandler09" is linked to the button as android:onClick in the xml
You need to do if("".equals(text9.getText().toString())) { ...
The toString() is there because the TextView will return a CharSequence which may or may not be a String.
Right now you are comparing the TextView itself to "", and not the String it is showing.
Edit - As far as the crash goes, you also want to catch the NumberFormatException that Float.parseFloat() throws.
float inputValue = 1.0f; // some default value, in case the user input is bad.
try {
inputValue = Float.parseFloat(text9.getText().toString());
} catch (NumberFormatException e) {
// possibly display a red flag next to the field
}
Why not try
if ("".equals(text9.getText())) {
} else {
}
You essentially have to do a getText() from a TextView and not equals a String with a TextView.
One thing I don't understand with your code is that you call:
converter(text9);
passing in the EditText, but by replacing converter(View view) with the function name myClickHandler09 (like so):
myClickHandler09(View view) {
the button being pressed with call this function (if you defined it in the xml layout onClick paramter).
So to match this behaviour with your current code, try this out:
public void myClickHandler09(View btnView){
if (text9.equals("")){
text9.setText("0");
} else {
converter(btnView);
}
}
I may have missed the point of you're post, but I think that is part of your issue. Also in stead of .equals("") I prefer (text9.toString().length() > 0) just seems a bit more logical, but that's me being a bit pedantic.