I'm developing Image Loader using both cache.
and here is my logic.
1st, start get the images on the disk cache (when app starting)
2nd, check the memory cache. if it is, load from Cache memory.
3nd, If the image doesn't exist in memory cache, check the Disk cache. then put the image into the memorycache.
4th, If there isn't the image both memory cache and disk cache, make the bitmap from url using the asynctask. then put the Disk cache.
and This is my source.
1st, App's onCreate()
protected void onCreate(Bundle savedInstanceState) {
...
if (workerTask == null) {
workerTask = new BitmapWorkerTask();
workerTask.execute(imgUrls);
}
...
}
class BitmapWorkerTask extends AsyncTask, Void, Bitmap> {
@Override
protected Bitmap doInBackground(ArrayList<String>... params) {
ArrayList<String> imgUrls = params[0];
Bitmap bitmap = null;
for (int i = 0; i < imgUrls.size(); i++) {
String key = imgUrls.get(i);
if (MainActivity.getBitmapFromDiskCache(key) == null) {
URLConnection urlConnection = null;
try {
urlConnection = (HttpURLConnection) new URL(key).openConnection();
urlConnection.setDoInput(true);
urlConnection.connect();
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
InputStream input = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(input);
}catch (Exception e){
e.printStackTrace();
}
MainActivity.addBitmapToDiskCache(key, bitmap);
}
}
return bitmap;
}
2nd to 4th, getView
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
...
if (MainActivity.getBitmapFromMemCache(imgUrl) != null) {
bitmap = MainActivity.getBitmapFromMemCache(imgUrl);
Log.d("Service", "getBitmapFromMemCache");
} else {
if (MainActivity.getBitmapFromDiskCache(imgUrl) != null) {
bitmap = MainActivity.getBitmapFromDiskCache(imgUrl);
MainActivity.addBitmapToMemoryCache(imgUrl, bitmap);
} else {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(imgUrl);
BitmapWorkerTask task = new BitmapWorkerTask();
task.execute(arrayList);
}
}
...
}
and the problem is 'when there is no data in both cache.' I think If that source is right, when there is no data in cache, the image have to put in the disk cache after task.execute(arrayList). but It isn't...
so, i try to change task.execute(arrayList).get(), but It take too much time.
I don't know how to fix it... and What I am missing
could anyone help me??