Loading an image that isn’t defined in your resource folder in android can be really tricky. The image has to be downloaded asynchronously, cached in the phone in case we want to reuse later and then display it in the ImageView. Luckily there are many libraries that do just that and better. I am going to be using the ImageLoader lib.
- Download the ImageLoader lib here. (Google ‘android ImageLoader’ if link fails)
- Place the jar file in the libs folder in your project.
- This piece of code should do the trick:
String image_url = "https://mycodeandlife.files.wordpress.com/2013/01/384088_2317070728022_2086719259_n.jpg"; ImageView image = (ImageView) findViewById(R.id.imageView1); // Get singletone instance of ImageLoader ImageLoader imageLoader = ImageLoader.getInstance(); // Initialize ImageLoader with configuration. Do it once. imageLoader.init(ImageLoaderConfiguration.createDefault(this)); // Load and display image asynchronously DisplayImageOptions options = new DisplayImageOptions.Builder() .showStubImage(R.drawable.ic_launcher) //this is the image that will be displayed if download fails .cacheInMemory() .cacheOnDisc() .build(); imageLoader.displayImage(image_url, image, options);
The last bit is to add permissions to the Android Manifest. Add the following permissions: android.permission.WRITE_EXTERNAL_STORAGE and android.permission.INTERNET.
That’s it. Of course there still a lot more. You can use this in a list view and even show progress. You can read more here