Question

else if in my codes. Basically i have several condition to fulfill before i can start drawing circles. However upon execution of the program, the popup dialog appears several times even if the condition is met. I would only want a dialog to appear once if there is a message to display. Am i doing it the right way? PLease advice.

my codes are as follows:

if (MainActivity.isClicked() == true) {

    if (condition 1) {

               canvas.drawCircle(x, y, radius, redPaint);
               invalidate();

    } else if (condition 2) {
                 canvas.drawCircle(x, y, radius, bluePaint);
               invalidate();        

    } else if (condition 3){
                msg = "green not available";

    } else {
                msg =" please add more colors";
    }
AlertDialog.Builder builder = new Builder(getContext());
            builder.setTitle("Warning").setMessage(msg);
            builder.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
                                  public void onClick(DialogInterface di,int i) {

                                 }

        });

        builder.create().show();
    }// if
Was it helpful?

Solution

Create an method for showing alert when condition meet as:

private void showAlert(String str_mesg){

AlertDialog.Builder builder = new Builder(getContext());
builder.setTitle("Warning").setMessage(str_mesg);
builder.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface di,int i) {

            }
    });
}

Call showAlert in if-else ladder to show alert:

    ......
    } else if (condition 3){
           msg = "green not available";
           showAlert(msg);

    } else {
         msg =" please add more colors";
         showAlert(msg);
    }
   .....
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top