3

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" />
4
  • 2
    Its because of there is no value in e1. First on click do validation and then convert to interger
    – Pavya
    Jan 22, 2016 at 12:54
  • 2
    e1 contains blank text, hence the issue Jan 22, 2016 at 12:54
  • 1
    you need to use gettext() inside onclick()
    – karan
    Jan 22, 2016 at 12:57
  • @jipr311 OP having problem with NumberFormatException not null pointer exception.
    – SatyaTNV
    Jan 22, 2016 at 12:58

5 Answers 5

12

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.

6
  • 1
    what if I have added 2 spaces
    – Pavya
    Jan 22, 2016 at 12:54
  • I've added the response to that in the answer.
    – Stultuske
    Jan 22, 2016 at 12:56
  • 1
    This will avoid the crash, yes, but does not allow OP to actually read the entered value since the code runs too early.
    – laalto
    Jan 22, 2016 at 12:58
  • The gettting value must be in onClick Its because its triggered when you click a button after entering some value to the text field. and op can also add a check !TextUtils.isEmpty(string) Jan 22, 2016 at 12:58
  • True, then again, the question is about the NumberFormatException.
    – Stultuske
    Jan 22, 2016 at 12:59
5

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

3
  • Possibly because you did not consider that height may not be a number. However, I upvoted this answer, because it is useless to use getText() during onCreate(). Jan 22, 2016 at 13:01
  • @LordAnomander ohh yes, i forget that point, will update my answer
    – Ravi
    Jan 22, 2016 at 13:01
  • Thankyou :) I just forget it Jan 22, 2016 at 13:05
2

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.

0

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.