0

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 ?

Luca D'Amico
  • 3,192
  • 2
  • 26
  • 38

1 Answers1

1

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.

kiruwka
  • 9,250
  • 4
  • 30
  • 41
  • @Luca What is the cause of the crash ? Moreover, this snapshot should be put on other thread as others pointed out, such as inside an AsyncTask. Let me know if you'd like to get more details on this. – kiruwka Oct 28 '13 at 19:59
  • @Luca Were you able to fetch Bitmap (non-null value) with the snapshot above ? If so, could I please ask you to accept the answer . Thnx – kiruwka Oct 28 '13 at 20:56
  • At the moment I'm not able, but I'm accepting your answer anyway. Because it looks like to be working. – Luca D'Amico Oct 28 '13 at 21:04
  • @Luca Thnx. Feel free to follow up with questions in case of problem. – kiruwka Oct 28 '13 at 21:05