используя исключения в Android

1

уважал всех;

Я новичок в программировании и нахожу барьер, то есть нажатие кнопки без ввода какой-либо вещи в поле Edittext превращает минную деятельность в катастрофу.

Поэтому после исследования я получил метод Try и catch, и он работает хорошо.

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

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

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

  • 0
    в чем ошибка в локате?
  • 0
    извините за то, что я новичок в Android, поэтому я не знаю, как использовать locat ... пожалуйста, предоставьте предварительные знания об этом.
Показать ещё 2 комментария
Теги:
exception
crash
redundancy

1 ответ

0
Лучший ответ

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

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();
  }}
  • 0
    спасибо :) большое спасибо

Ещё вопросы

Сообщество Overcoder
Наверх
Меню