Android Universal image Downloader Utility


Universal Image downloader :

Some times Image will not download properly because of URL Connection and HTTPClient APIs in android application. we need to check the Connection type before downloading the image.

This utility method will help you to download regardless of Network client.


public void downloadImageFromServer(String url) {
  Log.d(TAG,"downloading image started... : "+url);
  String filename = "filepath";
  File downloadingMediaFile = null;
  InputStream stream = null;
  FileOutputStream out= null;
      try {
    URLConnection conn = new URL(url).openConnection();
     if (conn instanceof HttpURLConnection){
    try {
  HttpURLConnection httpConn = (HttpURLConnection) conn;
  httpConn.setAllowUserInteraction(false);
  httpConn.setInstanceFollowRedirects(true);
  httpConn.setRequestMethod("GET");
  httpConn.connect();
  response = httpConn.getResponseCode();
  if (response == HttpURLConnection.HTTP_OK) {
   stream  = httpConn.getInputStream();
  }
  } catch (Exception ex) {
   throw new IOException("Error connecting");
  }
       }else{
  conn.setDoInput(true);
  conn.setDoOutput(true);
  conn.connect();
  stream = conn.getInputStream();
 }
 if (stream == null) {
  Log.e(getClass().getName(), "Unable to create InputStream for image Url:" + url);
 }
downloadingMediaFile = new File(activity.getApplicationContext().getCacheDir(),filename);
   // Just in case a prior deletion failed because our code crashed or something, we also delete any previously
   // downloaded file to ensure we start fresh.  If you use this code, always delete
   // no longer used downloads else you'll quickly fill up your hard disk memory.  Of course, you can also
   // store any previously downloaded file in a separate data cache for instant replay if you wanted as well.
 if (downloadingMediaFile.exists()) {
  downloadingMediaFile.delete();
 }else{
  downloadingMediaFile.createNewFile();
 }
 out = new FileOutputStream(downloadingMediaFile);
 byte[] buf = new byte[16384];
 int totalBytesRead = 0;
 do {
  int numread = stream.read(buf);
  if (numread <= 0)
   break;
  out.write(buf, 0, numread);
  totalBytesRead += numread;
 } while (true);
Log.d(TAG,"totalBytesRead : "+totalBytesRead);
stream.close();
if(out != null){
 out.close();
}
Log.d(TAG,"Image downloaded, image file path is : "+downloadingMediaFile.getAbsolutePath());
} catch (Exception e) {
   e.printStackTrace();
   try{
    if(stream != null){
     stream.close();
    }
    if(out != null){
     out.close();
    }
   }catch(Exception e1){
   }
   }
 }