How to show static HTML page in android emulator? - android

I want to display one static HTML page in my android emulator.

an easier way is described at Android HTML resource with references to other resources. Its working fine for me.
Put the HTML file in the "assets" folder in root, load it using:
webView.loadUrl("file:///android_asset/filename.html");

I'm assuming you want to display your own page in a webview?
Create this as your activity:
public class Test extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webview = new WebView(this);
setContentView(webview);
try {
InputStream fin = getAssets().open("index.html");
byte[] buffer = new byte[fin.available()];
fin.read(buffer);
fin.close();
webview.loadData(new String(buffer), "text/html", "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
}
}
This will read the file 'index.html' from your project assets/ folder.

So you can simply use the WebView control to display web content to the screen, which can think of the WebView control as a browser-like view.
You can also dynamically formulate an HTML string and load it into the WebView, using the loadData() method. It takes three arguments. String htmlData, String mimeType and String encoding
First of all you create a “test.html” file and save it into assets folder.
Code:
<html>
<Body bgcolor=“yellow”>
<H1>Hello HTML</H1>
<font color=“red”>WebView Example by Android Devloper</font>
</Body> </html>
if you want see full source code : Display HTML Content in Android

Related

How to pass parameter into HTML file from android

I can show up HTML file content in android webview well.Now how could i pass parameter into HTML file.For ex.my HTML content has an video player
i need to pass dynamic values(URL) into HTML file for playing dynamic video.My HTML file is located on asset folder.How could i do this?
Thanks.
I came upon this problem today, however I needed this to work with UTF-8 encoding, so this was my approach, hopefully it will help someone and clarify some of the previous answers to this question.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>%ERR_TITLE%</h1>
<h2>%ERR_DESC%</h2>
</body>
</html>
Java:
String content = IOUtils.toString(getAssets().open("error.html"))
.replaceAll("%ERR_TITLE%", getString(R.string.error_title))
.replaceAll("%ERR_DESC%", getString(R.string.error_desc))
mWebView.loadDataWithBaseURL("file:///android_asset/error.html", content, "text/html", "UTF-8", null);
As for IOUtils:
http://commons.apache.org/proper/commons-io/download_io.cgi
Instead of passing directly the video URL (following you example), i would have used tokens in the Html file. For example:
<embed src="$VIDEO_URL$" autostart="false" />
where the $VIDEO_URL$ will be the token wich will be replaced during the runtime with a real video URL.
Also, since you cannot change the contents of your asset folder during runtime you should load the html file contents into a String variable and use the replace method to replace the token with a real URL and, finally, pass that string to your webview. Something like this:
//The html variable has the html contents of the file stored in the assets folder
//and real_video_url string variable has the correct video url
html = html.replace("$VIDEO_URL$", real_video_url);
webview.loadData(html, "text/html", "utf-8");
If i would like to have something dynamic in my HTML i would have an html with dynamic parts written like this:
<B>%NAME%</B>
Then i would load my HTML:
String template = Utils.inputStreamToString(assets.open("html/template.html"));
then
Then i would replace all dynamics parts with what i want like this:
String data = template.replaceAll("%NAME%", "Alice McGee");
then i would pass it to my webView!
WebView webView = new WebView(this);
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "utf-8", null);
I managed to pass variables in a different way.
My problem was that everytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In onCreate method after setting up myWebView I did the following:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String urlString)
{
Log.i("onPageFinished", "loadVariables("+newURL+")");
if(newURL!="")
myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
jsInterface = new JSInterface(this,myWebView);
myWebView.addJavascriptInterface(jsInterface, "Android");
if (savedInstanceState != null)
{
// retrieve saved variables and build a new URL
newURL = "www.yoururl.com";
newURL +="?var1=" + savedInstanceState.getInt("key1");
newURL +="?var2=" + savedInstanceState.getInt("key2");
Log.i("myWebApp","NEW URL = " + newURL);
}
myWebView.loadUrl("www.yoururl.com");
So, what it happens is that first I load the page with the default URL (www.yoururl.com) and onPageFinished I call a new javascript method where I pass the variables.
In javascript loadVariables function looks like this:
function loadVariables(urlString){
// if it is not the default URL
if(urlString!="www.yoururl.com")
{
console.log("loadVariables: " + urlString);
// parse the URL using a javascript url parser (here I use purl.js)
var source = $.url(urlString).attr('source');
var query = $.url(urlString).attr('query');
console.log("URL SOURCE = "+source + " URL QUERY = "+query);
//do something with the variables
}
}
here assets means what?
String template = Utils.inputStreamToString(assets.open("html/template.html"));

Android - adding a image in html webview

Ok so the image i'm using is called test.png and I have a java class (Cherry.java) and a xml class (cherry.xml) Also I have a html file in the /res/raw folder called htmltest.html. What i'm trying to do is when the user clicks a button on the previous page and then takes them to cherry.xml all it is a webview. Now in the java class its just opening up the htmltest file and in the html file is just a normal web based layout. I want to display images in the html file so a image thats in the drawable folder or something like that with out having to use the internet. (don't want the internet permission to be used). Below is the code for the 3 files I have.
cherry.xml
<WebView
android:id="#+id/webviewHelp"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
Cherry.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class Cherry extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cherry);
WebView webview = (WebView) findViewById(R.id.webviewHelp);
webview.loadData(readTextFromResource(R.raw.htmltest), "text/html", "utf-8");
}
private String readTextFromResource(int resourceID)
{
InputStream raw = getResources().openRawResource(resourceID);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
stream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return stream.toString();
}
}
htmltest.html
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
<h2>Pictures</h2>
<img border="0" src="file:///android_drawable/test.png" alt="nothing" width="304" height="228" />
</body>
</html>
Any more questions just ask and i'll reply as fast as possible.
Everything works fine its just the images that I can't get to display.
First of all welcome to stackoverflow.
Now put your html and image etc inside the Assets folder. And use the following code.
Cherry.java
WebView webview = (WebView) findViewById(R.id.abtus_webView);
webview.loadUrl("file:///android_asset/index.html");
htmltest.html
<img src="images/abc.png">
I have put the images into the images Folder in Assets folder.This is working for me correct,I hope it helps you.
Create this directory assets/www
then place your html and image etc inside the www folder.
And use the following code.
Cherry.java
webview.loadUrl("file:///android_asset/www/htmltest.html");
htmltest.html
<img border="0" src="../res/drawable-hdpi/test.png" alt="nothing" width="304" height="228" />
Just modify the image path
From:
file:///android_drawable/test.png
To:
file:///android_res/drawable/test.png
If your images are small. Convert them to Base64 codings.
Explained here:
http://dean.edwards.name/my/base64-ie.html

