Luca D'Amico
Luca D'Amico

Reputation: 3212

Android - Can't load image from http

I need to load an image from http, and I'm using this code:

                        Bitmap bitmap;                        
                        InputStream is = null;
                        try {
                            is = (InputStream) new URL("www.TESTWEBSITE.com/TEST.JPG").getContent();
                        } catch (MalformedURLException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                        bitmap = BitmapFactory.decodeStream(is);

But bitmap is still null.. Any help please ?

Upvotes: 0

Views: 311

Answers (1)

kiruwka
kiruwka

Reputation: 9450

Update : this is full snapshot performing what you want :

        Bitmap bitmap = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL("www.TESTWEBSITE.com/TEST.JPG");
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream is = urlConnection.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

Please, make sure to run it off UI thread, such as in AsyncTask as others have commented. You can try it in main thread for experimental purposes but be prepared for ANR.

Upvotes: 1

Related Questions