3

Objective: I would like to take a JSON String and pass it into JavaScript function that is in an Android WebView.

What I am doing: I need to get data out of an android SQLite database, turn it into JSON, pass it into the browser, and use a chart to display the data. I have accomplished all of this, except I cannot figure out how to pass the JSON into the JavaScript function/ into the browser.

So here I have a js function in my html header:

        <script type="text/javascript">
            function returnData(json) {
                 //Do something in here with the JSON String
            }
        </script>

And then in my Java I have the javascript interface that I will cause the JS "returnData" function to be executed.

final class DemoJavaScriptInterface {
        DemoJavaScriptInterface() {
        }

        public void clickOnAndroid() {
            mHandler.post(new Runnable() {
                public void run() {
                    json = "[{ country: \\\"USA\\\", visits: 4252 },{ country: \\\"China\\\", visits: 1882 },{ country: \\\"Japan\\\", visits: 1809 }]";
                    mWebView.loadUrl("javascript:returnData("+json+")");

                }
            });
        }
}

Now if I JUST want to execute the "returnData" function it gets executed just fine. (Below works)

mWebView.loadUrl("javascript:returnData()");

But if I try and push a string into the function (like below), it just 'fails'... unfortunately I don't have much experience with JS, and so I have no idea why the JS function never gets called.

mWebView.loadUrl("javascript:returnData("+json+")");

I am looking for ANY way to push data into a java script function, or somewhere in the DOM I can store the data (i guess) where the JS function could get the data from.

Any help would be appreciated, thanks.

1 Answer 1

4

I needed to add single quotes around the JSON string.

mWebView.loadUrl("javascript:returnData('"+json+"')");
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing solution !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.