I'm trying to write some code for interaction between js and android's WebView.
A already read Building Web Apps in WebView
My goal now is getting some data from js. The appropriate example, that i found there is
Android code:
public class WebAppInterface {
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(String toast) {
Toast.makeText(getContext(), toast, Toast.LENGTH_SHORT).show();
}
}
HTML + JS:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
And ... it works perfect with primitive data (Strings, integers ..) and also arrays of primitive data
But when i try to pass complex objects, as i list below, it cause Java exception "Uncaught Error: Java exception was raised during method invocation", source: file:///android_asset/test.html (34)
:
Android code:
private class Data {
String a;
String b;
}
public class WebAppInterface {
/** Show a toast from the web page */
@JavascriptInterface
public void showToast(Data data) {
Toast.makeText(getContext(), data.a + data.b, Toast.LENGTH_SHORT).show();
}
}
HTML + JS:
<input type="button" value="Say hello" onClick="showAndroidToast()" />
<script type="text/javascript">
var data = {a: "Hello ", b: "world"};
function showAndroidToast() {
Android.showToast(data); // exception
}
</script>
I suppose this occurs because WebView can't define the way to translate JS data types to the Java ones (except of primitive ones).
Can you advise me the way to pass complex data types between JS and android's WebView?