Get integer value from edittext

前端 未结 3 340

When I try to run the code below, my program has stops. I want this code to get the value from edittext but it´s not working as I expected it. What am I doing wrong

相关标签:
3条回答
  • 2021-01-25 00:42

    as you can see from your Logcat:

    08-28 19:34:44.790: E/AndroidRuntime(3346): Caused by: java.lang.NumberFormatException: Invalid int: ""

    there was an empty input that couldn't be converted into an int.

    try validating user input.

    0 讨论(0)
  • 2021-01-25 00:47

    The problem seems that when Activity is bringed to front there is no value in EditText. Integer parser don't know how to parse empty String, so Exception is thrown.

    You need to check for existing of text in that EditText before parsing

    final int f = -1; // or other invalid value
    if (from.getText().toString().length() > 0)
        f = Integer.parseInt(from.getText().toString());
    

    Similarly for other EditText

    0 讨论(0)
  • 2021-01-25 00:59

    - Please check the value of EditText, is it a valid integer value or not.

    Try out this code:

    int i = 0;
    
    try{
    
      i = Integer.parseInt(from.getText().toString());
    
    }catch(NumberFormatException ex){
    
      System.out.println("Value at TextView is not a valid integer");
    
    }
    
    0 讨论(0)
提交回复
热议问题