java – Android – AlertDialog closes itself almost immediately after opening

Question:

The showResults method – shows the AlertDialog , the endOfGame method – closes the Aktivity . When displayed, AlertDialog appears for half a second, and then disappears, how to leave it on the screen?

private void stopGame() {
    showResults();
    endOfGame();
}

private void showResults() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.results);
    builder.setMessage("Message");
    builder.setNegativeButton(R.string.OK, null);
    builder.create().show();
}

The application gets to the stopGame() method from AsyncTask , maybe there is an error somewhere here?

private class TimerAsyncTask extends AsyncTask<Void, Integer, Void>{
    private int time;

    public TimerAsyncTask(int time) {
        this.time = time;
    }

    @Override
    protected Void doInBackground(Void... params) {
        while (time > 0) {
            SystemClock.sleep(1000);
            time--;
            publishProgress(time);
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        chronometrView.setText(values[0].toString());
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        stopGame();
    }
}

Answer:

I will join Abrog Petrovich's comment.

In the showResults() method, you call the builder to create the dialog box. The line AlertDialog.Builder builder = new AlertDialog.Builder(this); essentially says that the builder will use this activity (inflate it, use a style, etc.), so you create a dialog box regarding this activity.

But you're at endOfGame(); As I understand it, you close this activity, and the dialogue is closed – accordingly. Two ways of solving come to mind:

1.Indeed, move the closing Activity to those of your endOfGame () method; in the AlertDialog, let it fire when it is closed, for example, well, or do the Yes / No logic. Let the user accept the choice.

2. You can create a Dialog box in a new Acitivity, or open a new Actvity in the form of a dialog box, there are many options here, but you need to see what happens in the endOfGame () method.

Scroll to Top