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);
Related
I have an html file in asset folder and i would like to load it in a webview. I would like to use the string, and not the file in order to replace the content of file when i want (keep only one file and change the content i want to display).
For example my html file is like this:
<!DOCTYPE html>
<html>
<head>
<title>This is demo</title>
</head>
<body>
<p data-height="265" data-theme-id="0" data-slug-hash="dYPxYp" data-default-tab="html,result" data-user="sckarolos" data-embed-version="2" data-pen-title="SVG Shape Example" class="codepen">
See the Pen SVG Shape Example
by sckarolos (#sckarolos) on CodePen.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>
</body>
</html>
I have these two methods for reading the html file from assets as string and load it in a webview:
private String getHtmlFromAsset() {
InputStream is;
StringBuilder builder = new StringBuilder();
String htmlString = null;
try {
is = getAssets().open(htmlFilename);
if (is != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
htmlString = builder.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return htmlString;
}
/**
* Loads html page with the content.
*/
private void loadHtmlPage(WebView webView) {
String htmlString = getHtmlFromAsset();
if (htmlString != null) {
webView.loadDataWithBaseURL(null, htmlString, "text/html", "UTF-8", null);
}
else
Toast.makeText(this, "No such page", Toast.LENGTH_LONG).show();
}
And in my activity i use webview like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
AssetManager assetManager = getAssets();
//try to display html content
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setAllowContentAccess(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setAllowFileAccessFromFileURLs(true);
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
loadHtmlPage(webView);
}
On debuging i can see that my file read successfully and my string has the content of html file. But when i am trying load it in webview, the result is nothing. If i try to load the local html file using this:
webView.loadUrl("file:///android_asset/myFile.html");
then the file loads and displays successfully.
I suppose that my fault is in the way i use the string that i take back from getHtmlFromAsset and pass in loadHtmlPage.
Any help will be appreciated.
Here, code pan required javascript access so when link load you need to provide javascript access. this is working code also check into my emulator. Also, don't forget to give internet permission on the manifest.
XML:
<WebView
android:id="#+id/wv"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
JAVA:
String str = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
" <title>This is demo</title>\n" +
"</head>\n" +
"<body>\n" +
"\n" +
"<p data-height=\"265\" data-theme-id=\"0\" data-slug-hash=\"dYPxYp\" data-default-tab=\"html,result\" data-user=\"sckarolos\" data-embed-version=\"2\" data-pen-title=\"SVG Shape Example\" class=\"codepen\">\n" +
" See the Pen SVG Shape Example\n" +
" by sckarolos (#sckarolos) on CodePen.</p>\n" +
"<script async src=\"https://production-assets.codepen.io/assets/embed/ei.js\"></script>\n" +
"\n" +
"\n" +
"</body>\n" +
"</html>";
WebView wv = findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
wv.loadData(str, "text/html", "UTF-8");
I can show up HTML file content in android webview well.Now how could i pass parameter into HTML file.For ex.my HTML content has an video player
i need to pass dynamic values(URL) into HTML file for playing dynamic video.My HTML file is located on asset folder.How could i do this?
Thanks.
I came upon this problem today, however I needed this to work with UTF-8 encoding, so this was my approach, hopefully it will help someone and clarify some of the previous answers to this question.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>%ERR_TITLE%</h1>
<h2>%ERR_DESC%</h2>
</body>
</html>
Java:
String content = IOUtils.toString(getAssets().open("error.html"))
.replaceAll("%ERR_TITLE%", getString(R.string.error_title))
.replaceAll("%ERR_DESC%", getString(R.string.error_desc))
mWebView.loadDataWithBaseURL("file:///android_asset/error.html", content, "text/html", "UTF-8", null);
As for IOUtils:
http://commons.apache.org/proper/commons-io/download_io.cgi
Instead of passing directly the video URL (following you example), i would have used tokens in the Html file. For example:
<embed src="$VIDEO_URL$" autostart="false" />
where the $VIDEO_URL$ will be the token wich will be replaced during the runtime with a real video URL.
Also, since you cannot change the contents of your asset folder during runtime you should load the html file contents into a String variable and use the replace method to replace the token with a real URL and, finally, pass that string to your webview. Something like this:
//The html variable has the html contents of the file stored in the assets folder
//and real_video_url string variable has the correct video url
html = html.replace("$VIDEO_URL$", real_video_url);
webview.loadData(html, "text/html", "utf-8");
If i would like to have something dynamic in my HTML i would have an html with dynamic parts written like this:
<B>%NAME%</B>
Then i would load my HTML:
String template = Utils.inputStreamToString(assets.open("html/template.html"));
then
Then i would replace all dynamics parts with what i want like this:
String data = template.replaceAll("%NAME%", "Alice McGee");
then i would pass it to my webView!
WebView webView = new WebView(this);
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "utf-8", null);
I managed to pass variables in a different way.
My problem was that everytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In onCreate method after setting up myWebView I did the following:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String urlString)
{
Log.i("onPageFinished", "loadVariables("+newURL+")");
if(newURL!="")
myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
jsInterface = new JSInterface(this,myWebView);
myWebView.addJavascriptInterface(jsInterface, "Android");
if (savedInstanceState != null)
{
// retrieve saved variables and build a new URL
newURL = "www.yoururl.com";
newURL +="?var1=" + savedInstanceState.getInt("key1");
newURL +="?var2=" + savedInstanceState.getInt("key2");
Log.i("myWebApp","NEW URL = " + newURL);
}
myWebView.loadUrl("www.yoururl.com");
So, what it happens is that first I load the page with the default URL (www.yoururl.com) and onPageFinished I call a new javascript method where I pass the variables.
In javascript loadVariables function looks like this:
function loadVariables(urlString){
// if it is not the default URL
if(urlString!="www.yoururl.com")
{
console.log("loadVariables: " + urlString);
// parse the URL using a javascript url parser (here I use purl.js)
var source = $.url(urlString).attr('source');
var query = $.url(urlString).attr('query');
console.log("URL SOURCE = "+source + " URL QUERY = "+query);
//do something with the variables
}
}
here assets means what?
String template = Utils.inputStreamToString(assets.open("html/template.html"));
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
I'm loading an html asset page into a WebView using
webMain.loadUrl("file:///android_asset/record.html");
which works fine, but inside the html are a number of places where I'd like to use information from the app. For instance, the HTML may contain text that reads "[Custom]". Is there a way I can replace that word with information passed from the application?
This is an old and already accepted question, however I am sure that the problem can be solved in more elegant way by using javascript.
Keep the html file in your assets folder and surround the text which you want to replace into with div elements with unique id's.
<html>
<head> ... <head>
<body>
Static text
<div id="replace1">replace me</div>
<div id="replace2">replace me too</div>
More static text ...
</body>
</html>
Now create a javascript function which will replace the innerHtml of a div with an id:
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
This function will be best placed directly in the html file, update the <head> section to look like this:
<head>
...
<script type="text/javascript">
function replace(id, newContent)
{
document.getElementById(id).innerHTML = newContent;
}
</script>
</head>
Now we need to call the javascript function from from the WebView Android api:
WebView helpView = (WebView)findViewById(R.id.helpView);
helpView.getSettings().setJavaScriptEnabled(true);
helpView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:replace('replace1', 'new content 1')");
view.loadUrl("javascript:replace('replace2', 'new content 2')");
}
});
helpView.loadUrl("file:///android_asset/help.html");
Using this you will avoid reading potentially large data into memory and running expensive operations on it unnecessarily.
This is worked for me.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Payment Demo</title>
</head>
<body>
<div>
<input type="text" id="uname " name="uname " value="">
<input type="text" id="pass" name="pass" value="">
</div>
</body>
</html>
This is java code.
WebView wb = (WebView) findViewById(R.id.webView1);
wb.loadUrl("file:///android_asset/web1.html");
wb.getSettings().setJavaScriptEnabled(true);
wb.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView web, String url) {
// TODO Auto-generated method stub
String uname = "email#mail.com";
String pass = "******";
web.loadUrl("javascript:(function(){document.getElementById('uname').value = '"+uname+"';})()");
web.loadUrl("javascript:(function(){document.getElementById('pass').value = '"+pass+"';})()");
}
});
Actually I do not understand why the file size of record.html will affect maintainence of the code. Read the html string (using Java reader class or what ever) from the html file in asset, use replaceAll function with Regex to replace all the [Custom] in the html file. How long the html is should not really affect how you maintain the code. It should rather be a performance problem, or the string is really really long that exceeds the java String limit.
some code I have used before :
InputStream is = getApplicationContext().getAssets().open("details/product_jsmodify.html");
Reader r = new InputStreamReader(is);
String details = Utils.readertoString(r);
details = details.replace("%product_name%",productName );
Utils is my class doing the conversion to string. I am not using Regex here as I am only replacing word for once. Then I load the string like Cata does. It is quite clean I suppose.
Yes you can do that by loading your page in a String and then load that string in your WebView.
Eg:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
Taken from here
This one worked for me, with the html along with the text and images.
InputStream is = getAssets().open(html_name);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
str = str.replace("InitialTextToBeReplaced", "TextAfterReplacement");
//Now instead of webview.loadURL(""), I needed to do something like -
webView.loadDataWithBaseURL("file:///android_asset/", str, "text/html", "UTF-8",null);
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