DownloadImage.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package com.ivalentin.margolariak;
  2. import android.os.AsyncTask;
  3. import android.util.Log;
  4. import android.view.View;
  5. import android.widget.ImageView;
  6. import java.io.BufferedInputStream;
  7. import java.io.File;
  8. import java.io.FileOutputStream;
  9. import java.io.InputStream;
  10. import java.io.OutputStream;
  11. import java.net.URL;
  12. import java.net.URLConnection;
  13. /**
  14. * Async task to download images on the fly.
  15. * The remote image file, the local path, and the ImageView where the image will be loaded are set on the constructor.
  16. *
  17. * @author Iñigo Valentin
  18. *
  19. */
  20. class DownloadImage extends AsyncTask<Void, Void, Void> {
  21. private final String file;
  22. private final String path;
  23. private final ImageView iv;
  24. private final int size;
  25. /**
  26. * Constructor.
  27. *
  28. * @param file URL of the remote file.
  29. * @param path Path, including file name, where the image will be saved.
  30. * @param iv ImageView that will hold the image.
  31. * @param size Max size (width or height of the image)
  32. *
  33. * @see android.widget.ImageView
  34. */
  35. public DownloadImage(String file, String path, ImageView iv, int size) {
  36. super();
  37. this.file = file;
  38. this.path = path;
  39. this.iv = iv;
  40. this.size = size;
  41. }
  42. /**
  43. * Downloading file in background thread.
  44. */
  45. @Override
  46. protected Void doInBackground(Void... v) {
  47. int count;
  48. try {
  49. URL url = new URL(file);
  50. URLConnection conection = url.openConnection();
  51. conection.connect();
  52. // input stream to read file - with 8k buffer
  53. InputStream input = new BufferedInputStream(url.openStream(), 8192);
  54. // Output stream to write file
  55. OutputStream output = new FileOutputStream(path);
  56. byte data[] = new byte[1024];
  57. while ((count = input.read(data)) != -1) {
  58. // writing data to file
  59. output.write(data, 0, count);
  60. }
  61. // flushing output
  62. output.flush();
  63. // closing streams
  64. output.close();
  65. input.close();
  66. } catch (Exception e) {
  67. Log.e("Error downloading: ", e.getMessage());
  68. }
  69. return null;
  70. }
  71. /**
  72. * After completing background task, set the image on the ImageView.
  73. */
  74. @Override
  75. protected void onPostExecute(Void v) {
  76. Log.d("File downloaded", path);
  77. try {
  78. File file = new File(path);
  79. iv.setImageBitmap(GM.decodeSampledBitmapFromFile(file.getAbsolutePath(), size));
  80. iv.setVisibility(View.VISIBLE);
  81. }
  82. catch(Exception ex){
  83. Log.e("Bitmap error", "Not loading image " + path + ": " + ex.toString());
  84. }
  85. }
  86. }