0

I have created a Android WebView App for my browsergame. I use a Javascript-Alert to ask the user if he really wants to reset the score. But I want to use the Android Alert instead of the Javascript Alert. So I have created a Javascript Interface.

public class AlertJSInterface {
private Context context;

AlertJSInterface(Context c) {
    context = c;
}

@JavascriptInterface
public boolean alert(String title, String message) {
    AlertDialog.Builder alert = new AlertDialog.Builder(context);
    alert.setTitle(title);
    alert.setMessage(message);
    alert.setCancelable(true);
    alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });
    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });
    alert.show();

    //want to return true if clicked ok
}

Now i need the return value of the Android Alert inside Javascript. The problem is that the Android Alert has a ClickListener. But how can I get the value an return it to Javascript?

if(AndroidAlert.alert(resetScoreTitle, resetScoreAck) === true) {
    resetAll();
}
Pezcraft
  • 270
  • 3
  • 15

1 Answers1

1

What if you call js function after user click the "OK" button. It's like :

alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
       myWebView.loadUrl("javascript:resetAll();");
    }
});
Randyka Yudhistira
  • 3,612
  • 1
  • 26
  • 41
  • How can I get access to the webview? My Webview is decleared in my MainActivity. – Pezcraft Jun 07 '18 at 11:19
  • err,,setter and getter? pass it with constructor? make it static? anything you like – Randyka Yudhistira Jun 07 '18 at 11:37
  • I tried with static and constructor... `java.lang.RuntimeException: java.lang.Throwable: A WebView method was called on thread 'JavaBridge'. All WebView methods must be called on the same thread. (Expected Looper Looper (main, tid 2) {80fa4a0} called on Looper (JavaBridge, tid 351) {1f7547f}, FYI main Looper is Looper (main, tid 2) {80fa4a0})` – Pezcraft Jun 07 '18 at 13:25
  • ok I solved my exception with [this thread](https://stackoverflow.com/questions/22607657/webview-methods-on-same-thread-error) – Pezcraft Jun 07 '18 at 13:34