Search code examples
androidandroid-fragmentsandroid-actionbarreloadnetworkimageview

How to reload NetworkImageView


I have an app which is displaying fragment with one NetworkImageView widget from android Volley.

The image at URL which is loaded in NetworkImageView is changing every 5 secounds so I want to uptade this image by pressing reload button that I have created in action bar.

I have found 2 problems:

  1. If I call this code for loading Image again(it was already called when the fragment was created at onActivityCreated() method):

    mNetworkImageView = (NetworkImageView) getView().findViewById(R.id.networkImageView);
    mImageLoader = VolleySingleton.getInstance(getActivity()).getImageLoader();
    mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);
    

so nothing will happens(it is not the actual IMG of that link), I think its because it is now loading IMG from cache and not from internet.

  1. If I call fragment reload() method:

    public void reload(){
    
    MainActivity activity = (MainActivity) getActivity();
    IMAGE_URL = activity.getMyData();
    
    mNetworkImageView = (NetworkImageView) getView().findViewById(R.id.networkImageView);
    
    mImageLoader = VolleySingleton.getInstance(getActivity()).getImageLoader();
    
    mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);
    

from MainActivity:

public boolean onOptionsItemSelected(MenuItem item) {        
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        return true;
    }

    if (id == R.id.action_reload) {
        ViewFragment fragment = new ViewFragment();
        fragment.reload();
    }

    return super.onOptionsItemSelected(item);
}

app get NullPointerException error after clicking action bar reload button.

the reload(); method is the place where I would like to reload NetworkImageView.

Can someone explain me pls how to correct this issues?


Solution

  • First get the cache from request queue.

    Then remove your URL from the cache by calling remove function from the cache ( the key is your url).

    then use your first approach:

    mNetworkImageView = (NetworkImageView) getView().findViewById(R.id.networkImageView);
    mImageLoader = VolleySingleton.getInstance(getActivity()).getImageLoader();
    mNetworkImageView.setImageUrl(IMAGE_URL, mImageLoader);