Search code examples
androidandroid-imageviewpicasso

Updating ImageView based on URL


I have spent a lot of time trolling through multiple different threads concerning this topic, but I have yet to find an answer that works well with my code (Android SDK 23, in 2016). A lot of the answers are deprecated, and others just flat-out don't work like they're supposed to, and I was wondering if I could get a solid answer on this:

I am trying to include a Pokemon sprite (static image) in my program from Serebii. nums is a variable indicating the Pokemon's dex number (this one functions correctly, I promise). And this code is running in the main UI thread, which I know is frowned upon, but right now I'm trying to get the image loading, and then the smoothness of the app down. I don't really need a Bitmap, per se, but I need my ImageView to update and display the image given by the URL. How do I do it?

URL url = null;
try {
     url = new URL("http://www.serebii.net/xy/pokemon/" + nums + ".png");
} catch (MalformedURLException e) {
  e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
mImageView.setImageBitmap(bmp);

Solution

  • Just use Picasso library, it will do all your image loading. You only need to provide the url of the image correctly.

    String url = "http://www.serebii.net/xy/pokemon/" + nums + ".png";
    
    Picasso.with(yourContext)
        .load(url)
        .into(mImageView);