используя исключения в Android - PullRequest
1 голос
/ 03 сентября 2011

уважают все;

Я новичок в программировании и нахожу барьер, т. Е. При нажатии кнопки, когда в поле «Правка текста» ничего не вводится, конвертируется моя активность в аварию.

Итак, после исследования я получил Попробуй и поймай методы, и это хорошо работает.

     public void clickDiv(View button){
     try{
         EditText Input = (EditText) findViewById(R.id.editext);

        String input = Input.getText().toString();

         String empty = "";

         Float floatInput = new Float (input);

         TextView TextShow = (TextView) findViewById(R.id.textView1);

         String Newinput = floatInput.toString();

         TextShow.setText(Newinput);

         if (answer == 0){

             answer =  (answer+1) / floatInput  ;
         }else{
             answer =  (answer) / floatInput  ;
         }
         String answerString = answer.toString();

         TextShow.setText(answerString);

         Input.setText(empty); }
         catch (Exception e) {
         AlertDialog alertDialog;
        alertDialog = new AlertDialog.Builder(this).create();
          alertDialog.setMessage("Could not find the operand");
         alertDialog.show();
      }}

Но главная проблема в том, что я должен использовать его во всех методах кнопок. Есть ли другой способ избежать этого повторения в коде.

Пожалуйста, помогите ..

1 Ответ

0 голосов
/ 03 сентября 2011

измените код следующим образом. Надеюсь, это поможет вам.

public void clickDiv(View button){
 try{
     EditText Input = (EditText) findViewById(R.id.editext);

    String input = Input.getText().toString();

     //if no input, set the error to the edittext and return
     if(input.trim().length()==0){
        Input.setError("An input is required");
        return;
     }
     String empty = "";

     Float floatInput = new Float (input);

     TextView TextShow = (TextView) findViewById(R.id.textView1);

     String Newinput = floatInput.toString();

     TextShow.setText(Newinput);

     if (answer == 0){

         answer =  (answer+1) / floatInput  ;
     }else{
         answer =  (answer) / floatInput  ;
     }
     String answerString = answer.toString();

     TextShow.setText(answerString);

     Input.setText(empty); }
     catch (Exception e) {
     AlertDialog alertDialog;
    alertDialog = new AlertDialog.Builder(this).create();
      alertDialog.setMessage("Could not find the operand");
     alertDialog.show();
  }}
...