Thursday, December 8, 2011

AsyncTask to Show Image with loading

Following code will show a progress bar(ajax-loading) instead of the image I want to show.
docImage.setVisibility(View.GONE);
pBar.setVisibility(View.VISIBLE);
new DownloadFilesTask().execute(new URL("http://..."));

Once the download is complete the target image will be shown and the progress bar will be gone. To make this code work we need to put both target-image and progress-bar in the same layout position.
private class DownloadFilesTask extends AsyncTask {

Drawable d;

public Object fetch(URL url) throws MalformedURLException,IOException {
Object content = url.getContent();
return content;
}

protected Long doInBackground(URL... urls) {
long totalSize = 0;
URL url = urls[0];
try {
InputStream is = (InputStream) this.fetch(url);
d = Drawable.createFromStream(is, "src");
} catch (Exception e) {
e.printStackTrace();
return 0L;
}
return totalSize;
}

protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}

protected void onPostExecute(Long result) {
docImage.setImageDrawable(d);
pBar.setVisibility(View.GONE);
docImage.setVisibility(View.VISIBLE);
}
}

No comments: