Android Geeks, Welcome to Android Load HTML And Javascript In Webview From Assets tutorial.
Load HTML And Javascript In Webview Android example guide you to load HTML and JavaScript from local assets.
There will be situations where design of app can not be done with only xml file. You will need to implement html and css for better designing. Here, you will need to load html from asset.
We will also learn how can we integrate functions between android and JavaScript.
You will learn how to load HTML into Android WebView from String.
First, check the output of the tutorial then we will develop it.
Download Source Code for Load HTML And Javascript In Webview
[sociallocker]Download WebViewHtmlDemonuts [/sociallocker]
Step 1: Create a new project in Android Studio.
Make a new android studio project with empty activity.
Step 2: Making assets folder
Execute Rigth click on left menu bar->New Folder->Assets Folder as per below image
Creating JavaScript file
make new file and name it as load_JS_Demonuts.html
Copy below source code into it
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width; user-scalable=0;" /> <title>JavaScript Interface</title> </head> <body style="background-color:#E6E6FA"> <h1>JavaScript Interface</h1> <p id="mytext">JS view is controlled by Android code!!</p> <input type="button" value="Show Toast!" onClick="showJSToast('Toast to JS Interface!')" /> <input type="button" value="Open Dialog" onClick="openAndroidDialog()" /> <script language="javascript"> function showJSToast(toast) { AndroidFunction.showToast(toast); } function openAndroidDialog() { AndroidFunction.openAndroidDialog(); } function callFromActivity(msg){ document.getElementById("mytext").innerHTML = msg; } </script> </body>t </html>
put above file into assets folder.
We will fetch this file into Webview.
Step 3: Creating HTMLActivity
Make a new activity named HTMLActivity
put following code into activity_html.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.exampledemo.parsaniahardik.webviewhtmldemonuts.MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" /> </RelativeLayout>
Paste below source code into HTMLActivity.java
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.webkit.WebView; public class HtmlActivity extends AppCompatActivity { private WebView webView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_html); webView = (WebView) findViewById(R.id.webView); String htmlText = ""+ "<html>"+ "<head>"+ "<style = 'text/css'>"+ ".head{background: #cecb33;color: white;padding: 10px;border-radius: 7px;}"+ ".body{background: #FF4081;height: 75%;color: white;padding: 10px;border-radius: 7px;}"+ ".foot{background: #40ff56;color: white;padding: 10px;border-radius: 7px;}"+ "</style>"+ "</head>"+ "<body>"+ "<div class='head'>"+ "<h1>This HTML is loaded in WebView</h1>"+ "</div>"+ "<br>"+ "<div class='body'>"+ "<p>Body of the page</p>"+ "<h2>Header 2</h2>"+ "<h3>Header 3</h3>"+ "<h4>Header 4</h4>"+ "<h5>Header 5</h5>"+ "</div>"+ "<br>"+ "<div class='foot'>"+ "<p>Footer of the page</p>"+ "</div>"+ "</body>"+ "</html>"; webView.loadData(htmlText, "text/html", null); } }
In the above source code, we have store an HTML code into string variable. This string variable is loaded into the WebView with following code
webView.loadData(htmlText, "text/html", null);
Step 4: Creating JavaScriptActivity
Create a new activity named JavaScriptActivity
put below code into activity_java_script.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/msg" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <Button android:id="@+id/sendmsg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Msg to JavaScript" /> <WebView android:id="@+id/mybrowser" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
Paste below source code into JavaScriptActivity.java
import android.content.Context; import android.content.res.AssetManager; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.JavascriptInterface; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class JavaScriptActivity extends AppCompatActivity { private WebView webView; private EditText editText; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_java_script); webView = (WebView)findViewById(R.id.mybrowser); final MyJavaScriptInterface myJavaScriptInterface = new MyJavaScriptInterface(this); webView.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction"); webView.getSettings().setJavaScriptEnabled(true); webView.loadData(getHTMLData(), "text/html", "UTF-8"); editText = (EditText)findViewById(R.id.msg); button = (Button)findViewById(R.id.sendmsg); button.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub String msgToSend = editText.getText().toString(); webView.loadUrl("javascript:callFromActivity(\"" + msgToSend + "\")"); }}); } private String getHTMLData() { StringBuilder html = new StringBuilder(); try { AssetManager assetManager = getAssets(); InputStream input = assetManager.open("load_JS_Demonuts.html"); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String line; while ((line = br.readLine()) != null) { html.append(line); } br.close(); } catch (Exception e) { //Handle the exception here } return html.toString(); } public class MyJavaScriptInterface { Context mContext; MyJavaScriptInterface(Context c) { mContext = c; } @JavascriptInterface public void showToast(String toast){ Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } @JavascriptInterface public void openAndroidDialog(){ AlertDialog.Builder myDialog = new AlertDialog.Builder(JavaScriptActivity.this); myDialog.setTitle("Dialog of JS!"); myDialog.setMessage("I am generated from Android Code but I am in Webview and html-JS file !!!"); myDialog.setPositiveButton("Cool!", null); myDialog.show(); } } }
Step 5: Update MainActivity
Put below code in activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.exampledemo.parsaniahardik.webviewhtmldemonuts.MainActivity"> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_alignParentTop="true" /> </RelativeLayout>
Update MainActivity.java as per following
import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button btnHTML, btnJS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnHTML = (Button) findViewById(R.id.btnHtml); btnJS = (Button) findViewById(R.id.btnJS); btnHTML.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,HtmlActivity.class); startActivity(intent); } }); btnJS.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this,JavaScriptActivity.class); startActivity(intent); } }); } }
So that is all for Android WebView HTML JavaScript example.
If you have any questions or queries regarding this tutorial, then feel free to ask them in comment section.
You can also use comment section for your suggestions and reviews.
Thank you and keep sharing our tutorials.