santafebound santafebound - 2 months ago 18
Java Question

Clear Picasso image cache on refresh after loading data from web service

On refresh with SwipeRefreshLayout, I have the following code executed. This should load the new profile picture but it appears the old image is cached somehow on the device. When I exit the app and return to the activity, the new profile picture is available. But refreshing won't solve this. What can I do here?

Swipe:

private void setSwipeRefreshLayout(boolean isOnline, String userId) {
mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
mSwipeRefreshLayout.setOnRefreshListener(() -> {
if (!isOnline) {
mSwipeRefreshLayout.setRefreshing(false);
} else {
if (mSwipeRefreshLayout.isRefreshing()) {
mSwipeRefreshLayout.setRefreshing(false);
}

if (userId != null && userId.equals(ParseUser.getCurrentUser().getObjectId())) {
createProfileHeader(userId);
Picasso.with(getApplicationContext()).invalidate(imagePath);
}

}
});
}


Retrieve profile picture from Parse:

if (headerUserObject.getParseFile("profilePicture") != null) {

Picasso.with(getApplicationContext())
.load(headerUserObject.getParseFile("profilePicture").getUrl())
.placeholder(R.color.placeholderblue)
.into(((ImageView) findViewById(R.id.profile_picture)));

fadeInProfilePicture();
}


I'm not sure how I'd get
imagePath
above, since I'm downloading the image from the internet. But maybe this is not what I'm supposed to do?

Answer

Here is my code which will first load the image from the cache if the cache for that file exists, then update the cache file. If it doesn't exist, then load it from the internet(url).

Picasso.with(getApplicationContext()).load(headerUserObject.getParseFile("profilePicture").getUrl())
            .placeholder(R.color.placeholderblue).networkPolicy(Network.OFFLINE) // try to load the image from cache first
            .into(((ImageView) findViewById(R.id.profile_picture)), new Callback() {
                        @Override
                        public void onSuccess() {
                            //cache file for this url exists, now update the cache for this url
                            if(networkAvaialable()) // if internet is working update the cache file
                                Picasso.with(getApplicationContext()).invalidate(headerUserObject.getParseFile("profilePicture").getUrl());
                        }

                        @Override
                        public void onError() { // if cache file does not exist load it from the internet
                            Picasso.with(getApplicationContext()).load(headerUserObject.getParseFile("profilePicture").getUrl())
                            .placeholder(R.color.placeholderblue)
                            .into(((ImageView) findViewById(R.id.profile_picture)));
                        }
                    });