public class ImageDownloader extends AsyncTask<String, Void, Drawable> {
Context context;
ImageView image;
public ImageDownloader(ImageView image) {
this.image = image;
}
protected void onPreExecute() {
}
protected Drawable doInBackground(String... urls) {
InputStream is;
Drawable d = null ;
try {
is = (InputStream)new URL(urls[0]).getContent();
d = Drawable.createFromStream(is, "Image");
return d;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return d;
}
protected void onPostExecute(Drawable d) {
if(d != null){
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
image.setBackgroundDrawable(d);
}else{
image.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.noimage));
Toast.makeText(context, "No image", Toast.LENGTH_LONG).show();
}
}
}
because it's working in the beginning but when i download a lot of images it crash. I looked in my LogCat and this is because there is no more allocation for it. I want to do do an application like Pulse News, which display images but doesn't crash everytime. And i'm in ice cream sandwich, just in case.
You need to know about SoftReference class in java. Go ahead and search for it.You will get your answer
I found this class and it works fine, very fine !
To use it, it's simple :