Android : Display images in Webview

After processing a file, I get a HTML string in which the image is set as
<img src="abc.001.png" width="135" height="29" alt="" style="margin-left:0pt; margin-top:0pt; position:absolute; z-index:-65536" />
The path of the image should not be modified because I have to choose the file item from a list. The image is in the same directory as the file. I load the HTML string using loadData/loadDataWithBaseURL, but the image isn't displayed. I only see its frame.
How can I fix this? And can I apply that solution in case I have many images which are indexed as .001.jpg, .002.png , etc... (all in a directory) ?
Update: Thanks, it works with loadUrl() statement no matter how I name the image. In fact I have to read and process the content before loading it in WebView. That's why I use loadDataWithBaseUrl() statement and get the trouble above. Here's my code in the test project to read and display the content of Test.html.
String res = "";
File file = new File(Environment.getExternalStorageDirectory()+"/Test.html");
try {
FileInputStream in = new FileInputStream(file);
if (in != null) {
BufferedReader buffreader = new BufferedReader(
new InputStreamReader(in));
String line;
while ((line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
wv.loadDataWithBaseURL(null, res, "text/html", "utf-8", null);
//wv.loadUrl("file://"+Environment.getExternalStorageDirectory()+"/Test.html");
The statement in // works but that's not what I can do in my real project. I have a solution: after processing the content I have to save it in a temporary HTML file then load it, that file will be delete later. However, I'm still looking forward to a better solution :)
Try to change the name of the image file. I thought this is because of double dot in the name.
<img id="compassRose" src="CompassRose.jpg"></img>
this is working for me....
Code:
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.webkit.WebView;
public class StackOverFlowActivity extends Activity {
private Handler mHandler = new Handler();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView view=(WebView)findViewById(R.id.webView1);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl("file:///android_asset/index.html");
view.addJavascriptInterface(new MyJavaScriptInterface(), "Android");
}
final class MyJavaScriptInterface
{
public void ProcessJavaScript(final String scriptname, final String args)
{
mHandler.post(new Runnable()
{
public void run()
{
//Do your activities
}
});
}
}
}
index.html:
<html>
<head>
<title title="Index"></title>
</head>
<body>
<h2>Android App demo</h2>
<br /> <img src="CompassRose.jpg" />
</body>
</html>
Result:
simply use:
webview.loadUrl("file:///android_asset/mypicture.jpg");
Your problem is with the line:
wv.loadDataWithBaseURL(null, res, "text/html", "utf-8", null);
The first parameter (baseURL) is null. For some reason, WebView then refuses to load any linked resources even if you use absolute URLs. You might find that it will work if you change your code to (assuming your images are stored in the external dir):
wv.loadDataWithBaseURL ("file://" + Environment.getExternalStorageDirectory(), res, "text/html", "utf-8", null);
Remember to add the proper permission if you refer to resources on the network:
<uses-permission android:name="android.permission.INTERNET" />
Sorry, a little late in my reply. I was researching a similar problem when I came across this post.
WebView webView=(WebView)findViewById(R.id.my_wb);
String url = "YOUR URL";
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.loadUrl(url);

html5 apps for tablets: possible to load images from device's filesystem?

I created a simple html file that loads some images from my local hard-drive (ubuntu).
It is enough to put
<img src=/home/user/directory/image.jpg></img>
Now I need to know if it is the same when Html5 is displayed on a tablet like Android or iOS, or Html5 is used in offline app.
I mean, if html5 can load an image from the device's filesystem just like on my computer, without localStorage or sessionStorage.
If you deploy the application as native application it is possible (wrap it with Phonegap).
For saved HTML files it is not possible.
On Android, it can be done even though it looks a bit tricky at first. Say you have defined a WebView in your layout.xml, which you want to fill with an html file shipped with your application, which in turn should import a png also shipped with your application.
The trick is to put the html file into res/raw and the png into assets.
Example.
Say you have hello.html which should include buongiorno.png.
Within your project, say MyProject, place buongiorno.png into MyProject/assets.
The hello.html goes into MyProject/res/raw (because we want to avoid having it 'optimised' by the android resource compiler), and could look like this:
<html>
<head></head>
<body>
<img src="file:///android_asset/buongiorno.png"/>
<p>Hello world.</p>
</body>
</html>
In your java code, you would put this code:
WebView w = (WebView) findViewById(R.id.myWebview);
String html = getResourceAsString(context, R.raw.hello);
if (html != null) {
w.loadDataWithBaseURL(null, html, "text/html", "UTF-8", null);
}
where getResourceAsString() is defined as follows:
public static String getResourceAsString(Context context, int resid) throws NotFoundException {
Resources resources = context.getResources();
InputStream is = resources.openRawResource(resid);
try {
if (is != null && is.available() > 0) {
final byte[] data = new byte[is.available()];
is.read(data);
return new String(data);
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
} finally {
try {
is.close();
} catch (IOException ioe) {
// ignore
}
}
return null;
}

To show a static html page in android

I am trying to show an html file in my assets folder but in web view i am seeing white blank page. I got similar example from stackflow only.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String mimeType="text/html";
final String encoding="UTF-8";
String htmlString="<html><body>";
Document doc;
WebView wv= new WebView(this);
Elements link = null;
setContentView(wv);
try{
InputStream in=getAssets().open("myweb.html");
byte[] buffer= new byte[in.available()];
in.read(buffer);
in.close();
wv.loadData(new String(buffer), mimeType, encoding);
}
catch(IOException e)
{
Log.d("MyWebView", e.toString());
}
}
you can load the content of the web view using
// add a webview with id #+id/the_webwiev to your main.xml layout file
WebView wv = (WebView)findViewById(R.id.the_webview);
wv.loadUrl("file:///android_asset/myweb.html");
Uhm, did you try following the WebView example from the official webpage? It's really simple.
http://developer.android.com/resources/tutorials/views/hello-webview.html
I followed that and had no trouble implementing a WebView. Your code looks overly complicated for something that is quite simple.
If your file is called pmi_help.html (and located in the /assets/ folder), you load it using:
mWebView.loadUrl("file:///android_asset/pmi_help.html");
Put your html page in asset > www, then load:
mWebView.loadUrl("file:///android_asset/index1.html");

Categories

Resources