java.lang.NumberFormatException: Invalid int: “” : Error

 ̄綄美尐妖づ 提交于 2019-12-02 02:00:54
Ravi Rupareliya

put these lines inside onClick()

final  String height = e1.getText().toString();
final int a = Integer.parseInt(height);

You are fetching value of e1 in onCreate(), while you want it when user click on button

Also need to check whether height is having any value or not, check Stuluske's answer for this

You are trying to parse an empty String ( "" ) to a numerical value, but "" is not a numerical value.

Make sure you set it to required, or check for emptiness before trying to parse it.

final int a = !height.equals("")?Integer.parseInt(height) : 0;

for instance.

EDIT:

If you have added spaces, so it would be " ";

height = height.trim();
final int a = !height.equals("")?Integer.parseInt(height) : 0;

should do the trick.

There's no value yet when onCreate() runs. Move the getText() and parseInt() inside your click listener to read and parse the value when you have entered something.

put a check before doing Integer.parseInt like

final int a = (height == null || height.trim().equal("") ? 0 : Integer.parseInt(height));

Also you need to add this code for getting the height value from edittext inside onclick listener as when in OnCreate control will not have any value apart you set some default value in layout.xml as it is just created

you should get the values inside a method so that your app does not try to assign the values immediatly you are creating them check below how am doing it using kotlin

     myresult = findViewById<TextView>(R.id.txtresult)
     val1 = findViewById<EditText>(R.id.valone)
     val2 = findViewById<EditText>(R.id.valtwo)

after getting the field use method as below

    fun calculate() : Int {

        var value1 = Integer.parseInt(val1.text.toString())
        var value2 = val2.text.toString().toInt()
        var result : Int

        when (opType){

            "+" ->{result = value1 + value2
                    return result
                 }
            "-" ->{result = value1 - value2
                return result
            }
            "*" -> {result = value1 * value2
                return result
            }
            "/" -> {result = value1 / value2
                return result
            } else -> result = 20

        }

        return result
    }

     btn.setOnClickListener{

        println(calculate().toString())
        myresult.text = calculate().toString()


    }

for those moving to kotlin and finding the same error I hope this code will help you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!