#Android display /res/viewable in WebView - android

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.

Related

How to load local html pages to android

I want to load local HTML pages in to a WebView. I know how to do it in iPhone. Can any one tell me the way to do it in android.
How to do the below page in android?
put your file to asset folder than you can use the code below
WebView webview = (WebView) findViewById(R.id.yourwebview);
webview .loadUrl("file:///android_asset/UI/mylocalhtmlfile.htm");
use this.
yourWebView.loadUrl("file:///android_asset/yourfileName.html");
Create a TextView textArea and set it's text with the html string
You can define the string as a part of strings.xml file with your html tags and make sure you call getText(T.string.your_html_string) to fetch the html based text
<string name="your_html_text">"Press <font fgcolor="#ffffffff"><b>Menu</b></font> and touch:\n
\n<li><font fgcolor="#ffffffff"><b>Create </b></font> to create\n</li>
\n<li><font fgcolor="#ffffffff"><b>Delete All</b></font> to delete all\n</li>
</string>
and setText like
textArea.setText(getText(R.string.your_html_text));
The easiest way would probably be to put your web resources into the assets folder then call
webView.loadUrl("file:///android_asset/filename.html");

How to embed HTML code in Android app?

I am writing an app for which I need to embed HTML object in the Android app, I followed the tutorial given here: http://mobile.tutsplus.com/tutorials/android/android-sdk-embed-a-webview-with-the-webkit-engine/ and modified the code accordingly, following is the code, but I am getting a white screen...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView engine = (WebView) findViewById(R.id.web_engine);
engine.getSettings().setJavaScriptEnabled(true);
engine.getSettings().setPluginsEnabled(true);
engine.getSettings().setAppCacheEnabled(false);
engine.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String data = "<html>" +
"<body>" +
"bb"+
"<object width=\"450\" height=\"300\" align=\"middle\"><param name=\"movie\" value=\"http://www.raaga.com/widgets/top10/widgettopten.swf?l=H&q=1\" /><param name=\"wmode\" value=\"transparent\"><embed src=\"http://www.raaga.com/widgets/top10/widgettopten.swf?l=H&q=1\" width=\"450\" height=\"300\" align=\"middle\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" FlashVars=\"gig_lt=1312323434023&gig_pt=1312325057958&gig_g=2\"/> <param name=\"FlashVars\" value=\"gig_lt=1312323434023&gig_pt=1312325057958&gig_g=2\" /></object>"+
"gg"+
"</body>" +
"</html>";
engine.loadData(data, "text/html", "UTF-8");
}
}
The object that I want to embed is:
<object width="450" height="300" align="middle"><param name="movie" value="http://www.raaga.com/widgets/top10/widgettopten.swf?l=H&q=1" /><param name="wmode" value="transparent"><embed src="http://www.raaga.com/widgets/top10/widgettopten.swf?l=H&q=1" width="450" height="300" align="middle" type="application/x-shockwave-flash" wmode="transparent" FlashVars="gig_lt=1312323434023&gig_pt=1312326303531&gig_g=2"/> <param name="FlashVars" value="gig_lt=1312323434023&gig_pt=1312326303531&gig_g=2" /></object>
Put the file in the /assets directory, you can access it with the file:///android_asset/ directory.
Instead of putting the html in code the assets folder is where you can put static data files such as HTML and its related CSS, images, and JavaScript files, etc. Then you can use WebView.loadUrl(). This has the advantage of not having to be in code with Java String escapes and cumbersome editing. You will be able to create the file(s) separately, in your favorite web project editor, then copy and paste them. If you need to edit the file at runtime you can still load the file from the assets directory and still not have to worry about Java String escapes and cumbersome editing. Then apply the edits and pass to WebView.loadData().
To help debug this problem implement WebChromeClient.onLoadResource and check out the console message tutorial.
Don't forget to use PackageManager.getPackageInfo() to check if flash is available. If its not you can give the user the option to download it from the market.
Android has no official Flash viewer, so it doesn't know what to do with an embedded SWF.
If you put other (visible) HTML in your code, you should be able to see it in the view.
If you try to access your SWF through the webbrowser, you should get a broken/missing plugin icon.
Embedding HTML files is very simple, and loading it into WebView is even simpler. Here:
Create your HTML file, and put it in your project's assets file. in my case: "proj/assets/license.html"
WebView w = new WebView(this);
// Load the asset file by URL. Note the 3 slashes "file:///".
w.loadUrl("file:///android_asset/license.html");
That's it.
Did you declare the Internet permission in your Android manifest? In order to access the SWF which is on a remote server you will need that.
You need to enable plugins in your webview:
engine.getSettings().setPluginsEnabled(true);

named anchor not working webview android

In my little app i have a webview, i only have one html file in the assets folder. I'm trying to use a named anchor to make a Jump Link but it doesn't work. It only says Web page not available I don't know where i'm wrong. Is it trying to load a html file with the name tag i provided?
WebView mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.loadUrl("file:///android_asset/topics.html");
EDIT:
here's my html
<html>
<body>
<a href=”#tip”>Go somewhere</a>
//a lot of <br/>...
Somewhere
<a name=”tip”></a>
</body>
</html>
And yes the topics.html is under assets/
Where does your program fail - with the loading or when you click the anchor? It sounds like the problem is with your HTML file, so you should probably show the code from that instead. :) Also, the full LogCat output is handy too. The more info the merrier.
I recently implemented a WebView, the HTML code is extremely straight-forward (since I know close to no HTML and just wanted an easy way to display documentation). A simple anchor is just this for example:
Navigating the application
...
<a name="q1"></a>
<p><b>Navigating the application</b></p>
<p>...sliding motion (to the left or to the right) with your finger...</p>
If your program is failing at the actual loading part, then ensure that you have placed the topics.html file correctly in the /assets/ folder in your project folder. It has to be at the very root of your project folder - ie. workspace\<projectname>\assets\topics.html
Your code for loading the webpage looks fine.

Conflict between Windows and Android?

Please help me solve this file path conflict:
As you know, many HTML pages use relative paths starting with a "/" for the href attribute of link tags. For example: link href="/links/style.css".
In my code, I'm using loadDataWithBaseURL for a WebView to set a relative path name. If I give like this:
String webContent=//whole html page;
mWebView.loadDataWithBaseURL("file:///sdcard/mibook/pg90/",new String(webContent), "text/html", "UTF-8","" );
Result: No effect in WebView because (I felt) it takes two '/' while appending to pathname.
If I edit my HTML page by removing the first "/" from the href tag, then the WebView renders properly.
But my problem is that I don't want to edit HTML content as above. Any solution?
Javadoc of loadDataWithBaseURL states:
Note for post 1.0. Due to the change in the WebKit, the access to asset files through
"file:///android_asset/" for the sub resources is more restricted. If you provide null
or empty string as baseUrl, you won't be able to access asset files. If the baseUrl is
anything other than http(s)/ftp(s)/about/javascript as scheme, you can access asset
files for sub resources
So basically only allowed URL for file:/// scheme is file:///android_asset/ where files are in your asset folder.

Android Development: Using Image From Assets In A WebView's HTML

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

Categories

Resources