Android WebView – Reading Asset Files

person folder_openAndroidaccess_time March 22, 2015

This is a follow-up to the previous tutorial How to load HTML & CSS string in a WebView. In this, we are going to learn how to read text files from assets folder.
See flowing Steps :

  1. Create a layout file res/layout/activity_main.xml with one WebView in it.
  2. Create a data helper class to generate HTML content with CSS style scripts embedded.
  3. Read text file from assets folder. Parse the delimited data and fill it in HTML Table.
  4. INTERNET permission is not necessary in this case.

1. Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stackandroid.assets"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Activity layout file

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.hsbc.WebviewActivity" >
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HTML, CSS, Read Asset File"
            android:textColor="#860000"
            android:textSize="23dp"
            android:layout_centerHorizontal="true"
           android:textStyle="bold" />
   <WebView
       android:id="@+id/rawdataWebview"
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:layout_alignParentRight="true"
       android:layout_below="@+id/textView1"
       android:layout_marginTop="40dp" />
</RelativeLayout>

3. Asset File
Place this sample.txt file under assets folder.

Name:Tamil:English:Maths:Science:Social Science
Vinoth:93:96:100:98:99
Kumar:94:99:100:98:98
Raju:95:95:100:94:99
Bala:96:99:100:98:99

4. Main Activity code

package com.stackandroid.assets;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebView;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		String completeHtmlData = new DataHelper().generateHtmlData(this);
		WebView mWebView = (WebView)findViewById(
				R.id.rawdataWebview);
		// Add javascript support to the webview
		mWebView.getSettings().setJavaScriptEnabled(true);
		// Enable pinch zoom controls on webview
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.setInitialScale(100);
		mWebView.getSettings().setUseWideViewPort(true);
		// Load the html string data
		mWebView.loadData(completeHtmlData, "text/html", "UTF-8");
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}

5. Data Helper class
Read the text file and parse the delimited data. Create HTML table rows to display the content.

