Search code examples
javaandroidandroid-edittextgettext

converting the string from an EditText into an integer causes application stop-working before it starts


I am working on a code and the part of converting the string into and integer as shown above is causing the application to stop working before it starts when I upload it to the mobile. I have reduced the code as minimum as possible. the following code is giving the exact same problem. What would the solution be?

  String no=edttxt.getText().toString();       //this will get a string
  int no2=Integer.parseInt(no);              //this will get a no from the 

This is my code:

 public class MainActivity extends Activity {
    TextView txtview;
    EditText edttxt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtview=(TextView)findViewById(R.id.textView);
    edttxt=(EditText)findViewById(R.id.edittxt);

    String no=edttxt.getText().toString();       //this will get a string
    int no2=Integer.parseInt(no);              //this will get a no from the string

    Button btn=(Button)findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            txtview.setText(edttxt.getText());
        }
    });

}
}

Solution

  • You should be getting a java.lang.NumberFormatException because as soon as the app starts you are getting the string from edittext in onCreate(). This would return "" which would cause the exception in the line Integer.parseInt(). Depending on your use case for no2, you need to move it accordingly.