DarylDixon

Image download with progress dialog

Mar 27th, 2015
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. public class MyAsync extends AsyncTask<String, Integer, Bitmap> {
  2.  
  3. @Override
  4. protected void onPreExecute() {
  5. super.onPreExecute();
  6. dialog = new ProgressDialog(MainActivity.this);
  7. dialog.setTitle("Downloading...");
  8. dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
  9. dialog.show();
  10. dialog.setMax(100);
  11. }
  12.  
  13. @Override
  14. protected void onPostExecute(Bitmap bitmap) {
  15. imageView.setImageBitmap(bitmap);
  16. dialog.dismiss();
  17. super.onPostExecute(bitmap);
  18. }
  19.  
  20. @Override
  21. protected void onProgressUpdate(Integer... values) {
  22. super.onProgressUpdate(values);
  23. dialog.setProgress(values[0]);
  24. }
  25.  
  26. @Override
  27. protected Bitmap doInBackground(String... params) {
  28. try {
  29. URL url = new URL(params[0]);
  30. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  31. connection.setDoInput(true);
  32. connection.connect();
  33. InputStream input = connection.getInputStream();
  34. int total = connection.getContentLength();
  35. int downloaded = 0;
  36. int bytesCount;
  37. byte[] imageData = new byte[10000];
  38. File file = new File(getFilesDir().getPath() + "tempFile");
  39. if (!file.exists()) {
  40. file.createNewFile();
  41. }
  42. FileOutputStream cacheFile = new FileOutputStream(file);
  43. while ((bytesCount = input.read(imageData)) > 0) {
  44. downloaded += bytesCount;
  45. publishProgress((downloaded * 100) / total);
  46. cacheFile.write(imageData, 0, bytesCount);
  47. }
  48. cacheFile.close();
  49. Bitmap myBitmap = BitmapFactory.decodeFile(getFilesDir().getPath() + "tempFile");
  50. file.delete();
  51. return myBitmap;
  52. } catch (IOException e) {
  53. return null;
  54. }
  55. }
  56. }
Add Comment
Please, Sign In to add comment