How to Open an xhtml file in Android webview - android

I'm developing an epub reader. I was able to extract the files from the epub and create a filetree in the device sdcard. However, when I try to read the .xhtml file. It is not working. I tried opening an html file instead and it works.
Here's my code for loading the .xhtml
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new ReaderWebClient());
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.loadUrl("file:///" + Environment.getExternalStorageDirectory() + "/epub/EPUB/cover.xhtml");
I just used a hardcoded for the url first as to try if it can load the page.
The webview just displays, "Webpage not available"
Am I doing something wrong? Thanks for any help

My solution for this is I get the data for each item (.xhtml file) and pass it as an argument to loadDataWithBaseUrl(). I just have to determine the correct path for the files so that the images and CSS can be loaded correctly.
String baseUrl = "file:///" + Environment.getExternalStorageDirectory() + "/epub" + bookFilename + "/OPS/";
String data = new String(bookReader.book.getContents().get(2).getData());
webView.loadDataWithBaseURL(baseUrl, data, "application/xhtml+xml", "utf-8", null);

Use this:
webView.loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "epub/EPUB/cover.xhtml");
and take permission for writing to storage in manifest file, like this:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Try this:
webView.loadUrl("file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "epub/EPUB/cover.xhtml");

This is my working code .Try it.
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.HONEYCOMB)
{
getSettings().setAllowContentAccess(true);
}
getSettings().setJavaScriptEnabled(true);
getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
getSettings().setAllowFileAccess(true);
if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.JELLY_BEAN)
{
getSettings().setAllowUniversalAccessFromFileURLs(true);
}
loadUrl("file://"+Environment.getExternalStorageDirectory()+"/epub/EPUB/cover.xhtml");
once cross check your file path.

Related

Load images using html <img> tag from Android expansion file

I am trying to load my HTML files from Android expansion file(.obb) using WebView like
String prompt = "";
WebView webview = (WebView) rootView.findViewById(R.id.webview);
try {
InputStream html = getAssetFileDescriptor("www/" + mResult.getTitle() + ".html")
.createInputStream();
byte[] b = new byte[html.available()];
html.read(b);
prompt = new String(b);
html.close();
} catch (IOException e) {
Log.e("Webview", "Couldn't open webpage");
}
webview.loadData(prompt, "text/html", "utf-8");
*getAssetFileDescriptor returns InputStream read by ZipResourceFile function(Zip file library)
It loads HTML into Webview successfully but all the images inside the HTML are not appearing.
I guess It's because it cannot access to image files through img tags.
for example, my html files have img tags like
<img src="./image1.jpg" />
Relative path seems not working because html and image files are zipped into obb file.
How can I fix it?
You can mount the OBB file using StorageManager:
StorageManager storageManager = (StorageManager)app.getSystemService(Context.STORAGE_SERVICE);
boolean queued = storageManager.mountObb(<path>, null, new OnObbStateChangeListsner() {...});
Then, you can use this path to construct a path to your files: the returned path is the root to your OBB:
storageManager.getMountedObbPath(...) + "/image1.jpg";
an use that path to load your image
<img src="your_path" />

How to load images from internal storage in webview in android?

