Reputation: 35276
I am working on a project on embedding web app on android, following the WebView demo, however I need to call on a gwt function when the javascript function 'wave' is called back by the android app:
<html>
<script language="javascript">
/* This function is invoked by the activity */
function wave(s) {
// call a gwt function and
// pass 's' to the gwt function
}
</script>
<body>
<!-- Calls into the javascript interface for the activity -->
<a onClick="window.demo.clickOnAndroid()"><div style="width:80px;
...
</div></a>
</body>
</html>
Any ideas on how to achieve this?
Upvotes: 1
Views: 4728
Reputation: 11625
You will need to export any method you want to call from javascript into javascript global scope. What this means is that you cannot call an arbitrary java method from hand-written javascript. You must plan ahead and expose the necessary methods in javascript scope.
The process is pretty simple:
An example from GWT JSNI documentation with additional comments:
package mypackage;
public MyUtilityClass
{
//Method to be called from javascript, could be in any other class too
public static int computeLoanInterest(int amt, float interestRate,
int term) { ... }
//This method should be called during application startup
public static native void exportStaticMethod() /*-{
//the function named here will become available in javascript scope
$wnd.computeLoanInterest =
$entry(@mypackage.MyUtilityClass::computeLoanInterest(IFI));
}-*/;
}
EDIT:
Passing parameters to Java method:
When you call Java method that takes parameters, from javascript, you need to use a specific syntax:
[instance-expr.]@class-name::method-name(param-signature)(arguments)
For example, calling a static method that takes a String parameter will look like this:
@com.google.gwt.examples.JSNIExample::staticFoo(Ljava/lang/String;)(s);
Note that as we are calling a static method, 'instance-expr.' is omitted. The rest of the code is fully qualified class name followed by ::
and method name. The Ljava/lang/String;
after method name, specifies that we need to call the method that takes a String object as parameter. Finally s
is the actual value for that parameter.
Remember that param-signature, Ljava/lang/String;
in our case, in the syntax uses JNI type signature specs, and is required by GWT compiler to select the correct method even if there are multiple overloaded methods with the same name. A param-signature
is required even if the method is not overloaded.
Upvotes: 6
Reputation: 80340
GWT is compiled down to javascript and all function/object names are minified, so they became unreadable and unknown so you can not call them directly from Javascript. To work around this you need to check out how to Call a Java Method from Handwritten JavaScript.
Upvotes: 1
Reputation: 14863
Use Javascript Overlay Types!
Look here:
Can't descib it any better!
Upvotes: 0