Android - Load Images from URL


In this Android tutorial you will learn to load images from URL. To connect android application with server we need to create a background thread. 

To load image from server we are going to implement our own background task using AsynchTask. Then we will get the image as a bitmap. After that we will load that image on our ImageView.

Create a subclass of AsynchTask

To allow network operation in different thread we are using AsynchTask. Follow the instructions given below  to implement your custom AsynchTask.

public class LoadImage extends AsyncTask<String, Void, Bitmap>{
}
  1. Include the source of image file by providing URI of the resource.
    String src = "http://www.example.com/kb4dev-remoteimage.jpg";			
  2. Create a URL object which represents an absolute url.
    URL url = new URL(src);
  3. HttpURLConnection helps to send and receive data over the web.
    url.openConnection() returns a new connection to the resource at url.
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();    
    
  4. Open the connection to resource using connect().
     connection.connect();
  5. Convert data into bitmap. We need to fetch the inputstream first. Then we decode it to Bitmap object.
    InputStream input = connection.getInputStream();
    Bitmap myBitmap = BitmapFactory.decodeStream(input);
  6. Get the reference of ImageView in order to diplay image on it.
    ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
  7. Set bitmap as a resource on ImageView.
    ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);

 

Full implementation of AsynchTask

Below code snippet can be used to get image from server. Make sure you edit the URL according to location of your image file.

public class LoadImage extends AsyncTask<String, Void, Bitmap>{
		
		@Override
		protected Bitmap doInBackground(String... params) {
			// TODO Auto-generated method stub
			String src = "http://www.example.com/kb4dev-remoteimage.jpg";
			try {
				URL url = new URL(src);
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		        connection.setDoInput(true);
		        connection.connect();
		        InputStream input = connection.getInputStream();
		        Bitmap myBitmap = BitmapFactory.decodeStream(input);
		        return myBitmap;
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
                        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
                        imageView.setImageBitmap(bitmapList);
		}
		
		
		
	}

Output: