1

I found this snippet on the internet:

try{
        URL url = new URL(imgUrl+imageId[position]+".png");
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        InputStream is = con.getInputStream();
        Bitmap bmp = BitmapFactory.decodeStream(is);
        imageView.setImageBitmap(bmp);
    }catch(Exception e) {
        System.out.println(e.getMessage());
    }

The code doesn't give me any errors,I am getting the exact url I want. But the ImageView stays empty. Running the debugger I got no problem upto: InputStream is = con.getInputStream(); After this the debugger goes to the catch block, and debugger window shows

NetworkOnMainThreadException

I know it's because I am doing network operations on the UI thread , but my activity already is extending another class, so I can't extend AsycnTask. Any workaround for this?

Plus: If there is an exception, shouldn't the app crash? My app runs fine, but the imageview doesn't show anything.

Aman Grover
  • 1,621
  • 1
  • 21
  • 41

2 Answers2

1

Newer versions of Android requires you to make HTTP requests (networking) on a separate thread. You can create a separate Thread, or use AsyncTask for this. The same code should work after you do this.

tcak
  • 2,142
  • 1
  • 16
  • 23
1

You can use Picasso that will help you also in async thread:

Picasso.with(context).load(imgUrl+imageId[position]+".png").into(imageView);

You can download the source here: http://square.github.io/picasso/ or add it as dependency directly from Android Studio

Giorgio Antonioli
  • 15,771
  • 10
  • 45
  • 70