Problems downloading JPEG from the Internet
I am using the following class to download an image. The URL I am sending is correct but url.getContext() returns null every time. Does anybody know why?
package com.WasserSportLotse;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.drawable.Drawable;
class ImageDownloader {
private Drawable d;
public ImageDownloader(Context ctx, String url, String saveFilename) {
try {
InputStream is = (InputStream) this.fetch(url);
d = Drawable.createFromStream(is, "src");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrac开发者_如何学Ce();
}
}
public Drawable getImage(){
return d;
}
public Object fetch(String address) throws MalformedURLException,IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
}
calling url.getContent()
will return an image if applicable and only a stream of it's not an image or an audio clip. Though that doesn't seem to be your problem now, it will be a problem once you figure this one out.
Your code looks right. The only thing I can think of is the address isn't built right. It may work in a browser, but the URL class may be more picky than your browser. Make sure you're using the full form URL, with prepending http:// (not just www)
I changed the class quite a bit and found a much simpler version
private String path = "http://www.*YOURPATH.COM/SOMETHING*";
private String file;
private String url;
public ImageDownloader(String file){
this.file = URLEncoder.encode(file);
url = path + this.file;
}
public Drawable getImage() throws IOException, MalformedURLException {
return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), "name");
}
精彩评论