Android WebView doesn't show image - android

I have an html file locally with local images. I'm trying to display it using
webView.loadDataWithBaseURL(contentPath, content, "text/html", "UTF-8", null);
where contentPath is the file path and the content is the actual html.
It is showing the html fine but the problem is I have images inside it that don't show. an example is
<img src="images/philippines-map.png" class="full_page_image" alt="full page image for Philippines map" style="max-width:100%">
I checked and the location is right. Instead of the image it is showing a box with the alt text inside it. Anyone knows what's going on?
here are the variables initiation code
contentPath = context.getFilesDir() + "/" + pageFolderName + "/" + pageName;
content is initiated by
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new File(contentPath)), "ISO-8859-1"));
String line;
while ((line = reader.readLine()) != null) {
fileData.append(line).append('\n');
}
reader.close();
content = fileData.toString();

Change webView.loadDataWithBaseURL(contentPath, content, "text/html", "UTF-8", null); to webView.loadDataWithBaseURL("file://" + contentPath, content, "text/html", "UTF-8", null);.

In Android , file names and extenstions are case sensitive .
Check both file name and extenstion of your image are lower case .

Related

WebView not loading local HTML in Android?

I am trying to load a local html file in a WebView but it always give error
new::ERR_FILE_NOT_FOUND
I have attached the images of code I am using and the file directory. I have tried it with different directories but it didn't work.
Changed the file directory to res folder, res/raw folder.
tried to load different html
it does load the webvlinks
Path and the code image is here
It is good to place all file assets files in the assets folder.
So Add your HTML file to the assets folder and load webview with below code.
webview.loadUrl("file:///android_asset/privacy_policy.html");
Or if you don't want to move the file from that "sampledata" folder, then use below code.
webview.loadUrl("file:///sampledata/privacy_policy.html");
I had the same problem, I found this answer here: https://inneka.com/programming/android/loading-html-file-to-webview-on-android-from-assets-folder-using-android-studio-2/
try {
AssetManager assetManager = this.getAssets();
InputStream stream = assetManager.open("editor.html");
BufferedReader r = new BufferedReader(new InputStreamReader(stream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
total.append(line).append("\n");
}
webView.loadDataWithBaseURL(null, total.toString(), "text/html", "UTF-8", null);
} catch (Exception xxx) {

Issues in reading of data from text file Android Development

i have been experiencing problem reading data from text files which resides in my internal storage of my mobile phone. My code is as below:
public void recommend(View view) {
Context context = getApplicationContext();
String filename = "SendLog.txt";
TextView tv = (TextView)findViewById(R.id.textView134);
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
tv.getText();
tv.setText(line);
}
} catch (IOException e) {
e.getStackTrace();
}
I'm not getting any data input to my mobile phone. My "SendLog.txt" file reside in /storage/emulated/0/SendLog.txt directory. Anyone can assist me? I want to read everything from the text file and display in textView134. Anyone can assist?
Thank you in advance!
"/storage/emulated/0/SendLog.txt" is located on the External Storage, not the internal.
Instead of context.openFileInput(filename) you should be using Environment.getExtenalStorageDirectory() for example,
FileInputStream fis = new FileInputStream(new File(Environment.getExtenalStorageDirectory(), filename));
Though you will need to handle possibilities such as the External Storage being unavailable / unmounted.
You will also need the manifest permission to read external storage, or alternately to write it if you plan to do that as well (you only need one of the two, as write implies read).
You are building a string using stringbuilder but instead are settexting line. The result is last line in file, which may be an empty line

How to change decoration of a local HTML file to show it on the WebView in Android

In my android application I used to open a local HTML file like the one below:
mPath = ... myHTML.html
webView.loadUrl("file:///" + mPath);
Now I want to make some changes in my HTML file such as font size, align from left to right and right to left and ... I guess that I can do that by adding a CSS file to head of my HTML, but the problem is I have no idea how to access the source of my HTML file and convert it to string.
Is there any better way to change the decoration of a local HTML file? if not, how can I access the source of my HTML file?
OK I'm answering my own question. I used Panos's answer on: https://stackoverflow.com/a/13357785/1572408
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
In onCreate():
File fl = new File(myLesson);
FileInputStream fin;
fin = new FileInputStream(fl);
String ret = convertStreamToString(fin);
ret = ret.replace("<body>","<body align='right' style='font-size:14pt;>");
webView.loadDataWithBaseURL("file:///android_asset/", ret, "text/html",
"UTF-8", "");

how set text color of webview in android

i am trying to change text color of webview with this code
String message ="<font color='white'>"+"<u>"+
"text in white"+ "<br>" +
"<font color='cyan'>"+"<font size='2'>"+
" text in blue color "+"</font>";
webview.loadData(message, "text/html", "utf8");
but i have some html pages. store in my sdcard then how can i change text color..
i use
webViewRead.loadUrl(url);
url is path of my file.
You have to give the path of that file like this.
String extStorageDirectory = Environment.getExternalStorageDirectory()
.toString() + "/folder_name";
File directory = new File(extStorageDirectory);
File fileInDirectory = new File(directory,file_name.html);
//Read text from file
StringBuilder html_text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(fileInDirectory));
String line;
while ((line = br.readLine()) != null) {
html_text.append(line);
html_text.append('\n');
}
}
catch (IOException e) {
//You'll need to add proper error handling here
}
then use this html code for edit
String message ="<font color='white'>"+"<u>"+"text in white"+ "<br>" +"<font color='cyan'>"+"<font size='2'>"+" text in blue color "+"</font>";
webview.loadData(message, "text/html", "utf8");
htmlDetail = dbValues.getContent(3);
tvDescription3.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
String finalHtml = "<html><head>"
+ "<style type=\"text/css\">li{color: #00f} span {color: #000}"
+ "</style></head>"
+ "<body>"
+ htmlDetail
+ "</body></html>";
tvDescription3.loadData(finalHtml, "text/html; charset=UTF-8", null);
put your file path as
String htmlPath = "file:///mnt/sdcard/test/11.html";
String baseUrl = "file:///mnt/sdcard/test/";
webView.loadDataWithBaseURL(baseUrl, message, "text/html", "utf-8", null);
webView.loadUrl(htmlPath);
In order to change a WebView’s background color there is a standard way:
mWebView.setBackgroundColor(Color.Black);
In order to change a WebView’s text font color there is no standard way:
Either you change the font through the html code, or you do this:
htmlData="<font color='black'>" + htmlData + "</font>";
mWebView.loadDataWithBaseURL(null, htmlData, "text/html", "UTF-8", null);

