Problem casting variables in Java: NumberFormatException: For input string: ""

I was starting with Android, but when performing something that in Java has never given me problems and when launching it in an Android App, I have skipped quite a few errors when running it, because compiling does it without problems.

The exercise I'm trying to perform is a very simple calculator, I take two values from two different TextViews, sum them up and display the result on a screen.

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void calcularResultado(View view) {

        TextView cuadroNum1, cuadroNum2, resultado;

        cuadroNum1 = (TextView) findViewById(R.id.tNum1);
        cuadroNum2 = (TextView) findViewById(R.id.tNum2);
        resultado = (TextView) findViewById(R.id.resultado);


        int num1 = 0, num2 = 0, aux;


        num1 = Integer.parseInt(cuadroNum1.getText().toString());
        num2 = Integer.parseInt(cuadroNum2.getText().toString());

        resultado.setText(String.format(""+ (num1 + num2) ));
    }
}

After doing several tests I realized that the application is it closed by emulating it with casteos, as you can see in the code.

I don't know if on Android castings can't be done like this, because TextViews return "Char Sequences", but passing them to String gives no errors until I try to pass them to variables of type int, or if I should use another alternative element to the TextView if I want to work with digits.

Code the error:

       --------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.pabloperezaradros.calculadora, PID: 2740
                  java.lang.IllegalStateException: Could not execute method for android:onClick
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                      at android.view.View.performClick(View.java:5610)
                      at android.view.View$PerformClick.run(View.java:22260)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.reflect.InvocationTargetException
                      at java.lang.reflect.Method.invoke(Native Method)
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                      at android.view.View.performClick(View.java:5610) 
                      at android.view.View$PerformClick.run(View.java:22260) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
                   Caused by: java.lang.NumberFormatException: For input string: ""
                      at java.lang.Integer.parseInt(Integer.java:533)
                      at java.lang.Integer.parseInt(Integer.java:556)
                      at com.pabloperezaradros.calculadora.MainActivity.calcularResultado(MainActivity.java:26)
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
                      at android.view.View.performClick(View.java:5610) 
                      at android.view.View$PerformClick.run(View.java:22260) 
                      at android.os.Handler.handleCallback(Handler.java:751) 
                      at android.os.Handler.dispatchMessage(Handler.java:95) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6077) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
 2
Author: Jorgesys, 2016-10-08

3 answers

You have this problem when calling the method onClick() having the following as the main problem:

Caused by: java.lang.NumberFormatException: For input string: ""

And occurs when you try to convert a non-numeric string value to int, in this case an empty string, "".

You can use a function to first check if the value is numeric and then use Integer.parseInt() to perform the conversion:

public static boolean isNumeric(String valor) {
 try {
double d = Double.parseDouble(valor); 
} catch(NumberFormatException e) { 
return false; 
} 
return true;
 }

En based on the above method we can use a ternary operation to perform the conversion:

int num1 = 0, num2 = 0, aux;
num1 = isNumeric(cuadroNum1.getText().toString())? Integer.parseInt(cuadroNum1.getText().toString()):0 ; 
num2 = isNumeric(cuadroNum2.getText().toString())? Integer.parseInt(cuadroNum2.getText().toString()):0 ; 

When the value is not numeric the result will be 0, you can define the default value.

 4
Author: Jorgesys, 2016-10-10 19:26:01

Inner operations with integers should be in parentheses, as in Java. you must also declare your components in the onCreate{[2] method]}

TextView cuadroNum1, cuadroNum2, resultado;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cuadroNum1 = (TextView) findViewById(R.id.tNum1);
    cuadroNum2 = (TextView) findViewById(R.id.tNum2);
    resultado = (TextView) findViewById(R.id.resultado);
}

 public void calcularResultado(View view) {
    int num1 = 0, num2 = 0, aux;
    num1 = Integer.parseInt(cuadroNum1.getText().toString());
    num2 = Integer.parseInt(cuadroNum2.getText().toString());

    resultado.setText(String.format(""+ (num1 + num2) ));


 }
 1
Author: Dev. Joel, 2016-10-09 01:17:40

Add this good I'm using 2 EditText, 1 TextView (result) and 1 button

public class ejemplo extends AppCompatActivity {
private EditText editorTexto1, editorTexto2;
private TextView vistaTexto;
private Button boton;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.ejemplo_activity);
    editorTexto1    = (EditText)findViewById(R.id.editText1);
    editorTexto2    = (EditText)findViewById(R.id.editText1);
    vistaTexto      = (TextView)findViewById(R.id.textView);
    boton           = (Button)findViewById(R.id.button);
}

@Override
protected void onResume() {
    super.onResume();
    boton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            calcularResultado();
        }
    });
}

public void calcularResultado() {
    int num1 = 0, num2 = 0, resultado = 0;

    num1 = Integer.parseInt(editorTexto1.getText().toString());
    num2 = Integer.parseInt(editorTexto1.getText().toString());
    resultado = num1 + num2;

    vistaTexto.setText(String.valueOf(resultado));
}}
 0
Author: marlonpya, 2016-10-10 19:26:40