I have an application where i download images from a server and display them in a imageview. This works the majority of the time but not always. It seems the times it doesn’t work is when there are spaces in the url. The error i get is
java.lang.RuntimeException: java.io.FileNotFoundException:
I have tried a number of different ways to try and encode the url but have had no success upto now.
Here is the class I am using.
private URL url;
Bitmap bitmap;
public ImageDownloader() {
}//constructor
public Drawable getImage(String urlString) throws IOException{
Log.i("url", urlString);
url = new URL(urlString);
InputStream is = url.openStream();
Bitmap bitmap = BitmapFactory.decodeStream(new FlushedInputStream(is));
Drawable image = new BitmapDrawable(bitmap);
return image;
}//getImage
static class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
@Override
public long skip(long n) throws IOException {
long totalBytesSkipped = 0L;
while (totalBytesSkipped < n) {
long bytesSkipped = in.skip(n - totalBytesSkipped);
if (bytesSkipped == 0L) {
int bytee = read();
if (bytee < 0) {
break; // we reached EOF
} else {
bytesSkipped = 1; // we read one byte
}
}
totalBytesSkipped += bytesSkipped;
}
return totalBytesSkipped;
}
}
public Bitmap getBitmap(String urlString) {
try {
//String s = Uri.encode(urlString);
url = new URL(urlString);
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("User-agent", "Mozilla/4.0");
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream in = null;
try {
in = conn.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap = BitmapFactory.decodeStream(in);
}
Both the getImage and getBitmap have the same error.
Here is an example of a url i am using.
http://kaiorize-clone1.loomarea.com/sites/default/files/imagecache/app_product_full/sites/default/files/BsfL_Logo_final_sonderfarben 300dpi.jpg
This was a strange one. I tried to encode the normal way but I was still getting the same error. I check the URL that was being sent and the space had been changed for a “%20”. In the end through desperation I decided to just change the space into “%20” myself instead of encoding. This solved the problem. Not the most elegent of solutions but it worked!