Adil Waqar Adil Waqar - 1 year ago 75
Javascript Question

Returning String value from Android Activity to JS function

i am trying to return a string value to JS function from android activity.
the JS function first calls the android activity method and that method then return a string value but its not working ... take a look on code

<script type="text/javascript">
function PicMethod(){

var path = activity.getPic();


Here is the android activity method

public String getPic()
String temp="abcd";
return temp;

Answer Source

Depending on your use case, there are different ways of accomplishing this. The difficulty lies in that you want to do things in the onload method.

If it is possible to pass in the string after the page is loaded, you could use

String jsString = "javascript:addData('" + theString + "');");

if you really need the data accessible on the onload method of the page, you could modify the url called to to include query data if possible. Something like:

String urlWithData = yourUrl + "?data=" + theString;

and then use standard javascript to parse to get the data.

Finally, if you can't modify the URL for some reason, you can use a callback object to let the javascript get the value:

private class StringGetter {
   public String getString() {
       return "some string";

and then when config your webView with this callback before loading the url:

webView.addJavascriptInterface(new StringGetter(), "stringGetter");

and in the onload method of the page you could use:

var theString = stringGetter.getString();

Hope this helps!


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download