0

i'm having problem in passing data/variable from android to javascript.here is my code.

WebView webview = (WebView) findViewById(R.id.webview_graph);
    WebSettings webSettings = webview.getSettings();
    webSettings.setJavaScriptEnabled(true);
    String temp = "yoolod";
    webview.loadUrl("file:///android_asset/test.html");
    webview.loadUrl("javascript:sample(\""+temp+"\")");

in test.html

<!DOCTYPE html>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">

 function sample(var){ //this is line 10
       document.write (var);
       //echo var;
 }

</script>
</head>

<body>
</body>
</html>

I always have this, error and can't find solution yet. Hope you can help me.

"Uncaught ReferenceError: sample is not defined", source: (1) "Uncaught SyntaxError: Unexpected token var", source: file:///android_asset/test.html (10)

2 Answers 2

1

after searching and trial error i somehow found a way. i just put the loadurl where im calling the function inside the onfinished of the webview.

webview.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String loc) {
            view.loadUrl("javascript:sample('"+temp+"')");
        }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Put the value in to the single quotes, below i have changed your code, take that code and try again.

webview.loadUrl("javascript:sample('"+temp+"')");

i have set the value (which is getting from the android) in edittext.

so you will get value in to the edit text in html.

test.html

<!DOCTYPE html>
<html> 
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width; user-scalable=0;" />
<script language="javascript">

 // getting Value from Android/ios
 function sample(temp){  
 var textcontrol = document.getElementById("txtname");
 textcontrol.value = temp;
 }

</script>
<title>My HTML</title>
</head>
<body >
<h1>My HTML </h1>
<br>
<input type="text" id="txtname" />
</body>
</html>

2 Comments

i tried the codes above sir but i still have the error "Uncaught ReferenceError: sample is not defined", source: (1) . i even tried the html above but still the same. am i missing something sir? thanks
by the way, i will be using this for the google chart, i pass dynamic data from android to javascript. maybe u could give some tips to better to do it.

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.