I want to fill an ImageView with an image saved on my localhost. I can display it in a browser fine but it doesn't get displayed in my ImageView.
PHP script to display image:
<?php
include('connect_db.php');
$id = $_GET['id'];
$path = 'Profile_Images/'.$id.'.jpg';
echo '<img src='.$path.' border=0>';
?>
Here is my android code to download an image from a URL:
URL url;
try {
url = new URL("http://192.168.1.13/get_profile_image.php?id=145");
new DownloadImage(this).execute(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void imageDownloaded(final Bitmap downloadedImage) {
runOnUiThread(new Runnable() {
public void run() {
ImageView imageView = (ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(downloadedImage);
}
});
}
When I put the URL to some other image it works fine but mine never gets loaded, any ideas?
Also, the following code works but I have a feeling its bad practice..
URL url;
try {
url = new URL("http://192.168.1.13/Profile_Images/145.jpg");
new DownloadImage(this).execute(url);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Where 145 would be a variable.
Edit
Any reasons for the down-votes would be appreciated!
It's pretty simple, actually. When you send a request to http://192.168.1.13/get_profile_image.php?id=145 a string (<img src=Profile_Images/'.$id.'.jpg border=0>) is sent back. Because the DownloadImage class doesn't parse HTML (it wants raw image data) it doesn't know where the actual image is. Two solutions:
Your 'bad practice' approach
Use this PHP script instead to echo the raw image data:
PHP:
$id = $_GET['id'];
$path = 'Profile_Images/'.$id.'.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($path));
readfile($path);
EDIT: forgot to credit someone: the above code is taken from here (with adapted variable names): https://stackoverflow.com/a/1851856/1087848
Your PHP code will print out something along the lines of:
<img src=Profile_Images/145.jpg border=0>
Not only is this malformed HTML, but it is a text output. Your other URL, http://192.168.1.13/Profile_Images/145.jpg points to an image file, from which the data your receive is an image, not an HTML string.
You should consider having your PHP return a JSON response with the URL of the image ID, and then running DownloadImage on that URL. The advantage this has over a raw echo is that you can easily expand the solution to return other types of files, and even return an array of files.
Related
I've been trying to create a program in Java that can catch the odds of a game from a sportsbook like FanDuel but I've been running into a lot of problems. When I print the html for the site I dont get the entire html for the site so Im unable to go into the divs and retrieve the actual data I want.
I used the Url https://sportsbook.fanduel.com/ . If I try and run a method like Elements element = doc.getElementByID("root"); to get the data inside that div the rest of the data in that div will not appear. enter image description here. I specifically would just like to get the moneyline data for each game if anyone can help that would be great
public class ExtractSportsBookData {
public static void extractData(String url){
try{
Document doc = Jsoup.connect(url).get();
String html = doc.html();
System.out.println(html);
} catch (IOException e){
e.printStackTrace();
}
}
}
enter image description here
If you look at the image inside the li tags is where the data is stored for the moneylines for each game but I cannot seem to find a way to extract that data using Jsoup
public class Main {
public static void main(String[] args) {
ExtractSportsBookData.extractData("https://sportsbook.fanduel.com/");
}
}
import java.io.IOException;
import java.io.SyncFailedException;
public class ExtractSportsBookData {
public static void extractData(String url){
try{
Document doc = Jsoup.connect(url).get();
String html = doc.html();
//System.out.println(html);
Elements element = doc.getElementsByClass("jo jp fk fe jy jz bs");
System.out.println(element.isEmpty());
} catch (IOException e){
e.printStackTrace();
}
}
}
enter image description here
The result I receive from this is true meaning that the element is empty which is not what I want. Any help on this would be appreciated
I have a microprocessor that hosts a webServer and webpage over wifi and interacts with an Android app. The webpage has a submit button eg HTML
<form action="/RUNME" method="POST">
<input type="submit" value="Run Me">
</form>\
When the button is pressed on the opened webpage on the Android device it prompts the server to process its runMe method which executes on a microprocessor.
The microprocessors c code includes this line which when receiving a POST request executes the method runMe
server.on("/RUNME",HTTP_POST,runMe);
I need to achieve the same behaviour from within an android app equivalent to pressing the submit button or
running the runMe routine on the webserver.
The method has to receive the URL eg http://www.xxx.xxx.xx.xx and some argument "/RUNME" or "Run Me". I am unsure of the formatting of the arguments nor which method to use.
String websiteUrl = http://www.xxx.xxx.xx.xx;
URL url = new URL(websiteUrl);
HttpURLConnection connection = url.openConnection();
connection.setDoOutput(true);//Set output method to POST
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(websiteUrl + "/RUNME");
out.close();
Example code block part of my Asynchronous Task
#Override
protected Integer doInBackground(String[] arg0) {
try {
url = new URL(arg0[0]);
urlconn = (HttpURLConnection)url.openConnection();
urlconn.setAllowUserInteraction(false);
urlconn.setDoOutput(true);
urlconn.setIfModifiedSince(0);
urlconn.setUseCaches(true);
urlconn.setConnectTimeout(3000);
urlconn.setReadTimeout(3000);
urlconn.connect();
responseCode =urlconn.getResponseCode();
if(responseCode==HttpURLConnection.HTTP_OK){
//POST the HTTP request how to get the same behaviour as pressing the webpage submit buttom
//How do you do this what method should you use and what arguments that include the url, arg0[0] and /RUNME
urlconn.????
}
urlconn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return responseCode;
}
I'm making a small application in Java that requires me to scrape an image from a website and display it in a GUI. Now I'm not asking how to get the image's absolute URL, I'm asking how I can display it once I've gotten the absolute URL. I'm using the jsoup library as the web scraper.
I used the following piece of code to get the desired output shown in the image below (Use appropriate imports):
BufferedImage myPicture = null;
try {
URL url = new URL("https://www.w3schools.com/css/img_fjords.jpg");
URLConnection connection = url.openConnection();
connection.setRequestProperty("User-Agent", "MyAppName");
myPicture = ImageIO.read(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JLabel picLabel = new JLabel(new ImageIcon(myPicture));
frame.getContentPane().add(picLabel);
For setRequestProperty, use any string in place of MyAppName, it's just a value to the User-Agent attribute in the http request made by your app
Reference Image
I am parsing a JSON Obj to get the url of an image.
I am using this code.
private Drawable LoadImageFromWebOperations(String strPhotoUrl) {
try {
InputStream is = (InputStream) new URL(strPhotoUrl).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
Log.e("TAGG", strPhotoUrl);
return d;
} catch (Exception e) {
Log.e("TAGG", e.toString());
return null;
}
}
But I get an error that this must be done in an AsyncTask,i.e., Different Thread. But then how will I insert the drawable in an ImageView? Since DoInBackground() dosen't have access to UI elements. Also I don't have access to the URL until I parse the JSON obj I get the URL from. So what solution can I use in my situation. Thanks!
You can access the UI elements from onPostExecute().
So, you can make the API call and get the data in the background thread. After the image has been downloaded, you can set the image to the ImageView in the onPostExecute() method.
Problem description : user press print screen button and then click on paste button on application. That image will be store on server.
I googled and find answer on Stack over and used following code
public Image getImageFromClipboard()
{
Clipboard systemClipboard = (Clipboard) AccessController.doPrivileged(new PrivilegedAction() {
public Object run()
{
Clipboard tempClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
return tempClipboard;
}
});
// get the contents on the clipboard in a
// Transferable object
Transferable clipboardContents = systemClipboard.getContents(null);
// check if contents are empty, if so, return null
if (clipboardContents == null)
return null;
else
try
{
// make sure content on clipboard is
// falls under a format supported by the
// imageFlavor Flavor
if (clipboardContents.isDataFlavorSupported(DataFlavor.imageFlavor))
{
// convert the Transferable object
// to an Image object
Image image = (Image) clipboardContents.getTransferData(DataFlavor.imageFlavor);
return image;
}
} catch (UnsupportedFlavorException ufe)
{
ufe.printStackTrace();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
/*try {
Robot robot;
robot = new Robot();
final GraphicsConfiguration config
= GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice().getDefaultConfiguration();
final BufferedImage screenshot = robot.createScreenCapture(config.getBounds());
return screenshot;
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
return null;
}
This code work well if application is running on my machine and I press Print Screen. Image is available and store.
My problem is that when I am deploying this application on separate server and run application on another machine. When user press Print screen and then click on button in application. Server won't find any image because it look on clipboard and on server clipboard no image is available. Image is available on Client desktop clipboard.
Kindly help me to access Client clipboard from server using JSF/primefaces. Or other alternative way.
I am using primefaces 3.4, server is weblogic 10.3.5.
If your application will be running on different browsers, you will find no 100% reliable way of doing it unless you implement some specific component with some other technology like Flash.
I would really use the approach of saving the image and uploading it to the server via a normal file upload form. Else you will be having headaches with Browser security issues.
Regards