We want to display html page with its contents like text, images etc offline(without internet connection) in webview. We are able to display text only. For image, we are storing image on internal storage(sd card) from image url and replacing that image url(server url) with the image internal storage(sd card) path.
But, those images are not displaying in webview.
For example,
Below is the img tag in html..
<img alt="img" class="center_top_img" src="http://test.com/uploads/section/images/523.jpg" />
We are replacing above image url(server url) with the image internal storage(sd card) path like
<img alt="img" class="center_top_img" src=\"file:///data/data/com.app.test/files/523.jpg\" />
Wherever the image is, just get its absolute path and add "file://" in advance.
File file = ...
String imagePath + "file://" + file.getAbsolutePath();
String html = "...<img src=\""+ imagePath + "\">...";
Try this
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/test.jpg";
String html = "<html><head></head><body><img src=\""+ imagePath + "\"></body></html>";
mWebView.loadDataWithBaseURL("", html, "text/html","utf-8", "");
Remember you image is inside app directory.
You can use this:
<img src="file:///data/data/com.yourapp/files/yourimage.jpg" />
In my case I wanted the images to be in 'internal storage', not the sd-card as you stated in description (and also inferred from your usage of getExternalStorageDirectory - your question title however mentioned 'internal storage'. For this reason, get the right path:
//image paths; 'images' folder was earlier created by getFilesDir
String basePATH = "";
String imagePSPPath = "";
String imagePSP = "passportImage.jpeg"; //can be generated dynamically if needed
File images = new File(getApplicationContext().getFilesDir(), "images");
if(file.exists()) {
//fine, it exists, build right strings
basePATH = images.toString();
imagePSPPath = basePATH +"/"+ imagePSP;
Log.i("XPATH", imagePSPPath); //loged for ease of copying
}else {
//error, path not found
Toast.makeText(YourActivity.this, "Sorry, path not found: ", Toast.LENGTH_LONG).show();
}
Next, use this path but also ensure that it has 3 forward slashes, not 2. For me, I just copied the XPATH address from LOG.i and pasted it in my Html page directly:
<img src="file:///"+imagePSPPath +" alt="PSP Photo">

WebView loading images from phone gallery

I'm trying to have the user pick an image from the phone's gallery. Then using the webview to display the image. The file path retrieved is something like "content://media/external/images/media/14". when i looked at other problems, seems like their file path usually start with "file://"
When the program is ran, it displays a long list of random characters. Not sure whats wrong, help is appreciated. thank you
edit this has been solved thx to Md Abdul Gafur's link.
new fixed code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//message is the path of the file.
setContentView(R.layout.activity_picture_large);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setAllowFileAccess(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setBuiltInZoomControls(true);
String html = "<html><head></head><body><p>hello</p><img src=\"" + message + "\" alt=\"alternativo\" /></body></html>";
myWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
}

showing image from sdcard with webview not working

I have downloaded map750.png file in the root of sdcard, but when I try to show it within a webview with some text, only the text is shown. Could you help me to find what is wrong in the code? thanks.
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
mWebView.loadData(html, "text/html","utf-8");
I edit the post to add the solution suggested by oneilse14, thanks!!
setContentView(R.layout.webview);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setAllowFileAccess(true);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setBuiltInZoomControls(true);
String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
mWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");
Try this,
final String fileName = "file:///mnt/sdcard/1.jpg";
final String mimeType = "text/html";
final String encoding = "utf-8";
final String html = "<img src=\""+fileName+"\">";
webView.loadDataWithBaseURL("", html, mimeType, encoding, "");
Check out loadDataWithBaseURL() in the Developer docs
http://developer.android.com/reference/android/webkit/WebView.html
loadData() has certain restrictions on what it can display. This method is able to display local device files like you are trying to do.
Note that the access using the file:// schema can fail due security restrictions.
Another approach is to use the URI of a ContentProvider that handles the local file access. Overwrite openFile(Uri, String) in a subclass of ContentProvider for this approach.

How do i reference an Image from with in an HTML page locally package in an android App?

I was trying to display a static html page in an android app having some images in it.
I saved the image in assests folder and also in res/raw folder.
I was loading html file with this technique and html file is also in res/raw folder.
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
String data = ResourceUtils.loadResToString(R.raw.temp, this);
final String mimetype = "text/html";
final String encoding = "UTF-8";
mWebView.loadData(data, mimetype, encoding);
I tried different ways to refer to image like.
img1.png, /img1.png, file:///img1.png, content://img1.png
HtmlViewer/assets/img1.png, content:///HtmlViewer/assets/img1.png and file:///HtmlViewer/assets/img1.png
PackageName/assets/img1.png, content:///PackageName/assets/img1.png and file:///PackageName/assets/img1.png
Can anyone tell me how to get path for image?
file:///android_asset/file_name.ext
This should work. Use this method instead.
loadDataWithBaseURL("file:///android_asset/", summary, "text/html", "utf-8", null);

Categories

Resources