Raheel Sadiq
Raheel Sadiq

Reputation: 9867

caching images in android

I want to cache some images when downloaded and when again my application starts, it should check if the images are cached so it returns images otherwise null , so I download and cache them again

I tried using LRU Cache http://developer.android.com/reference/android/util/LruCache.html but it didn't work for me , coz its for API level 12, and I am working on 10. here is that question caching images with LruCache

What are the other easy adoptable possible solutions to cache

Upvotes: 1

Views: 251

Answers (2)

Raheel Sadiq
Raheel Sadiq

Reputation: 9867

okay I did like this

        private Bitmap getFile(String fileName) {
        Bitmap file = null;
         try {
              FileInputStream fis; 
              fis = openFileInput(fileName);
              file = BitmapFactory.decodeStream(fis);

              fis.close();
         }
         catch (FileNotFoundException e) {
          e.printStackTrace();
         } catch (IOException e) {
          e.printStackTrace();
         }
        return file;
    }
    protected void putFile(Bitmap bitmap, String fileName){
        FileOutputStream fos;
           try {
            fos = openFileOutput(fileName, Context.MODE_PRIVATE);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.close();
           }    
           catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
               } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
               }
    }
    @Override
    protected String doInBackground(Void... params) {

        for (int i = 0; i < HomeActivity.globalObj.categoriesList.size(); i++) {
            Bitmap b;
            b = getFile(HomeActivity.globalObj.categoriesList.get(i).name);
            if (b == null) {
                b = getImageBitmap(HomeActivity.globalObj.categoriesList.get(i).large_image);
                putFile(b, HomeActivity.globalObj.categoriesList.get(i).name);

            }
            ImageView iv = new ImageView(getApplicationContext());
            iv.setImageBitmap(b);
            imageViewList.add(iv);
        }

Upvotes: 1

Anders Metnik
Anders Metnik

Reputation: 6247

Check out this for storing your files: Storage options android sdk

Upvotes: 1

Related Questions