There are few SO questions and other articles about calling Java class method from Javascript but all of them deals with java method with return type void.
Here is what I am trying to achieve: There are 2 strings to be displayed in WebView - say Yes and No. But they needs to be localized and hence I want to get the string value from Java method rather than using multiple JS for each locale.
Here's the code sample: Java class
onCreate(){
//Some code
contentWebView.addJavascriptInterface(new CalculatorJavaScriptCallInterface(), "calculatorjavascriptcallinterface");
//Some code
}
String localizedString = "";
private class CalculatorJavaScriptCallInterface {
CalculatorJavaScriptCallInterface() {
}
@JavascriptInterface
public String getLocalizedString(final int stringId) {
localizedString = getResources().getString(stringId);
Toast.makeText(getActivity(), "localizedString :: " + localizedString, Toast.LENGTH_SHORT).show();
return localizedString;
}
}
Javascript file
function Checkboxpicker(element, options) {
//Some code
this.options = $.extend({}, $.fn.checkboxpicker.defaults, options, this.$element.data());
}
$.fn.checkboxpicker.defaults = {
//EXISTING STRINGS
//offLabel: 'No',
//onLabel: 'Yes',
offLabel: window.calculatorjavascriptcallinterface.getLocalizedString("Consult.JSSupport.checkbox.selected"),
onLabel: window.calculatorjavascriptcallinterface.getLocalizedString("Consult.JSSupport.checkbox.notSelected"),
};
I am getting blank string as output when I run above code.
Here are some notes:
- This Javascript is being used appropriately as it works if I use hard-coded strings
- Respective stings have been defined in
string.xml - I tried using
calculatorjavascriptcallinterfacein Camel case and lower case both - I tried with and without
window.to call Java method - Tried returning hard-coded value from Java method - IT IS WORKING THIS WAY
Any suggestions will be appreciated. Thanks in advance!
EDIT I'm getting following error even though the string is present in strings.xml:
No package identifier when getting value for resource number 0x00000000
android.content.res.Resources$NotFoundException: String resource ID #0x0
setJavaScriptEnabled? Is yourgetLocalizedStringgetting called?