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
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top