addJavascriptInterface doesnt return a string value in Android
I'm using following code to extract a string variable in my JavaScript file in Android:
This is my JavaScript file:
<script language="javascript">
//EDIT:
clsVariable = "vikrant";
function refuseClick(){
clsVariable = "vikrant";
refuse.performClick();
document.getElementById("no").value = "Refuse";
}
</script>
<button type="button" id="no" onClick="refuseClick();">Je refuse</button>
</div>
</body>
</开发者_StackOverflow社区html>
In my Android class I'm writing following method on a button click. This button click event I'm calling from JavaScript file:
refuse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.v(LOG_TAG, "variable=" + clsVariable); //This shows me null
}
});
wbvw = (WebView) findViewById (R.id.webvw);
wbvw.setWebViewClient(new HelloWebViewClient());
wbvw.getSettings().setJavaScriptEnabled(true);
WebSettings ws = wbvw.getSettings();
ws.setJavaScriptEnabled(true);
wbvw.addJavascriptInterface(clsVariable, "clsVariable");
wbvw.loadUrl("http://www.sbc.co.in/projects/AndroidTest.html");
}
I'm new to this platform as well as writing JavaScript.
What is it that I'm doing wrong?
It looks like you misuse the addJavascriptInterface(). The method allows you to expose some java object to javascript. You can then invoke methods of the object withing javascript and those invocations will be transferred to 'real' java object. For example, you can declare such a nested class to access your java field:
class ClsAccessor {
public void setValue(String value){
YourOuterClassName.this.clsVariable = value;
}
}
Then pass an instance of the class into addJavascriptInterface() method:
wbvd.addJavaScriptInterface(new ClsAccessor(), "accessor");
Then, to set a value to your class field you need to invoke a setValue() method on accessor
object from javascript (for example in on click handler):
accessor.setValue('vikrant');
That will result in call of java 'setValue()' and your field variable will be set.
Note that snippets can be not exact, I've type them directly from my head :) But you should get the principle. Hope that helps.
精彩评论