Android - adding a image in html webview - android

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

Related

Android image map. - displaying an .svg and using it as an image map (touch zones)

I am looking for a way to display an image and have the user tap on different parts of the image to navigate and perform actions.
I was considering using an invisible color map to check which parts have been touched.
But since i also want to highlight the selected areas, i was thinking of using vectors.
There is a nice library to render svg files into an image view here, but it doesn't handle touches.
Is there a library out there that does? Or any smarter way of doing this?
(I also checked out this project but it won't swallow .svg files and my vector image is far too complex to insert all the data by hand)
Interesting problem! I'm not convinced you can't use a combination of the libraries you mentioned.
What I would do is first use SVG-Android to programmatically read in your SVG file. Looking at SVG-Android, it looks like it returns the final product as a PictureDrawable, which is a subclass of Drawable.
Right after SVG-Android finishes processing the SVG graphics, I'd use ImageView.setImageDrawable to load the main ImageView with the PictureDrawable we just generated. Then I'd just use that ImageView as the base for the implementation of "Images with Clickable Areas" you linked in the original question.
Honestly, I think the hardest part will be getting SVG-Android to work correctly (I've played with it a bit, and it's a bit finicky). However, I don't think you'll have much difficulty combining the SVG-generated drawable with the clickable areas. It's a simple change in the source of the base image.
Good luck!
Not sure if this is the sort of thing you are after but here is an example of click enabled svg in a Android WebView:
WebView webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.w3.org/TR/SVG/images/script/script01.svg");
It should show a red circle that you can click on and the circle changes size.
Here is the same example reworked with the svg loaded from the assets folder and an android javascript interface exposed so you do callbacks into android code from your svg file.
WebView webView;
public class WebAppInterface {
/** Show a toast from svg */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebAppInterface(), "Android");
String svg = loadSvg();
webView.loadData(svg, "image/svg+xml", "utf-8");
}
String loadSvg() {
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
getAssets().open("test.svg")));
StringBuffer buf = new StringBuffer();
String s = null;
while ((s = input.readLine()) != null) {
buf.append(s);
buf.append('\n');
}
input.close();
return buf.toString();
} catch (IOException ex) {
ex.printStackTrace();
}
return null;
}
and the test.svg file:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="6cm" height="5cm" viewBox="0 0 600 500"
xmlns="http://www.w3.org/2000/svg" version="1.1">
<desc>Example script01 - invoke an ECMAScript function from an onclick event
</desc>
<!-- ECMAScript to change the radius with each click -->
<script type="application/ecmascript"> <![CDATA[
function circle_click(evt) {
Android.showToast("Hello from SVG");
var circle = evt.target;
var currentRadius = circle.getAttribute("r");
if (currentRadius == 100)
circle.setAttribute("r", currentRadius*2);
else
circle.setAttribute("r", currentRadius*0.5);
}
]]> </script>
<!-- Outline the drawing area with a blue line -->
<rect x="1" y="1" width="598" height="498" fill="none" stroke="blue"/>
<!-- Act on each click event -->
<circle onclick="circle_click(evt)" cx="300" cy="225" r="100"
fill="red"/>
<text x="300" y="480"
font-family="Verdana" font-size="35" text-anchor="middle">
Click on circle to change its size
</text>
</svg>
It's very very simple ;-)
You must create an javascript interface to handle click from web view and add this file to your web view. Just flow the step:
1) Create JavaScript Interface
public class WebViewInterface {
#JavascriptInterface
public void showDetail(String content) {
Toast.makeText(getActivity(), content, Toast.LENGTH_SHORT).show();
}
}
2) Add interface to web view
WebView webView = findViewById(R.id.web_view);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewInterface(), "Android");
3) Edit svg file same as this one
<?xml version="1.0" standalone="no"?>
<svg width="10cm" height="10cm" viewBox="0 0 600 500"
xmlns="http://www.w3.org/2000/svg" version="1.1">
<desc>Sample SVG</desc>
<script type="application/ecmascript"> <![CDATA[
function section_click(evt) {
Android.showDetail("OnClick: " + evt.id);
}
]]> </script>
<rect id="rect" onclick="section_click(this)" x="1" y="1" width="598" height="498" fill="none" stroke="blue"/>
<circle id="circle" onclick="section_click(this)" cx="300" cy="225" r="100"
fill="red"/>
<text id="text" onclick="section_click(this)" x="300" y="480"
font-family="Verdana" font-size="35" text-anchor="middle">
Click on each element
</text>
</svg>

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;
}

Retrieve data from sqlite database and display in assest folder's HTML page in android

I want to make a dynamic webpage that can display my sqlite database's element in tabular format. How can I create a dynamic webpage in android?
I make a static HTML page and put in assest folder. It works but now I want a dynamic webpage. Please help:
package com.Htmlview;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class Htmlview extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
WebView webview = new WebView(this);
setContentView(webview);
try {
InputStream fin = getAssets().open("index3.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 page works ...
Help to make it dynamic through code.
gaurav gupta
Use java.text.MessageFormat:
Put "{0}" markers in your html file.
Read your html file into a string
Create an arguments array from the database record
Call MessageFormat.format(htmlString, dbArgs)
Load the resulting string into the webview.
You can't modify the asset folder in runtime as it compiled at build time. So, you have 2 variants:
You content from database as it is. Just read the bytes and pass them to the webview without storing to anywhere.
Store the content to the file in internal memory and do like you did it with assets. But there is no sence as you already have your data in db.

How to show static HTML page in android emulator?

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

Categories

Resources