1

I need to load a image by URL, set in the ImageView and save the file in the SD Card.

This class do that, but very slowly.... The jpg files have 60kb, and the time to download its 3~6 seconds in my 10Mbps internet connection...

I'm using this to load any images in a listview...

public class DownloadImageTask extends AsyncTask {

ImageView bmImage;
String path;
String filename = "pg0.rsc";
String param;
Context context;

public DownloadImageTask(Context context, ImageView bmImage, String param, String code) {
    this.bmImage = bmImage;
    this.param = param;
    this.path = Environment.getExternalStorageDirectory().toString() + "/.RascunhoCache/." + code + "/";
    this.context = context;
}

protected Bitmap doInBackground(String... urls) {
    String urldisplay = urls[0];
    Bitmap mIcon11 = null;
    try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
    } catch (Exception e) {
        Log.e("Error", e.getMessage());
        e.printStackTrace();
    }
    return mIcon11;
}

protected void onPostExecute(Bitmap result) {       
    bmImage.setImageBitmap(result);
    if(param.equals("c")){
        OutputStream outStream = null;
        new File(path).mkdirs();
        File file = new File(path, filename);
        try {
         outStream = new FileOutputStream(file);
         result.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
         outStream.flush();
         outStream.close();
        }
        catch(Exception e){}
    }
}

}

Felipe Porge Xavier
  • 2,236
  • 6
  • 19
  • 27

1 Answers1

1

Don't decode your data directly. First store it on disk.

Suppose that jpeg decoding needs to go forward and backward in the stream to decode an image. Do you imagine how slow that would be (even impossible in some cases) ?

Use IOUtils from apache to assist you with streams and files.

Have a look at your post execute method. This will be executed on the main thread, freezing the UI while your code will be executed. We use AsyncTask to manipulate bitmaps, but we do it to lighten the UI Thread, so do any encoding/decoding/lengthy operation inside doInBackground.

And also, do stuff in your catch clause, it's a very bad practice to leave them empty : your app has no chance to know something went wrong. It needs to recover, or at least tell your user, or log something.

And finally, you should have a look at this thread, there are better approaches than asynctask for networking and some pretty good libraries can help a lot.

Community
  • 1
  • 1
Snicolas
  • 37,840
  • 15
  • 114
  • 173