Fetching image from url in Android

I am trying to Fetch image from Url, but i’m getting I/O exception. I really have no idea why.

 try {
        URL profilePicUrl =  new URL("http://houssup.netau.net/vivek_thumbnail.jpg");

        HttpURLConnection connection =(HttpURLConnection) profilePicUrl.openConnection();

        connection.setDoInput(true);


        connection.connect();

        InputStream inputStreamImage = connection.getInputStream();

        Bitmap profileImage = BitmapFactory.decodeStream(inputStreamImage);

        holder.profilePic.setImageBitmap(profileImage);


    } catch (MalformedURLException e) {
        Log.e("Profile Image","Error in URL");
         e.printStackTrace();
    } catch (IOException e) {
        Log.e("Profile Image","Error in IO");
        e.printStackTrace();
    }

Also i want to make point that, HttpURLconnection is throwing exception everywhere in my app. I mean in every class, I am not able to use this class.

Answer

I tried that code and the error is this:

Caused by: android.os.NetworkOnMainThreadException

so the solution is to include this on your code:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
StrictMode.setThreadPolicy(policy);

Leave a Reply

Your email address will not be published. Required fields are marked *