将字符串从 EditText 转换为整数会导致应用程序在启动前停止工作

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

我正在编写代码,如上所示将字符串转换为整数的部分导致应用程序在我将其上传到手机时在启动之前停止工作。 我已尽可能减少代码。以下代码给出了完全相同的问题。解决方案是什么?

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

这是我的代码:

 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());
        }
    });

}
}

您应该得到 java.lang.NumberFormatException,因为一旦应用程序启动,您就会从 onCreate() 中的编辑文本中获取字符串。这将 return "" 导致行 Integer.parseInt() 中的异常。根据 no2 的用例,您需要相应地移动它。