Binding JavaScript code to Android code

I try to call a method in java from javascript, but this does not happen when I run the application in the emulator, the application stops when it is supposed to call the method in java.
here is the java code:

import android.os.Bundle; import android.webkit.WebView; import com.phonegap.*; public class App extends DroidGap { WebView webView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webView = new WebView(this); webView.addJavascriptInterface(new message(), "Show"); super.loadUrl("file:///android_asset/www/index.html"); } class message { String msg() { return "Hello World!!"; } } } 


here is javascript:

 <script type="text/javascript"> { alert("Start"); alert(Show.msg()); alert("End"); } </script> 

He shows the first warning, but after that nothing can help?

+4
source share
2 answers

Your problem is that you are half using PhoneGap and half are not. You create a separate WebView class from PhoneGap. The WebView class that you added Show is never used. Instead, the WebView class, which is a member of super ( DroidGap ), is.

You must do one of two things.

  • Use the PhoneGap plugin structure (see examples here )
  • Do not use PhoneGap at all, and you have a class that looks more like the following:

     public class act extends Activity { WebView webView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); webView = new WebView(this); webView.getSettings().setJavaScriptEnabled(true); // Set JS alert() hook webView.setWebChromeClient(new WebChromeClient() { public boolean onJsAlert(WebView view, String url, String message, JsResult result) { return false; } }); webView.loadUrl("file:///android_asset/www/index.html"); // Add JS libraries webView.addJavascriptInterface(new message(), "Show"); } class message { public String msg() { return "Hello World!!"; } } } 

Note that the msg method must be public

+4
source

Why not just use AlertDialog?

 private void showDialog(int title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(title); builder.setMessage(message); builder.setPositiveButton(R.string.ok_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); builder.show(); } 
0
source

All Articles