Farrukh Faizy
Farrukh Faizy

Reputation: 1235

java.lang.NumberFormatException: Invalid int: "" : Error

I am doing some calculation but unable to parse a string into int or even in float.I searched for solution and i read it somewhere there must be a empty string but i checked my editText using

log.v("Valuee",e1.getText().toString());

and its print the values prove that string is not empty.. What i am missing ?

Here is logcat

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.farrukh.bmi/com.example.farrukh.bmi.Main2Activity}: java.lang.NumberFormatException: Invalid int: "" at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) at android.app.ActivityThread.access$800(ActivityThread.java:135) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.NumberFormatException: Invalid int: "" at java.lang.Integer.invalidInt(Integer.java:137) at java.lang.Integer.parseInt(Integer.java:358) at java.lang.Integer.parseInt(Integer.java:331) at com.example.farrukh.bmi.Main2Activity.onCreate(Main2Activity.java:31) at android.app.Activity.performCreate(Activity.java:5231) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)  at android.app.ActivityThread.access$800(ActivityThread.java:135)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:136)  at android.app.ActivityThread.main(ActivityThread.java:5017)  at java.lang.reflect.Method.invokeNative(Native Method) 

Here is MainActivity.java

 public class Main2Activity extends AppCompatActivity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);

          final   Button b = (Button) findViewById(R.id.button);
          final   EditText e1 = (EditText) findViewById(R.id.editText2);
          final   TextView text = (TextView) findViewById(R.id.textView4);
          final  String height = e1.getText().toString();


          final int a = Integer.parseInt(height); //got error while parsing

     b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {


                 //   Log.v("EditText",e1.getText().toString());

                }
            });


        }


    }

Here is activity.xml

<Button
        android:layout_width="132dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
         android:layout_gravity="center_horizontal"
        android:text="CLICK"
        android:clickable="true"
        android:id="@+id/button"/>

<EditText
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="20dp"
        android:gravity="center" />


    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView4"
        android:layout_gravity="center_horizontal"
        android:gravity="center"
        android:layout_marginTop="20dp"
        android:textColor="#3b9ff0" />

Upvotes: 3

Views: 30541

Answers (5)

Austine Gwa
Austine Gwa

Reputation: 812

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

Upvotes: 0

Ravi
Ravi

Reputation: 35549

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

Upvotes: 5

Rajen Raiyarela
Rajen Raiyarela

Reputation: 5636

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

Upvotes: 0

Stultuske
Stultuske

Reputation: 9427

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.

Upvotes: 12

laalto
laalto

Reputation: 152817

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.

Upvotes: 2

Related Questions