Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android- using addJavaScriptInterface to return a value from Javascript

So i know there are other posts addressing the same issue, and I think I've followed them to the letter but alas to no avail. I'm trying to learn how to get my app to interact with javascript. I just want to be able to return a value from my javascript to my activity.
here is my activity:

public class JSExample extends Activity {
WebView mWebView;
String mString;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    mWebView = (WebView)findViewById(R.id.mWebView);
    mWebView.addJavascriptInterface(new ClsAccessor(), "accessor");
    String html = getAssetsContent("jsinterface.html");

    mWebView.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);

 //   Log.d("YO!", mString);        
}

private String getAssetsContent(String filename){
    .....
}

private void closeStream(BufferedReader stream) {
    .....
}

class ClsAccessor{
    public void setValue(String value){
        JSExample.this.mString = value;
    }
}

Here is the html file loaded by my WebView that contains the javascript i want to run:

    <!DOCTYPE html>

<html>
<head>
    <script language="javascript">
        accessor.setValue('Hello!');
    </script>
</head>
<body>
<h1>Testing</h1>
</body>
</html>

This does not work. When i run the code with "Log.d("YO!", mString);" uncommented I get a null pointer exception, which means that the javascript never assigned a value to mString. what am i doing wrong?

like image 497
aamiri Avatar asked Mar 15 '11 16:03

aamiri


2 Answers

This may not be correct, I will have to double check but it may be due to the reference being lost..

Try making your ClsAccessor reference a member level one..

public class JSExample extends Activity {
    ...
    ClsAccessor _accessor = new ClsAccessor();
    ...
    public void onCreate(Bundle savedInstanceState) {
        ...
        mWebView.addJavascriptInterface(_accessor, "accessor");
        ...

Also if you debug line by line does setValue() ever get called in managed code?

For what it is worth, I have code that is doing as I have described above and the script to managed interface works fine, however I am not in a position currently to test and see if not having a reference to the class also works.

like image 91
Quintin Robinson Avatar answered Nov 03 '22 12:11

Quintin Robinson


Try enabling javascript on your webview :

mWebview.getSettings().setJavaScriptEnabled(true);
like image 2
Anonymous Avatar answered Nov 03 '22 14:11

Anonymous