What is the simplest way to fetch an image from a url in an android program?
I would strongly recommend using an AsyncTask instead. I originally used URL.openStream, but it has issues.
class DownloadThread extends AsyncTask>{
protected List doInBackground(URL... urls){
InputStream rawIn=null;
BufferedInputStream bufIn=null;
HttpURLConnection conn=null;
try{
List out=new ArrayList();
for(int i=0;i
Closing the stream/connection and exception handling is difficult in this case. According to Sun Documentation you should only need to close the outermost stream, however it appears to be more complicated. However, I am closing the inner most stream first to ensure it is closed if we can't close the BufferedInputStream.
We close in a finally so that an exception doesn't prevent them being closed. We account for the possibility of the streams will being null if an exception prevented them from being initialised. If we have an exception during closing, we simply log and ignore this. Even this might not work properly if a runtime error occurs .
You can use the AsyncTask class as follows. Start an animation in onPreExecute. Update the progress in onProgressUpdate. onPostExecute should handle the actual images. Use onCancel to allow the user to cancel the operation. Start it with AsyncTask.execute.
It is worth noting that the source code and the license allow us to use the class in non-Android projects.