Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 207
Pie Avatar asked Dec 06 '22 14:12

Pie


1 Answers

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.

like image 146
Rahul Patel Avatar answered Dec 28 '22 06:12

Rahul Patel