Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Drawable Images from URL

I am presently using the following piece of code to load in images as drawable objects form a URL.

Drawable drawable_from_url(String url, String src_name)  throws java.net.MalformedURLException, java.io.IOException {         return Drawable.createFromStream(((java.io.InputStream)new java.net.URL(url).getContent()), src_name);  } 

This code works exactly as wanted, but there appears to be compatibility problems with it. In version 1.5, it throws a FileNotFoundException when I give it a URL. In 2.2, given the exact same URL, it works fine. The following URL is a sample input I am giving this function.

http://bks6.books.google.com/books?id=aH7BPTrwNXUC&printsec=frontcover&img=1&zoom=5&edge=curl&sig=ACfU3U2aQRnAX2o2ny2xFC1GmVn22almpg 

How would I load in images in a way that is compatible across the board from a URL?

like image 645
Señor Reginold Francis Avatar asked Jul 30 '10 20:07

Señor Reginold Francis


2 Answers

Bitmap is not a Drawable. If you really need a Drawable do this:

public static Drawable drawableFromUrl(String url) throws IOException {     Bitmap x;      HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();     connection.connect();     InputStream input = connection.getInputStream();      x = BitmapFactory.decodeStream(input);     return new BitmapDrawable(Resources.getSystem(), x); } 

(I used the tip found in https://stackoverflow.com/a/2416360/450148)

like image 106
Felipe Avatar answered Sep 19 '22 15:09

Felipe


Solved it myself. I loaded it in as a bitmap using the following code.

Bitmap drawable_from_url(String url) throws java.net.MalformedURLException, java.io.IOException {      HttpURLConnection connection = (HttpURLConnection)new URL(url) .openConnection();     connection.setRequestProperty("User-agent","Mozilla/4.0");      connection.connect();     InputStream input = connection.getInputStream();      return BitmapFactory.decodeStream(input); } 

It was also important to add in the user agent, as googlebooks denies access if it is absent

like image 28
Señor Reginold Francis Avatar answered Sep 17 '22 15:09

Señor Reginold Francis