0

I want to show progressbar where image downloaded and set custom color I do it in onProgressUpdate() but it dosent work it also doesn't appear in logcat.. it also shows a white screen until download completed and if I press back button during the download, it will crash.

my code:

public class DownloadImage extends AsyncTask<String ,Void, Bitmap> {

    Bitmap bit;

    @Override
    protected Bitmap doInBackground(String... urls) {
        try {
            URL url = new URL(urls[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();
            return BitmapFactory.decodeStream(connection.getInputStream());
        } catch(Exception e){
            Log.i("error download", "doInBackground: "+e.getMessage());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        Log.i("download", "onPostExecute: ");
        imageView.setImageBitmap(bitmap);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        Log.i("download", "onProgressUpdate: ");
        imageView.setColorFilter(R.color.imagecolor);
    }
}

and onCreate() method:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main3);
    imageView = findViewById(R.id.imageView2);
    progressBar = findViewById(R.id.progressBar2);
    DownloadImage downloadImage = new DownloadImage();
    downloadImage.execute("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRaL6woz3RgMF-UXU682S_BYb1ayl5xaVancp0PPvF2HnCDmPsb");

    try {
        downloadImage.get();
    } catch (Exception e){

    }
}
Martin Zeitler
  • 1
  • 19
  • 155
  • 216
Noah Mohamed
  • 114
  • 1
  • 1
  • 8

1 Answers1

3

I want to show progressbar where image downloaded and set custom color I do it in onProgressUpdate() but it dosent work

You need to call publishProgress() from doInBackground(). That will trigger calls to onProgressUpdate(). You are not doing this, and so onProgressUpdate() will not be called.

it also shows a white screen until download completed

Remove your downloadImage.get(); call. That will block the main application thread, and the point of using AsyncTask (or its more modern replacements) is to not block the main application thread.

and if I press back button during the download, it will crash.

If the activity/fragment is destroyed, you should not update the UI. So, you need to confirm in onPostExecute() whether it is safe to update the UI (e.g., call isDestroyed() on the activity).

Beyond that, use Logcat to examine the stack trace associated with any crashes.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491