0

Having a problem where it takes too long to load a profile picture from my web server. This is the code I'm using to load the image (in an AsyncTask):

@Override
        protected Bitmap doInBackground(Void... params) {
            String urlPath = AppVariables.SERVER_ADDRESS + "pictures/" + name + ".JPG";
            try {
                URLConnection connection = new URL(urlPath).openConnection();
                connection.setUseCaches(true);
                connection.setConnectTimeout(1000 * 30);
                connection.setReadTimeout(1000 * 30);
                return BitmapFactory.decodeStream((InputStream) connection.getContent(), null, null);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

This should work according to the top answer here: Android image caching

I still experience a delay though - when I go to 'Profile' in the app it takes a good 2-3 seconds for the profile picture to display.

Any ideas?

Community
  • 1
  • 1
eyes enberg
  • 556
  • 1
  • 8
  • 30

2 Answers2

0
//onCreate
try
    {
        File httpCacheDir = new File(getApplicationContext().getCacheDir(), "http");
        long httpCacheSize = 100 * 1024 * 1024; // 100 MiB
        HttpResponseCache.install(httpCacheDir, httpCacheSize);
    }
    catch (Exception e) {}

//onStop
try {
        HttpResponseCache cache = HttpResponseCache.getInstalled();
        if (cache != null) {
            cache.flush();
        }
    }
    catch(Exception e){}

Are you setting up your cache?

scubasteve623
  • 637
  • 4
  • 7
0

Just use Universal Image Loader ( https://github.com/nostra13/Android-Universal-Image-Loader ).

You can set to cache the image like this:

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisk(true)
            .build();

And then, you can get the URL to the cached image like this:

File file = DiscCacheUtil.findInCache(imageUrl, imageloader.getDiscCache());
Filnik
  • 352
  • 1
  • 12
  • 33