I store my html page in asset folder and insert it to my sqlite.
i store my html page as text in sqlite.
Anyone know how to load my html page into webview?
i've tried to add some code, and not working
if (info.size() != 0) {
lu.setText(info.get(2));
WebView wb = (WebView) findViewById(R.id.mywebview);
wb.loadDataWithBaseURL("file:///android_asset/"+lu,"text/html","UTF-8",null);
}
You question already has well elaborated answers here on SO Webview load html from assets directory... I believe one of the answers should solve your problem... Hope that helps gudluck.
what is lu?, should it be a comma instead of +?
In any case, the method loadDataWithBaseURL takes 5 arguments:
base, data, mimetype, encoding, historyUrl
E.g:
wbHelp.loadDataWithBaseURL("file:///android_asset/",
readAssetFileAsString("index.html"),
"text/html",
"UTF-8",
null);
readAssetFileAsString is as follows:
private String readAssetFileAsString(String sourceHtmlLocation)
{
InputStream is;
try
{
is = getContext().getAssets().open(sourceHtmlLocation);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
return new String(buffer, "UTF-8");
}
catch(IOException e)
{
e.printStackTrace();
}
return "";
}
Related
What is the best way to load a jpeg from an install-time asset pack and show it on a WebView?
I got it working in case the jpeg is a regular asset, however, I couldn't get it working optimally with install-time assets:
WebView webView = this.findViewById(R.id.webView);
String sHtmlTemplate = "<img src='file:///android_asset/files/"+file+".jpg' width='100%'/>";
webView.loadDataWithBaseURL("file:///android_asset/files/", sHtmlTemplate, "text/html", "utf-8", null);
UPDATE:
The solution below works, but it is slow. Is there a way to load images directly from InputStream or install-time assets?
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024000];
int count;
while(-1 != (count = is.read(buffer, 0, buffer.length))) {
baos.write(buffer, 0, count);
}
baos.flush();
byte[] imageRaw = baos.toByteArray();
baos.close();
is.close();
String image64 = Base64.encodeToString(imageRaw, Base64.DEFAULT);
String html = String.format("<img width='100%%25' src='data:image/jpeg;base64,%s' />", image64);
webView.loadData(html, "text/html; charset=UTF-8", null);
Thanks
Perhaps the WebView is not the most optimal way to show a jpg in this case. I ended up using another control:
com.ortiz.touchview.TouchImageView touchView = this.findViewById(R.id.touchImageView);
try {
AssetManager assetManager = getAssets();
InputStream is = assetManager.open(songNo + ".jpg");
Drawable d = Drawable.createFromStream(is,"src");
touchView.setImageDrawable(d);
}catch(Exception e){
Log.i("xxx", e.getMessage());
}
I'm trying to host an Angular app with nanohttpd, so I put the files into a dist/ folder inside the assets folder of the android app. Now I want to serve the angular files but I keep getting this kind of errors in console (it only appears when trying to request fonts and images):
GET http://hostname/font.woff2 200 (OK)
This is the code that I use to serve the files:
public Response serve(IHTTPSession session) {
String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
String content;
byte[] buffer;
Response res;
InputStream is;
try {
is = this.assetManager.open("dist/" + filepath);
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer);
content = content.replace("old string", "new string");
if (typeText(mimeType)) { // If mimeType is text/html or application/json
res = newFixedLengthResponse(content);
}else{ // This is when I try to serve fonts or images
res = newFixedLengthResponse(Response.Status.OK, mimeType, is, size); // Not working
}
}catch(IOException e) {
res = newFixedLengthResponse("Error!");
}
return res;
}
I think that maybe the font files are getting compressed, or the size is not the real size of the InputStream. Also when loading the page, vendor.js takes a lot to download, and after that, it stops downloading the rest of the files.
I also get this error on the logcat:
Communication with the client broken, or an bug in the handler code
I fixed it like this:
public Response serve(IHTTPSession session) {
String filepath = getFilepath(session.getUri()); // Get filepath depending on the requested url
String mimeType = getMimeType(filepath); // Get mimetype depending on the extension of the filepath (font/woff, font/woff2, font/ttf, image/x-icon, text/html, application/javascript)
String content;
byte[] buffer;
Response res;
InputStream is;
try {
is = this.assetManager.open("dist/" + filepath);
if (!typeText(mimeType)) { // If mimeType is font/<something> or image/<something>
return newFixedLengthResponse(Response.Status.OK, mimeType, is, -1);
}
int size = is.available();
buffer = new byte[size];
is.read(buffer);
is.close();
content = new String(buffer);
content = content.replace("old string", "new string");
}catch(IOException e) {
content = "Error!";
}
return newFixedLengthResponse(content);
}
I really don't know what happend, but it works really well this way. It seems to me that is.available() was not returning the right file size.
I am able to download and view from url ending with *.pdf with the below code
private static final int MEGABYTE = 1024 * 1024;
public static void downloadFile(String fileUrl, File directory){
try {
URL url = new URL(fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
//urlConnection.setRequestMethod("GET");
//urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(directory);
int totalSize = urlConnection.getContentLength();
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while((bufferLength = inputStream.read(buffer))>0 ){
fileOutputStream.write(buffer, 0, bufferLength);
}
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
but I have tried to download PDF file with url ending with .aspx as its generate PDF dynamically and its not working .
I have also tried to embed with webview with google doc url "http://docs.google.com/viewer?url="+URL but its also not working.
Can anyone help in this?
'.aspx' Is ASP.NET page that is actually web form.
Web forms are contained in files with a ".aspx" extension; these files
typically contain static (X)HTML markup or component markup.
So what you are loading is a simple HTML page rendered on server side. So you cannot use it to view PDF - in PDF viewer.
Instead of openning '.aspx' from file load this url into WebView - this will work only if there are no additional security on the site you are pointing to.
In case of Google Docs the link you are providing to the WebView should be sharing links like following:
https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing
Where x's are part of hash. To get this link - click on Share option for the document and then get shareable link.
Before WebView reaches pdf document it could receive few redirects that potentially will be handled by Android itself. To avoid this you need to override WebViewClient#shouldOverrideUrlLoading like in following example:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing");
Also you could get direct link to the file using sharable url you get above:
change this:
https://drive.google.com/file/d/xx-xxxxxxxxxxxxxxx/view?usp=sharing
to this:
https://drive.google.com/uc?export=download&id=xx-xxxxxxxxxxxxxxx
or to this:
https://docs.google.com/document/d/xx-xxxxxxxxxxxxxxx/export?format=pdf
I am new to android development.
I am using webview to display HTML pages in android, but only the text shows up.
Can you please help me with the problem.
thank you in advance, would be very helpful.
WebView view = (WebView) this.findViewById(R.id.webView);
try{
InputStream stream = this.getAssets().open("Capacitor Code Calculator.html");
int streamsize = stream.available();
byte[] buffer = new byte[streamsize];
stream.read(buffer);
stream.close();
String html = new String(buffer);
view.loadData(html,"text/html", "utf-8");
}
catch (Exception e){
e.printStackTrace();
Does it have to do something with "text/html" in view.loadData(html,"text/html", "utf-8");
I have my html and image file both in assets folder.
It might be that you can't have spaces in your file name in the line:
InputStream stream = this.getAssets().open("Capacitor Code Calculator.html");
What is the url you're giving in the <img> tag? Do you have spaces in this name also?
WebView view = (WebView) this.findViewById(R.id.webview);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
view.setWebViewClient(new WebViewClient());
The last setWebViewClient() displays the images .....finally relieved :)
Hope it helps.
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");