0

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();
  alert(path); 
    }

    </script>

Here is the android activity method

 public String getPic()
    {
 String temp="abcd";
return temp;
    }
3
  • how you are adding to js interface? Commented Mar 20, 2014 at 11:25
  • What exactly isn't working? I notice there is a typo in your javascript code: alret (path) should be alert(path); Commented Mar 20, 2014 at 11:26
  • sorry that was a typing mistake i didn't copied it from code.. Commented Mar 20, 2014 at 11:29

1 Answer 1

1

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 + "');");
webView.loadUrl(jsString);

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;
webView.loadUrl(urlWithData);

and then use standard javascript to parse window.location.search 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!

Regards:@albin

Sign up to request clarification or add additional context in comments.

6 Comments

actually the thing is that i am calling PicMethod() on html button click and this method calls getPic() in get pic i open android camera activity and save the path of picture user just took and return it to JS function ...
what is the type of your image ?
path of picture you are saving right ?? so you can send that as a string. you try that?
no error in LogCat and no alert showing in response . .
are you sure about the server. Do you test that in some browser ?
|

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.