How do I use disk caching in Picasso?

前端 未结 9 779
-上瘾入骨i
-上瘾入骨i 2020-11-22 14:44

I am using Picasso to display image in my android app:

/**
* load image.This is within a activity so this context is activity
*/
public void loadImage (){
           


        
相关标签:
9条回答
  • 2020-11-22 15:38

    I use this code and worked, maybe useful for you:

    public static void makeImageRequest(final View parentView,final int id, final String imageUrl) {
    
        final int defaultImageResId = R.mipmap.user;
        final ImageView imageView = (ImageView) parentView.findViewById(id);
        Picasso.with(context)
                .load(imageUrl)
                .networkPolicy(NetworkPolicy.OFFLINE)
                .into(imageView, new Callback() {
                    @Override
                    public void onSuccess() {
                    Log.v("Picasso","fetch image success in first time.");
                    }
    
                    @Override
                    public void onError() {
                        //Try again online if cache failed
                        Log.v("Picasso","Could not fetch image in first time...");
                        Picasso.with(context).load(imageUrl).networkPolicy(NetworkPolicy.NO_CACHE)
                                .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).error(defaultImageResId)
                                .into(imageView, new Callback() {
    
                                    @Override
                                    public void onSuccess() {
                                        Log.v("Picasso","fetch image success in try again.");
                                    }
    
                                    @Override
                                    public void onError() {
                                      Log.v("Picasso","Could not fetch image again...");
                                    }
    
                                });
                    }
                });
    
    }
    
    0 讨论(0)
  • 2020-11-22 15:40

    I don't know how good that solution is but it is definitely THE EASY ONE i just used in my app and it is working fine

    you load the image like that

    public void loadImage (){
    Picasso picasso = Picasso.get(); 
    picasso.setIndicatorsEnabled(true);
    picasso.load(quiz.getImageUrl()).into(quizImage);
    }
    

    You can get the bimap like that

    Bitmap bitmap = Picasso.get().load(quiz.getImageUrl()).get();
    

    Now covert that Bitmap into a JPG file and store in the in the cache, below is complete code for getting the bimap and caching it

    Thread thread = new Thread() {
     public void run() {
     File file = new File(getCacheDir() + "/" +member.getMemberId() + ".jpg");
    
    try {
          Bitmap bitmap = Picasso.get().load(uri).get();
          FileOutputStream fOut = new FileOutputStream(file);                                        
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100,new FileOutputStream(file));
    fOut.flush();
    fOut.close();
        }
    catch (Exception e) {
      e.printStackTrace();
        }
       }
    };
         thread.start();
      })
    
    

    the get() method of Piccasso for some reason needed to be called on separate thread , i am saving that image also on that same thread.

    Once the image is saved you can get all the files like that

    List<File> files = new LinkedList<>(Arrays.asList(context.getExternalCacheDir().listFiles()));
    

    now you can find the file you are looking for like below

    for(File file : files){
                    if(file.getName().equals("fileyouarelookingfor" + ".jpg")){ // you need the name of the file, for example you are storing user image and the his image name is same as his id , you can call getId() on user to get the file name
                        Picasso.get() // if file found then load it
                                .load(file)
                                .into(mThumbnailImage);
                        return; // return 
                    }
            // fetch it over the internet here because the file is not found
           }
    
    0 讨论(0)
  • 2020-11-22 15:40

    Add followning code in Application.onCreate then use it normal

        Picasso picasso = new Picasso.Builder(context)
                .downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
                .build();
        picasso.setIndicatorsEnabled(true);
        picasso.setLoggingEnabled(true);
        Picasso.setSingletonInstance(picasso);
    

    If you cache images first then do something like this in ProductImageDownloader.doBackground

    final Callback callback = new Callback() {
                @Override
                public void onSuccess() {
                    downLatch.countDown();
                    updateProgress();
                }
    
                @Override
                public void onError() {
                    errorCount++;
                    downLatch.countDown();
                    updateProgress();
                }
            };
            Picasso.with(context).load(Constants.imagesUrl+productModel.getGalleryImage())
                    .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
            Picasso.with(context).load(Constants.imagesUrl+productModel.getLeftImage())
                    .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
            Picasso.with(context).load(Constants.imagesUrl+productModel.getRightImage())
                    .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
    
            try {
                downLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            if(errorCount == 0){
                products.remove(productModel);
                productModel.isDownloaded = true;
                productsDatasource.updateElseInsert(productModel);
            }else {
                //error occurred while downloading images for this product
                //ignore error for now
                // FIXME: 9/27/2017 handle error
                products.remove(productModel);
    
            }
            errorCount = 0;
            downLatch = new CountDownLatch(3);
    
            if(!products.isEmpty() /*&& testCount++ < 30*/){
                startDownloading(products.get(0));
            }else {
                //all products with images are downloaded
                publishProgress(100);
            }
    

    and load your images like normal or with disk caching

        Picasso.with(this).load(Constants.imagesUrl+batterProduct.getGalleryImage())
            .networkPolicy(NetworkPolicy.OFFLINE)
            .placeholder(R.drawable.GalleryDefaultImage)
            .error(R.drawable.GalleryDefaultImage)
            .into(viewGallery);
    

    Note:

    Red color indicates that image is fetched from network.

    Green color indicates that image is fetched from cache memory.

    Blue color indicates that image is fetched from disk memory.

    Before releasing the app delete or set it false picasso.setLoggingEnabled(true);, picasso.setIndicatorsEnabled(true); if not required. Thankx

    0 讨论(0)
提交回复
热议问题