Chemik
Chemik

Reputation: 1479

confirm dialog returns false immediately

This is my code:

index.html:
    ...
      <script type="text/javascript" charset="utf-8" src="main.js"></script>
    </head>
    <body onload="init();"></body>
    ...

main.js:
    function onBackPressed(e) {
        console.log("onBackPressed()");
        var answer = confirm("Do you want to exit?");
        console.log(answer);
        if (answer) {
            navigator.app.exitApp();
        }
    }
    function init() {
        ...
        document.addEventListener("backbutton", onBackPressed, false);
        ...
    }

When I exit application first time, everything seems to be ok. The problem is when I start application next time, confirmation dialog returns false immediately and dialog stay visible. So when I click "OK" nothing will happen.

Here is output from logcat:

04-11 16:16:26.444: D/PhoneGapLog(18356): onBackPressed()
04-11 16:16:26.444: D/PhoneGapLog(18356): file:///android_asset/www/main.js: Line 49 : onBackPressed()
04-11 16:16:26.444: I/Web Console(18356): onBackPressed() at file:///android_asset/www/main.js:49
04-11 16:16:26.584: D/PhoneGapLog(18356): false
04-11 16:16:26.584: D/PhoneGapLog(18356): file:///android_asset/www/main.js: Line 51 : false
04-11 16:16:26.584: I/Web Console(18356): false at file:///android_asset/www/main.js:51

Is this a bug in phonegap or android? Or I'm doing something wrong?

I use Nexus One with android 2.3.6 and phonegap 1.4.1 (version 1.5 have issue with backbutton event).

Upvotes: 1

Views: 1842

Answers (1)

Paul Beusterien
Paul Beusterien

Reputation: 29572

In PhoneGap, confirm is does an asynchronous callback. See the api docs.

The variable answer will always be false because of the immediate return.

The code should look more like:

    // process the confirmation dialog result
function onConfirm(button) {
    alert('You selected button ' + button);
}

// Show a custom confirmation dialog
//
function showConfirm() {
    navigator.notification.confirm(
        'You are the winner!',  // message
        onConfirm,              // callback to invoke with index of button pressed
        'Game Over',            // title
        'Restart,Exit'          // buttonLabels
    );
}

Upvotes: 3

Related Questions