Android webview images not showing after loading once - java

In android, I'm loading a local html with local images into a webview. On the emulators and even on one newer android device I tested, everything works fine - there are no problems. However, I have a much older device (with android 2.3.4) that has an issue. When I first load the html file, the images display fine. When I click the phone back button, then navigate back to the page, the images disappear. I'm trying to figure out if this is a common problem or just a problem with an old phone.
Here is the loading file:
w = (WebView) findViewById(R.id.webview1);
w.getSettings().setJavaScriptEnabled(true);
w.getSettings().setBuiltInZoomControls(false);
w.getSettings().setDefaultTextEncodingName("utf-8");
InputStream is;
try {
is = getAssets().open("Learn/TrigGraphing.html");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String str = new String(buffer);
w.loadDataWithBaseURL("file:///android_asset/Learn/Images/", str, "text/html", "utf-8", "file:///android_asset/Learn/TrigGraphing.html");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here is the html:
<img id="img03" class="images" src="file:///android_asset/Learn/Images/UnitCircle10.png"/>
There is also one twist - I resize the images if they're too big to fit on screen. This is mainly for tablets. On the html body onload() function, I execute the following javascript:
function checkImgSize() {
if($(document).width() > $(window).width()) {
windowWidth = $(window).width();
var elements = document.getElementsByClassName("images");
for (var i=0; i<elements.length; i++) {
currentImgWidth = elements[i].width;
currentImgHeight = elements[i].height;
newImgWidth = Math.round(0.85*windowWidth);
newImgHeight = (newImgWidth/currentImgWidth)*currentImgHeight;
elements[i].style.width = newImgWidth;
elements[i].style.height = newImgHeight;
}
}
I looked at this resize function and I dont see why it would make the images disappear if they loaded a second time but I'm not sure. Anybody have any advice?

I solved my own problem after thinking about it for awhile. Apparently the webpage was loading from the cache after it loaded once and for some reason this messed it up - though i'm still not sure why. I just cleared the cache with "w.clearCache(true);" before loading the html and it works fine now.

I solved my problem by using css background property instead of img tag.
Instead of this:
<img width="100" height="100" class="images" src="file:///android_asset/Learn/Images/UnitCircle10.png"/>
I used this:
<div style="width: 100px; height: 100px; background:url(file:///android_asset/Learn/Images/UnitCircle10.png); background-size:cover; "></div>

Related

Java : Determine if String is an URL(without www or http), take its screenshot

I am working on a Spring-MVC webapplication in which we are trying to get a screenshot of an URL. Currently I am using PhantomJS for that task, but it's too slow(>10seconds). Also, the URL's have to be with http/https and www for detecting that it's an URL. As this is a chat application, there can be simple URL's which users add like helloworld.com. Any help would be nice. Thank you.
Code:
String[] words = message.split(" ");
for( String item : words ){
boolean val = ResourceUtils.isUrl(item);
if(val){
urlIdentifier = calcUrl(item);
break;
}else {
System.out.println("Url false is "+item);
}
}
if(urlIdentifier!=null){
replies.setPreviewIdentifier(urlIdentifier);
input.put("preview_identifier",urlIdentifier);
}
Method to calculate screenshot :
private String calcUrl(String website){
try {
String identifier = String.valueOf(new BigInteger(130, random).toString(32));
String previewLocation = msg + "chatthumbs/" + identifier ;
Process proc = Runtime.getRuntime().exec("phantomjs --ssl-protocol=any " +
"/home/deploy/phantom/rasterizepdf.js " +" "+website+" " +previewLocation);
proc.waitFor();
BufferedImage image = ImageIO.read(new File("/home/akshay/testme.png"));
if(image!=null){
if (image.getWidth() > image.getHeight()) {
image = Scalr.resize(image, Scalr.Mode.FIT_TO_HEIGHT, 250, 250);
} else {
image = Scalr.resize(image, Scalr.Mode.FIT_TO_WIDTH, 250, 250);
}
image = Scalr.crop(image, 250, 250);
ImageIO.write(image, "png", new File(previewLocation));
}
return identifier;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
Any help would be nice. Thank you.
(a) I think the process of taking a screen shot is taking time. Is this code running on the same device as the chat screen? Why not use java.awt.Robot to take the screen shot ? or just save the text why do you need a screen shot?
(b) Is the system too busy/ Use on a SSD to see if faster?
(c) But curious as to the end application, is this part of a web app? How will your code run on the client systems? Or will you java agent be installed on all user systems that monitors the web page and takes screen shots? Then why use a web page, use a java app to chat, and parse the text as typed.
Parsing the text. What if user types/ pastes a long message? Are you parsing everything once or on change? Think of ways to improve that if it seems to be a problem. Ignore if not the immediate issue now.
Also if the msg is too long the parsing can take a lot of time. maybe process after every key press or change event (if paste) keep local js copy of previous text to get diff?

IE caches and references old images for h:graphicImage

I have an web application that uses JSF for form submission. I have a user select an image from a list followed by filling out and submitting a form. I then use the selected image and form input to annotate the image with the information. I then process a pdf file using the annotated images and email it to the user. After processing, I give the user the option to navigate back to the image selection page, or use the same images and go back to the form. Here is the jsf/html for the form that allows the user to navigate to their new page:
<h:form id="form" method="post">
<div>
<h:commandButton value="images" action="#{artwork.backToArt}"/>
</div>
<div>
<h:commandButton value="Form" action="#{artwork.backToForm}"/>
</div>
<div>
<h:commandButton value="Upload" action="#{artwork.backToUpload}"/>
</div>
</h:form>
It seems that IE caches the annotated images and keeps those images on display regardless of my method calls.
Here are my methods:
public String backToArt()
{
log.info("========= Setting back to art page ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "loginSuccess.xhtml";
}
public String backToUpload()
{ log.info("========= Setting back to upload ==========");
this.backToForm();
this.selectedValue = "";
this.resizedArt = "";
this.backArt = "";
return "CSVSubmit.xhtml";
}
public String backToForm()
{
log.info("============ Reseting all variables ==========");
String temp = null;
if (this.selectedValue != null)
{
temp = this.selectedValue;
temp=temp.substring(temp.lastIndexOf(Dir.getDir("\\")) + 1, temp.length() - 4);
this.selectedValue = temp;
}
log.info("Setting input variables");
//set all previous values to blank
//this.jobNum = "";
this.quantity = null;
this.headLine = null;
this.codeNum = null;
this.pass = null;
this.expir = null;
this.website = null;
log.info("Setting front art to old image");
//setting previous images to non-text
if (temp.length() > 0)
{
temp = this.resizedArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.resizedArt=temp;
log.info("Setting back art to old image");
temp = this.backArt;
temp = "converted" + temp.substring(temp.lastIndexOf(Dir.getDir("\\")),temp.length() - 8)
+ ".jpg";
this.backArt = temp;
log.info("Deleting old text images");
//start to delete text images
File folderOne = new File(Env.textDestOne);
this.deleteFiles(folderOne);
File folderTwo = new File(Env.textDestTwo);
this.deleteFiles(folderTwo);
}
log.info("============ Reset Complete ==========");
return "FormSubmission.xhtml";
}
These methods reset the input variables and the images selected as well as deletes my annotated images depending on which button is pressed on that page. Looking at my logging, the methods are called and are processed, but no updating occurs for the images. When I process my pdf, the correct images and input are outputed, but what is viewed still shows old values. This means that my values are being stored properly and my methods are being called correctly. When I go to cancel and reprocess using Google Chrome, the images are updated properly.
Using all of this information, I have concluded that IE must be caching my images and not updating them with the correct values. I'm not sure how to override this, but I need to somehow clear the cache so that the images are updated to the correct values.
Edit: I noticed that when I refresh the page hitting F5, the pictures would update. Not sure what this means.

Encoding problems in Android Application (WebView.LoadData())

I'm having a problem encoding a part of a webpage in my Android-application. What I've got is a application collecting part of a webpage and displaying this to a user. For this question lets say that I've got a webpage with a text and below the text a table and below the table a lot of junk I'm not interested in. So I'm chosing what to view using the position of the first element (for example a unique tag) and a end position (same there, something unique. Using a inputstreamreader with a start/end position.
Then in my string ("string") I run:
String s = Uri.encode(string);
The string s is then used accordingly:
web.loadData(s, "text/html","ISO-8859-1");
But this gives me some unwanted chars in the middle of the text: "Â" appears. I've tried to in the string run .replace("Â", ""); but this doesn't solve the problem.
I've also tried following:
web.loadData(s, "text/html", "UTF-8");
web.loadData(s,"text/html;utf-8",null);
But the "Â" and one or two "*" still appears?
Been searching the web and found the: loadDataWithBaseUrlbut this doesn't solve it either so I would very much like som assistence :)
On the top of the page:
<html xmlns="http://www.w3.org/1999/xhtml" lang="sv-se" dir="ltr">
On another page:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-us" dir="ltr">
So I've got one english and one swedish page but the error is regarding both url:s.
Best regards!
use this:
webview.loadData(html_content, "text/html; charset=utf-8", "utf-8");
I tested it, and it works.
This code worked for me.
String base64EncodedString = null;
try {
base64EncodedString = android.util.Base64.encodeToString((preString+mailContent.getBody()+postString).getBytes("UTF-8"), android.util.Base64.DEFAULT);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(base64EncodedString != null)
{
wvMailContent.loadData(base64EncodedString, "text/html; charset=utf-8", "base64");
}
else
{
wvMailContent.loadData(preString+mailContent.getBody()+postString, "text/html; charset=utf-8", "utf-8");
}

h:commandLink not firing file download action without f:ajax

I have an h:datatable that contains a column with a link that will call the backing bean and "should" return a PDF document generated.
The column looks like this :
<h:form>
...
<h:datatable>
...
<h:column >
<h:commandLink action="#{bean.downloadPDF}" target="_blank" >
<f:param name="value1" value="#{bean.val1}"/>
<f:param name="value2" value="#{bean.val2}"/>
<f:param name="value3" value="#{bean.val3}"/>
<h:graphicImage name="certificate.jpg" library="images"/>
</h:commandLink>
</h:column>
...
</h:datatable>
...
</h:form>
I have no javascript errors on my page (according to chrome and firebug). The backing bean looks like this :
public void downloadPDF() {
...
File outputPDF = new File(outputFileName);
//Get ready to return pdf to user
BufferedInputStream input = null;
BufferedOutputStream output = null;
try {
// Open file.
input = new BufferedInputStream(new FileInputStream(outputPDF), 10240);
//Return PDF to user
// Init servlet response.
response.reset();
response.setHeader("Content-Type", "application/pdf");
response.setHeader("Content-Length", String.valueOf(outputPDF.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + pdfName + "\"");
output = new BufferedOutputStream(response.getOutputStream(), 10240);
// Write file contents to response.
byte[] buffer = new byte[10240];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
// Finalize task.
output.flush();
} catch(IOException e) {
e.printStackTrace();
} finally {
output.close();
input.close();
}
facesContext.responseComplete();
}
Now, I know my PDF generation works because I can create the custom PDF and save it on the drive.
Then, if I add <f:ajax/> to the h:commandLink The method is called. Without that, it reloads the current page without the action method ever being called.
I have tried a few different things... with or without any f:params. Adding a String return value to the downloadPDF() function. EDIT : Taking away the target="_blank" parameter. Using actionListener instead of action. When using action, the bean method does not get called, but I get this error message in the h:messages : Conversion Error setting value '' for 'null Converter'..
Cannot get it to call the function. What I am hoping to get is that when one clicks on the downloadPDF link, it opens a new window and downloads the PDF.
Any help would be greatly appreciated.
EDIT 2 / Solution (temporary)
I have managed to get this working using the attribute immediate="true". Still havn't found exact field that is giving me the Conversion Error, but am assuming is a field in the form that does not need to be submitted for this specific function.
Logic associated with the question was good. The issue was with other items within the form that were staying null. As with the Edit 2, adding the immediate="true" made it so that the fields I needed alone were sent to the servlet.
Lesson learned
When submitting part of a form in JSF, make sure only the fields you need are being submitted. Especially in large forms and integrating ajax with sub sections of the form.

Java - Android - Installed packages' icons not showing in listview

I'm trying to load installed packages' icons into a listview, but they are not showing in anyway, searched and used everything I found on the web but they just won't show, while they work if I use
R.drawable.ic_launcher
So I guess it's not a layout-related issue.
Here's the code I'm using
for(int i = 0; i < numeroElementi; i++){
boolean nonSystem = (packages.get(i).flags & ApplicationInfo.FLAG_SYSTEM) == 0;
if(nonSystem == true){
HashMap<String,Object> app = new HashMap<String,Object>();
app.put("appName", packages.get(i).loadLabel(pm)); // these both work
app.put("appPackageName", packages.get(i).packageName);
try {
//app.put("appIcon", pm.getApplicationIcon(packages.get(i).packageName));
//app.put("appIcon", packages.get(i).icon + "");
//app.put("appIcon", packages.get(i).loadIcon(pm));
app.put("appIcon",packages.get(i).icon);
//app.put("appIcon", R.drawable.ic_launcher); <- this works
} catch (NameNotFoundException e) {
app.put("appIcon", R.drawable.ic_launcher);
}
installedList.add(app);
}
}
Is then there another way to grab the icon? As said earlier, if I force the ic_launcher icon, then it works... testing with packages.get(i).icon I found out that some of the voices have got the ic_launcher icon shown, so I thought that method just directed to that specific icon... anyone can help me get this work, please?

Categories

Resources