2

I need to make some UI part in javascript for android application for that I'm writing some code in javascript and load it in android web view. Now, I want to call java class from javascript.

Is it possible to call java class from javascript?

Thanks in Advance!

2
  • Why are you splitting the application that way? Why not just write it all,including UI, in Java? Commented Jul 7, 2011 at 5:34
  • because i need to draw much complex UI in android you can see the following question at stackoverflow.com/q/6596294/562296 Commented Jul 7, 2011 at 5:39

3 Answers 3

4

It's possible, but I wouldn't do it for your given use case :) (the UI could be done with the Android framework)

You can add what they call "Javascript Interfaces", which are basically links from Javascript to Java code. First, define a class to bind containing the methods you which to call, and add it to your WebView :

    class HelloInterface  
    {  
        public void test(String name)  
        {  
            Log.i(TAG, "Hello " + name); 
        }  
    } 

    webview.addJavascriptInterface(new HelloInterface(), "HELLO");  

Then, from your javascript code, you can just call

window.HELLO.test("Webview");
Sign up to request clarification or add additional context in comments.

1 Comment

I meant I wouldn't use javascript just to create a UI that could be done with the native Android framework :) Besides that, binding java and javascript is fine.
1

Refer the following urls,

http://www.rgagnon.com/javadetails/java-0170.html

Post #6 of-> http://ubuntuforums.org/showthread.php?t=565819

Hope this helps..

Comments

0

its actually reall easy (and cool) use:

webView.addJavascriptInterface(js, "pageObject");

js is a java object made in you activty (or somewhere where you init the webview), pageObject is the namespace identifier (variable) you can use with javaScript on your webpage.

Comments

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.