Search code examples
androidandroid-fragmentsandroid-viewpagerfragmentpageradapterpicasso

ViewPager unable to load images lazily with Picasso


I have a FragmentActivity in the first tab of a TabHost, and the FragmentActivity itself holds a ViewPager.

The ViewPager's setAdapter() method sets a FragmentPagerAdapter with a set of Fragments. The goal is to have swipeable images in the first pane of the TabHost.

To test it, I was loading a bunch of images that I had kept locally in the project's drawable directory. Everything worked beautifully.

After having tested this initial setup, I'm downloading a bunch of image URLs' off a REST web service. I want these images to load lazily in the ViewPager, and I tried calling Picasso's load() method in three places:

  1. The onCreateView() method of the ViewPager's Fragments (the same place where I was earlier loading images from the local drawable directory).

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
        Bundle savedInstanceState) {                
    
        View myFragmentView = inflater.inflate(R.layout.layout_fragment, container, false);
    
        ImageView imageView = (ImageView)getView().findViewById(R.id.fragment_image);
        String url = getArguments().getString(IMAGE_RESOURCE_URL);
        Context context = getActivity();
        Picasso.with(context).load(url).fit().into(imageView);
    
        return myFragmentView;
    }
    
  2. The onViewCreated() method of the ViewPager's Fragments.

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState){
    
        Context context = getActivity();
        String url = getArguments().getString(IMAGE_RESOURCE_URL);
        ImageView imageView = (ImageView)view.findViewById(R.id.fragment_image);
        Picasso.with(context).load(url).fit().into(imageView);      
    
    }        
    
  3. The onInstantiateItem() method of the FragmentPagerAdapter.

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
    
        View v = inflater.inflate(R.layout.layout_fragment, container, false);
        Context context = Tab1Activity.this;
        String url = getItem(position).getArguments().getString("IMAGE_RESOURCE_URL");
        ImageView imageView = (ImageView)v.findViewById(R.id.fragment_image);
        Picasso.with(context).load(url).fit().into(imageView);
        return v;
    }
    

None of these methods worked. I know that its not a problem with Picasso because the other day I tried using Picasso in a ListView and it worked like a charm. What am I doing wrong ?


Solution

  • Your first approach should work fine... if you implement it correctly. I would expect your code to crash with a NullPointerException.

    Replace:

    ImageView imageView = (ImageView)getView().findViewById(R.id.fragment_image);
    

    with:

    ImageView imageView = (ImageView)myFragmentView.findViewById(R.id.fragment_image);