package com.stackandroid.assets;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.app.Activity;
import android.util.Log;
public class DataHelper extends Activity{
	StringBuffer html;
	/**
	 * Generate HTML data and append input data stored in asset text file
	 * @param activity
	 * @return
	 */
	public String generateHtmlData(Activity activity){
		try {
			// Read text file from assets folder
			InputStream is = activity.getAssets().open("sample.txt");
			BufferedReader reader = new BufferedReader(new InputStreamReader(is));
			String line;
			String[] tableArray = null;
			html = new StringBuffer("<html><head>"+getCSSForTable()+"</head>" + "<table class=\"TableStyle\">");
			while ((line = reader.readLine()) != null) {
				tableArray = line.split(":");
				html.append("<tr>");
				for (int i = 0; i < tableArray.length; i++) {
					html.append("<td>" + tableArray[i] + "</td>");
					Log.v("table array", tableArray[i]);
				}
				html.append("</tr>");
			}
			html.append("</tr>" + "</table>" + "<br/><br/><div align=\"center\"><<<< Scroll horizontally >>>></div><br/><div align=\"center\">Supports Pinch Zoom</div></html>");
			Log.v("html appended value", html.toString());
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
			return "";
		}
		return html.toString();
	}
	/**
	 * Generate CSS styles
	 * @return
	 */
	private String getCSSForTable(){
		String cssString;
		cssString = "<style>"+
		".TableStyle {"+
			"margin:0px;padding:0px;"+
			"width:100%;"+
			"box-shadow: 10px 10px 5px #888888;"+
			"border:1px solid #07214f;"+
			"-moz-border-radius-bottomleft:0px;"+
			"-webkit-border-bottom-left-radius:0px;"+
			"border-bottom-left-radius:0px;"+
			"-moz-border-radius-bottomright:0px;"+
			"-webkit-border-bottom-right-radius:0px;"+
			"border-bottom-right-radius:0px;"+
			"-moz-border-radius-topright:0px;"+
			"-webkit-border-top-right-radius:0px;"+
			"border-top-right-radius:0px;"+
			"-moz-border-radius-topleft:0px;"+
			"-webkit-border-top-left-radius:0px;"+
			"border-top-left-radius:0px;"+
		"}.TableStyle table{"+
		    "border-collapse: collapse;"+
		    "border-spacing: 0;"+
			"width:100%;"+
			"height:100%;"+
			"margin:0px;padding:0px;"+
		"}.TableStyle tr:last-child td:last-child {"+
			"-moz-border-radius-bottomright:0px;"+
			"-webkit-border-bottom-right-radius:0px;"+
			"border-bottom-right-radius:0px;"+
		"}"+
		".TableStyle table tr:first-child td:first-child {"+
			"-moz-border-radius-topleft:0px;"+
			"-webkit-border-top-left-radius:0px;"+
			"border-top-left-radius:0px;"+
		"}"+
		".TableStyle table tr:first-child td:last-child {"+
			"-moz-border-radius-topright:0px;"+
			"-webkit-border-top-right-radius:0px;"+
			"border-top-right-radius:0px;"+
		"}.TableStyle tr:last-child td:first-child{"+
			"-moz-border-radius-bottomleft:0px;"+
			"-webkit-border-bottom-left-radius:0px;"+
			"border-bottom-left-radius:0px;"+
		"}.TableStyle tr:hover td{"+
		"}"+
		".TableStyle tr:nth-child(odd){ background-color:#ffffff; }"+
		".TableStyle tr:nth-child(even)    { background-color:#a6d3ed; }.TableStyle td{"+
			"vertical-align:middle;"+
			"border:1px solid #07214f;"+
			"border-width:0px 1px 1px 0px;"+
			"text-align:left;"+
			"padding:7px;"+
			"font-size:12px;"+
			"font-family:Arial;"+
			"font-weight:normal;"+
			"color:#020101;"+
		"}.TableStyle tr:last-child td{"+
			"border-width:0px 1px 0px 0px;"+
		"}.TableStyle tr td:last-child{"+
			"border-width:0px 0px 1px 0px;"+
		"}.TableStyle tr:last-child td:last-child{"+
			"border-width:0px 0px 0px 0px;"+
		"}"+
		".TableStyle tr:first-child td{"+
				"background:-o-linear-gradient(bottom, #629edb 5%, #003f7f 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #629edb), color-stop(1, #003f7f) );"+
			"background:-moz-linear-gradient( center top, #629edb 5%, #003f7f 100% );"+
			"filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#629edb\", endColorstr=\"#003f7f\");	background: -o-linear-gradient(top,#629edb,003f7f);"+
			"background-color:#629edb;"+
			"border:0px solid #07214f;"+
			"text-align:center;"+
			"border-width:0px 0px 1px 1px;"+
			"font-size:15px;"+
			"font-family:Arial;"+
			"font-weight:bold;"+
			"color:#ffffff;"+
		"}"+
		".TableStyle tr:first-child:hover td{"+
			"background:-o-linear-gradient(bottom, #629edb 5%, #003f7f 100%);	background:-webkit-gradient( linear, left top, left bottom, color-stop(0.05, #629edb), color-stop(1, #003f7f) );"+
			"background:-moz-linear-gradient( center top, #629edb 5%, #003f7f 100% );"+
			"filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=\"#629edb\", endColorstr=\"#003f7f\");	background: -o-linear-gradient(top,#629edb,003f7f);"+
			"background-color:#629edb;"+
		"}"+
		".TableStyle tr:first-child td:first-child{"+
			"border-width:0px 0px 1px 0px;"+
		"}"+
		".TableStyle tr:first-child td:last-child{"+
			"border-width:0px 0px 1px 1px;"+
		"}"+
		"</style>";
		return cssString;
	}
}

6. Demonstration

Webview Read Asset File
Webview Read Asset File

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">