How to display image with WebView loaddata?

I've got the following
String urlStr = "http://example.com/my.jpg"
String mimeType = "image/jpeg";
String encoding = null;
String pageData = ""; // This is data read in from an HttpURLConnection
webview.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
but when I run this, all I see is a blue question mark instead of my image. What is the proper way to handle displaying an image in a WebView with loadData?
Edit:
Is there a way to do this without passing pageData as <img src="http://example.com/my.jpg/"> ? It seems silly that loadData takes a mime-type if it can only handle "text/html". Especially since the javadoc lists "image/jpeg" as an example mime-type that you might pass in.
It is possible to embedd the base64 encoded imagedata direct into the <img>-tag:
<img src="data:image/jpeg;base64,base64DataHere" />
Here an example for creating the <img>-tag (I use an byte-array instead the String for raw-data, because in my tests an String as source didn't work - I assume that String can't handle binary-data):
byte[] imageRaw = yourImage;
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
The Base64-class was introduced with API v.2.2 - for older API-versions you can copy the sourcefile from git and integrate it in your app. It should work with older API-versions.
Or you can use one of the alternative classes for base64-encoding like Base64Coder.
And here the complete working code for retrieving, converting and showing the image:
byte[] imageRaw = null;
try {
URL url = new URL("http://some.domain.tld/somePicture.jpg");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
out.flush();
imageRaw = out.toByteArray();
urlConnection.disconnect();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String urlStr = "http://example.com/my.jpg";
String mimeType = "text/html";
String encoding = null;
String pageData = "<img src=\"data:image/jpeg;base64," + image64 + "\" />";
WebView wv;
wv = (WebView) findViewById(R.id.webview);
wv.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, urlStr);
Use this.. solve the problem of images load in webview.
WebView webView = (WebView)findViewById(R.id.webView1);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
String url ="Path of image";
String imgSrcHtml = "<html><img src='" + url + "' /></html>";
webView.loadData(imgSrcHtml, "text/html", "UTF-8");

Categories

Resources