简体   繁体   中英

Alertdialog pop inside a while statement

I have an alert box where a user can enter a persons name presses Ok and the box comes up again if there is another persons name to be entered. The code below does work, but if there is a high number of people to be added (like 50) my tablet crashes and resets. I'm pretty sure this happens because there are 50 dialog boxes drawn on top of each other and my tablet runs out of memory and shuts down.

How can I get it to wait for the user to input the name and then run again?

        while(i < number)
        {
            final AlertDialog.Builder alert = new AlertDialog.Builder(this);
            final EditText input = new EditText(this);
            alert.setMessage("Enter persons name (" + (number - i) + " names left to enter)");
            alert.setView(input);
            alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int whichButton) 
                {
                    String value = input.getText().toString().trim();
                    setUp(value);
                }
            });
            alert.show();
            i++;
        }

Yes, you are showing all alerts at the same time.

Pseudo code to avoid this problem:

function showAlerts(Integer i) {
    if (i < number) {
        // Build the alert and display it
        alert.setPositiveButton(..., new OnClickListener() {
            setup(...);
            showAlerts(i+1);
        }
    }
}

showAlerts(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM