I created my first two Android applications completely using Android APIs. However I realized that I can build better user interface quickly using HTML, JavaScript and CSS. Android SDK provides WebView controls which is a browser control. So I started looking for ways to make WebView render local HTML files. Most APIs of WebView are simple to understand and use, except one important method, loadUrl.
To begin with I was not sure where to store my HTML/JS files in the Android project and what URL to use to load them. JavaDoc help for WebView did not mention how to load local assets into WebView. It turned out that you need to keep all your HTML/JS files in the ‘assets’ folder of you project and load them with URL file://android_asset/.
Here are steps to load local HTML file in the Activity class –
- You first need to create a layout for your Activity in res/layout folder of your Android project
- In the left pallet, click ‘Composite’ view and drag and drop ‘WebView’ control on to the layout
- In your activity class, associate above layout with the activity using setContentView method –
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // pass id of layout resource }
- In the onStart method of the Activity, get reference to the WebView we created above and load URL
public void onStart() { super.onStart(); WebView webView = (WebView)findViewById(R.id.webView1); //enable JavaScript webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl("file:///android_asset/index.html"); }
- Create index.html in the ‘assets’ folder of your project
Accessing Java class from JavaScript
With HTML, JavaScript and CSS you can create many useful Android applications. If you use HTML5 APIs, you could even create and access SQLLite database from JavaScript. However sometimes you many want to get access to Android APIs from your JavaScript code. You can do that as follows.
Create a class that will act as an interface between Java code and JavaScript code
public class java2JSAgent { public String getContacts() { String jsonResponse = null; //call Android APIs to get contacts //serialize to JSON and assign to jsonResponse return jsonResponse; } }
Craeate and instance of this class in onStart method and associate it with the instance of WebView
webView.addJavascriptInterface(new java2JSAgent(), "java2JSAgentVar");
The second argument to addJavascriptInterface method is name
of the JavaScript variable
. You can now access the Java object in JavaScript code using this variable name
.
<script type="text/javascript"> var contactsJson = java2JSAgentVar.getContacts(); </script>
So, using HTML, JavaScript, CSS and native Android APIs you can create quite powerful Android applications. And if you want to develop cross platform mobile applications using HTML and JS, then PhoneGap is your best bet.
-Ram Kulkarni
Update :
In Android SDK 4.2, you have to annotate (@JavascriptInterface) methods in Java class that you want to make available to JavaScript. (see description of addJavascriptInterface). So in the above example the class java2JSAgent would be –
import android.webkit.JavascriptInterface; public class java2JSAgent { @JavascriptInterface public String getContacts() { String jsonResponse = null; //call Android APIs to get contacts //serialize to JSON and assign to jsonResponse return jsonResponse; } }
Also when running this code with the latest SDK and emulator, I had to sometimes call webView.setWebChromeClient(new WebChromeClient()) after enabling JavaScript in the WebView. Otherwise I observed that JavaScript code on the HTML page was not getting executed. However I observed that this behavior was inconsistent.
public void onStart() { super.onStart(); WebView webView = (WebView)findViewById(R.id.webView1); //enable JavaScript webView.getSettings().setJavaScriptEnabled(true); webView.setWebChromeClient(new WebChromeClient()); webView.loadUrl("file:///android_asset/index.html"); }
Quality information, trendy website design and style, maintain the good work
hellooo…. when i try lo load the html page, it shows an error message such that unable lo load… i tried 100 times… but it remains same!!! help…plz…..
What is the exact error message? Have you saved your HTML file in the assets folder, under project root?
Hello,
I got a problem with Android 4.0.
Class functions are not called.
On previous versions (2.1-3.3) everything worked very well.
Have you met such issue in your work?
I tried the example code in this post with Android 4.0 and did not see any issue.
PhoneCap is Great! Thanx for sharing this tutorial!
I am getting an error in the following line in the onStart() method.
webView.addJavascriptInterface(new Contacts(), “contactsVar”);
here is my onstart method
@Override
public void onStart()
{
super.onStart();
WebView webView = (WebView)findViewById(R.id.webView1);
//enable JavaScript
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new Contacts(), “contactsVar”);
webView.loadUrl(“file:///android_asset/www/index.html”);
}
To find the error i have to literally remove one line by line which i have added as i dont know how to debug. Below is the error from logcat
Changing log level to DEBUG(3)
DroidGap.onCreate()
JNI WARNING: jarray 0x4055a8b0 points to non-array object (Ljava/lang/String;)
“WebViewCoreThread” prio=5 tid=9 NATIVE
| group=”main” sCount=0 dsCount=0 obj=0x405202f0 self=0x2a83d0
| sysTid=364 nice=0 sched=0/0 cgrp=default handle=2786568
| schedstat=( 685751416 1090116864 113 )
at android.webkit.LoadListener.nativeFinished(Native Method)
at android.webkit.LoadListener.nativeFinished(Native Method)
at android.webkit.LoadListener.tearDown(LoadListener.java:1200)
at android.webkit.LoadListener.handleEndData(LoadListener.java:721)
at android.webkit.LoadListener.handleMessage(LoadListener.java:219)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:629)
at java.lang.Thread.run(Thread.java:1019)
VM aborting
Are you using Android emulator 2.3 ? There is bug in java interface in this version of the emulator – http://code.google.com/p/android/issues/detail?id=12987. A workaround has been posted here, http://www.jasonshah.com/handling-android-2-3-webviews-broken-addjavascriptinterface/,though I have not tried it.
From the stack trace I see that a mention of DroidGap. Are you using PhoneGap? In that case you do not need to create WebView. PhoneGap creates one for you. You can access WebView instance of DroidGap from the class extending it e.g.
public class MyDroidActiviry extends DroidGap
{
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.appView.addJavascriptInterface(new Contacts(), “contactsVar”);
super.loadUrl(“file:///android_asset/www/index.html”);
}
}
However I am not sure if you will hit the same bug after these changes, because of the bug in the emulator.
good tutorials thanx
brother, can i build a real android app with html, css & js without java..? and also if u plz tell that how can i install the app in my android phn which is made by html,css &js,,
hopefully waiting for your reply…
Yes, it is possible to build Android app using HTML, JS and CSS. Take a look at PhoneGap. It allows you to call device APIs for Contacts, Camera, Metdia etc from JS code. You can use PhoneGap Build to package the application (create APK file). Once you have an APK file, copy it to SD card of the phone and try to open it. This will open up the installer to install the application.
Or you can download ADT. It is an Eclipse plugin. You can create an Android project in ADT or using PhoneGap and open it in ADT. Then from ADT you can export the project to create an APK file.
Hello Ram,
Is it possible to interact with the HTML/JS using Java? i.e., i want my UI to be using HTML/JS but want the back end processing to be in Java, like when a HTML button is clicked i can get the event in my Java code and then the Java code send some text or image back to HTML UI to display.
Is this possible?
When i am execute this program i did’t get output. If any changes required in manifest file.
I don’t think I posted a complete application in this blog entry, so not sure which program you executed. However I have created a demo project which you can download and run.
Hi I have downloaded your app however it doesn’t solve my problem. in you assets folder you have single html file. However in mine there is one html file and 3 external js files. how could I run them on my phone via webview?
Hello,
My html and all javascript files on my web server(test.com).
and created one apk for android. Loading test.com in webview in this app.
Now I want to use “interface” which is created in apk using “addjavascriptinterface” in my js files which is located at test.com.
and that inface name is “Android” as follows :
browser.addJavascriptInterface(new WebAppInterface(this), “Android”);
but when I am calling function as ” Android.moveToNextScreen( cd[16] ); ” in javascript.
It throws error
11-21 16:04:16.995: I/chromium(1026): [INFO:CONSOLE(89)] “Uncaught TypeError: undefined is not a function”, source:http://test.com…..
Please help me.
public class java2JSAgent
{
public String getContacts()
{
String jsonResponse = null;
//call Android APIs to get contacts
//serialize to JSON and assign to jsonResponse
return jsonResponse;
}
}
hi , i’m not very good at java and android , please help me how can i
//call Android APIs to get contacts
and
//serialize to JSON and assign to jsonResponse
thank u.
My comment says “call Android API to get contact” just as an example of calling any Adnroid API, not necessarily contact APIs. Whatever the result of the API, serialize that to JSON so that JavaScript code can easily parse the result. If you are specifically interested in contact APIs, take a look at http://developer.android.com/training/contacts-provider/retrieve-names.html
wow, thats the best articel, but i cannot follow your tutorial, can u give us source of you tutorial?thx alot
As mentioned in one of my comments above, I have created a demo project which you can download and run.
Thanks For Your valuable posting, it was very informative. Am working inErp Software Company In India
guys visit here for more good examples ……
http://androidexample.com/Show_Loader_To_Open_Url_In_WebView__-_Android_Example/index.php?view=article_discription&aid=125&aaid=145
Hey there. This tutorial is helpful. I am trying to open the file chooser dialogue and have tried examples. But none of them showed well how to implement the javascript to call the Java api. This should help!
nice