In my app I'm making a basic HTML help document.
I wanted my app's logo in the HTML img tag itself, but I don't know how I'd reference to the logo which will be stored in assets.
Is this possible, if so how?
Thanks for the help!
Put your Logo into the assets directory eg: assets/logo.png
Then load your html with:
webView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "utf-8", null);
Reference your img like:
<img src="logo.png">
Store the images in assets folder:
Read the image in the html from assets with file:///android_asset/
for example:
String sHtmlTemplate = "<html><head></head><body><img src=\"file:///android_asset/img/mybadge.png\"></body></html>";
load inside the WebView:
webView.loadDataWithBaseURL(null, sHtmlTemplate, "text/html", "utf-8",null);
You can reference assets with this URL syntax:
file:///android_asset/YourAssetFilename
dump them into assets folder and just put in the html
<img src="filename.png">
simple as that
Put your Logo into the assets directory
Example : assets/logo.png
Then
String imgData="<img src=home.png>";
webView.loadDataWithBaseURL("file:///android_asset/", imgData, "text/html", "utf-8", null);
Consider we have placed an image your_image.png in assets/imgs.
In earlier versions of android you can directly access images like below.
webView.loadData("<img src='file:///android_asset/imgs/your_image.png'/>",
"text/html", "UTF-8");
But can't access files directly in latest versions due to added security concerns. for the latest versions we need to use WebViewAssetLoader. refer the below code.
Helper class to load local files including application's static assets and resources using http(s):// URLs inside a WebView class. Loading local files using web-like URLs instead of "file://" is desirable as it is compatible with the Same-Origin policy.
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
.addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this))
.build();
webView.setWebViewClient(new WebViewClient() {
#Override
public WebResourceResponse shouldInterceptRequest(WebView view,
WebResourceRequest request) {
return assetLoader.shouldInterceptRequest(request.getUrl());
}
});
webView.loadData("<img src='https://appassets.androidplatform.net/assets/imgs/your_image.png'/>",
"text/html", "UTF-8");
for more information please refer android dev portal links
https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader
https://developer.android.com/jetpack/androidx/releases/webkit?fireglass_rsn=true
Related
I need to load some HTML that I construct at runtime into a WebView and apply a CSS file to it placed in the assets directory. And I already have a base URL that I need to provide to the webview's loadDataWithBaseURL function.
Code Snippet (not applying CSS file):
StringBuffer buff = new StringBuffer();
buff.append("<head>");
buff.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"file:///android_asset/my_css_file.css\"/>");
buff.append("</head>");
buff.append("<div class=\"announcement-header\">");
buff.append("HEADER");
buff.append("</div>");
buff.append("<div class=\"announcement-separator\"></div>");
buff.append("<div class=\"announcement\">");
buff.append("CONTENT");
buff.append("</div>")
WebView.loadDataWithBaseURL(MY_BASE_URL, buff.toString(), "text/html", HTTP.UTF_8, null);
I've looked at these 2 similar issues Issue 1 & Issue 2, but my case is slightly different as I cant give file:///android_asset/ as the base url to the loadDataWithBaseURL function.
Any ideas how I can apply the CSS file in this case ?
If you want to intercept some of the requests from WebView you can do so by overriding shouldInterceptRequest() in WebViewClient like this:
public WebResourceResponse shouldInterceptRequest (final WebView view, String url) {
if (URLUtil.isFileUrl(url) && url.contains(".css")) {
return getCssWebResourceResponseFromAsset();
} else {
return super.shouldInterceptRequest(view, url);
}
}
There is already an excellent detailed answer here https://stackoverflow.com/a/8274881/1112882
HOWEVER
You can not access local file if your base url is not local because of security reasons. So give relative path to your css and then intercept the request.
I would suggest using a pattern to differentiate b/w actual relative and custom relative paths. e.g. use android_asset/my_css_file.css instead of my_css_file.css and modify shouldInterceptRequest() accordingly to always intercept requests starting from android_asset.
I am developing a android app, I need some help from experts, my scenario is below.
I am storing html(text) in SQlite database, in that html I have some images, can I load those images from assets folder.
I load html from database, images(src) in that html should point to assets folder.
Please add your suggestions and comments.
Thanks,
Ashok
Just add the corresponding uri in the src attribute of your img elements using the file:///android_asset/your_image.png uri schema. For example...
<img src="file:///android_asset/image_name.png" />
Make sure you specify the base url when loading the html into the WebView
webView1.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", null);
In my local storage I have the following folder
/data/data/com.test.testapp/files/1/images
and the following file exists.
/data/data/com.test.testapp/files/1/images/f.png
These were stored/retrieved using context.getApplicationContext().getFilesDir()
In my HTML I have "<img src="f.png" />"
I can get TextView working with html/images using an ImageGetter, which effectively returns a drawable from:
Drawable.createFromPath(targetFile.getAbsolutePath());
Where the targetFile is as described above ends up being (/data/data/com.test.testapp/files/1/images/f.png)
However, when I try to use WebViewer as follows (I've pasted in the string for ease):
String url = "file:///data/data/com.test.testapp/files/1";
webViewer.loadDataWithBaseURL(url, content, "text/html", "utf-8", null);
Where content ends up with the same text as my TextView.
All I get is an image placeholder, i.e. it didn't find it.
OMG! ;)
How petty are those people at Google!
All I had to do was append a slash to the url so the base url:
file:///data/data/com.test.testapp/files/1
When changed to
file:///data/data/com.test.testapp/files/1/
Works.
I would like to set some html content in my webview with some pictures.
I've read on the internet i must use loadDataWithBaseUrl to do such a thing because i need to link the folder of images (basUrl) in order.
My html content nicely loads, i can even ran the javascripts perfectly, but for some reason my images cannot be loaded.
Somewhere i've read there are some security reasons and thats why i cant load images from sd card to webview and some says it can be easily done via loadDataWithBaseUrl, so i really dont know which one is true.
Here is my method i tried, maybe with some mistakes so dont be rude:
I got my html file here:
mnt/sdcard/com.mypackage.myproject/3/3.html
My images are here:
mnt/sdcard/com.mypackage.myproject/3/images/Cover.png
And this is my content loading:
myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");
In my html code:
<img src="images/Cover.png" alt="Cover.png" height="820"/>
So as you see i give the baseUrl, and for some reason the webview cannot load my images.
As many said, this can be a solution:
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.loadData(html, "text/html","utf-8");
BUT, i have 700 different html files and there are many images in many different places... so i cannot modify the html code.
Is there a way to link the image folder to my html files to properly use them as a baseUrl?
You have a syntax error in your loading statement. You have to put : after file
myWebView.loadDataWithBaseURL("file:///mnt/sdcard/com.mypackage.myproject/3", myHtml, "text/html", "utf-8", "");
You don't need to put full path of your image into html.
img src="images/test1.jpg"
Instead
img src=\""+ imagePath + "\"
I am throwing HTML to a webview to render. In the HTML I need to load an image that I have in /res/drawable.
I have /res/drawable/my_image.png and code such as this:
final WebView browser = (WebView) findViewById(R.id.my_webview);
String html = new MyHelper(myObject).getHtml();
browser.loadDataWithBaseURL("", html, "text/html", "UTF-8", "");
Where the String html has something like:
<html><head>
<h1>Here is the image</h1>
<img src="my_image.png" />
</head><html>
The question is, what should that image src attribute be to refer to the image in /res/drawable?
This worked in android 2.2
<img src = "file:///android_res/drawable/q1.png" />
where q1.png is in the res/drawable-hdpi folder
I admit I don't know much about WebViews / HTML, but it seems like you're taking the more complicated route for this. There's an easy way to load the HTML file; put it in your assets folder, and then it can be referred to as follows.
WebView webView = new WebView(this);
webView.loadUrl("file:///android_asset/index.html");
setContentView(webView);
Obviously your layout is more complex as you have more than just the WebView so you can't use setContentView() directly, but that's the basic idea. Then to reference an image in that HTML file, I used a <img> tag like so:
<img src="res/drawable/icon.png"/>
Does that work for you?
user302750,
Your method is incorrect. res/drawable/banner300.jpg should be file:///android_res/drawable/banner300.jpg.
banner300.jpg can be in one of the following locations in your project, and android will automatically load the correct one for the device you're using.
res/drawable/banner300.jpg
res/drawable-ldpi/banner300.jpg
res/drawable-mdpi/banner300.jpg
res/drawable-hdpi/banner300.jpg
res/drawable-xhdpi/banner300.jpg
The assets folder is for generic resources that you don't need different versions of. An example might be an XSL template, or something of that nature.
MikeNereson, your response to your problem is also incorrect, drawable resources should be contained in the res directory.
Here's an example from my own project. I output html, exactly like this:
<img src="file:///android_res/drawable/stats_btn.png"/>
If using an ldpi device, I get the ldpi image, if using hdpi or mdpi, I get the appropriate one for those as well. Android resolves file:///android_res/drawable/stats_btn.png to one of the following resources that I have in my project.
./res/drawable-ldpi/stats_btn.png
./res/drawable-hdpi/stats_btn.png
./res/drawable-mdpi/stats_btn.png
From my tests the path, "file:///android_res/drawable/q1.png" only works with 2.2+. For 2.1 that gives a file not found error. Moving the resource to assets will work but that isn't really feasible if you want to make use of the drawable features (meaning you'd need a copy of the image in each folder...).
Answers involving file:// URLs may not work any more as of Android 4.0. See answer to this question. A way that will work is in the answer here.
I have the exact same problem, but neither placing the image file in res/drawable (which I first had to create, I hust had drawable-hdpi, -ldpi and -mdpi already existing) or using the file:///asset/ URL worked for me.
Here is what I do:
Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
String summary = "<html><body><div style=\"background:red; width:300px; height:50px;\"></div><img src=\"res/drawable/banner300.jpg\"/></body></html>";
mWebView.loadData(summary, "text/html", "utf-8");
Then in res/drawable I placed the banner300.jpg - but it does not show up. Any ideas?
You load the drawables like you would anywhere else in your code...
http://developer.android.com/guide/topics/resources/drawable-resource.html
Resources res = getResources();
Drawable drawable = res.getDrawable(R.drawable.myimage);
also #MikeNereson using Android, you can only directly access raw files that are located in the assets directory and SDCard.