Question

respected all;

I am new to programming and find a barrier i.e on clicking the button without any thing being inputted in the Edittext box converts mine activity to crash.

So after research i got Try and catch methods and it works good .

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

But the main problem is that i have to use it in all the button methods. is there any other way other to avoid this repetition in code.

Please help..

Was it helpful?

Solution

modify the code like this. Hope it helps you.

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();
  }}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top