2016-08-21 1 views
1

コードを処理していて、上に示したように文字列を整数に変換する部分は、アプリケーションが起動する前に動作を停止する原因となります。私はそれをモバイルにアップロードします。 私はできるだけコードを減らしました。次のコードはまったく同じ問題を与えています。解決策は何でしょうか?EditTextの文字列を整数に変換すると、アプリケーションが起動する前にアプリケーションが停止する

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

} 
} 

答えて

4

ので、すぐにアプリがあなたがonCreate()でのEditTextから文字列を取得している起動するとあなたはjava.lang.NumberFormatExceptionを取得する必要があります。これにより""が返され、Integer.parseInt()という例外が発生します。 no2のユースケースに応じて、それに応じて移動する必要があります。

+0

コードを編集して再掲載することはできますか? – Aloweiwi

+0

このようなものint no2 = 0; try {no2 = Integer.parseInt(no); } catch(Exception e){} – Ramit

+0

@Aloweiwiこのように^はいの場合は、 'Exception'を' NumberFormatException'に変更してください。 – Shaishav

関連する問題