Refresh images on FragmentStatePagerAdapter on resuming activity
Asked Answered
C

4

18

I have created an activity that uses FragmentStatePagerAdapter to provide small gallery. However, I can't get it to refresh when activity resumes (after coming back from other activity, for example). Every time first two pictures will be blank, and only after i swipe two pictures to the side, they get refreshed. None of the answers I've found work (especially overriding getItemPosition())

I set it up like this:

mPagerAdapter = new PhotosPagerAdapter(getSupportFragmentManager());
mPager = (ViewPager) findViewById(R.id.photosViewPager);
mPager.setAdapter(mPagerAdapter);

Then I have FragmentStatePagerAdapter class:

private class PhotosPagerAdapter extends FragmentStatePagerAdapter{

    public PhotosPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return photos.size();   
    }

    @Override
    public Fragment getItem(int position) {
        ImageFragment f = new ImageFragment(position);
        return f;
    }

    @Override
    public int getItemPosition(Object object) {
        throw new RuntimeException();
        //return POSITION_NONE;
    }

}

As you probably noticed, I throw RuntimeException in getItemPosition, because I wanted to check when it's called. And it isn't called until I add something to list containing my pictures. Then ImageFragment class:

public class ImageFragment extends Fragment{

    int position;
    Bitmap mBitmap;
    int width;
    int height;
    ImageView img;

    public ImageFragment(){
    }

    public ImageFragment(int position){
        this.position = position;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        img = new ImageView(container.getContext());
        img.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        width = container.getWidth();
        height = container.getHeight();

        loadBitmap();

        return img;
    }       

    public void loadBitmap(){
        if (img == null){
            return;
        }
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(photos.get(position), options);
        options.inSampleSize = calculateInSampleSize(options, width/2, height/2);
        options.inJustDecodeBounds = false;
        mBitmap = BitmapFactory
                .decodeFile(photos.get(position), options);         

        img.setImageBitmap(mBitmap);
    }


    @Override
    public void onDestroyView() {
        mBitmap.recycle();
        super.onDestroyView();
    }       
}

Code is kinda messy after I tried to fix it... But: removing onDestroyView() doesn't work. I have put mPagerAdapter.notifyDataSetChanged() in several places that must be called (like onResume()), with no result. I'm getting kinda desperate with that.

Colfin answered 4/12, 2012 at 3:31 Comment(0)
E
37

Dealing with fragment pager adapters can be a PITA.

Here are a few helpful tips:

ViewPager PagerAdapter not updating the View

Update ViewPager dynamically?

Generally speaking this one works 99% of the time...

Override getItemPosition in your PagerAdapter like this:

@Override
public int getItemPosition(Object object) {
    return POSITION_NONE;
}

Sometimes even those don't work, I have to use the 'brute force' method and recreate the entire view again (from onCreate onwards)...

Elene answered 4/12, 2012 at 4:12 Comment(1)
Works corresponding to the adapter's notifyDataSetChanged() call.Acherman
A
4

I was having a similar problem like your, after some research i created a nice script that avoid recreating fragments that are already there but at the same time allow you to update all visible/initiated fragment.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.view.ViewGroup;

import java.util.WeakHashMap;

/**
 * Created by TheCobra on 9/17/15.
 */
public abstract class FragmentAdvanceStatePagerAdapter extends FragmentStatePagerAdapter
{
    private WeakHashMap<Integer, Fragment> mFragments;

    public FragmentAdvanceStatePagerAdapter(FragmentManager fm)
    {
        super(fm);
        mFragments = new WeakHashMap<Integer, Fragment>();
    }

    @Override
    public Fragment getItem(int position)
    {
        Fragment item = getFragmentItem(position);
        mFragments.put(Integer.valueOf(position), item);
        return item;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object)
    {
        super.destroyItem(container, position, object);
        Integer key = Integer.valueOf(position);
        if (mFragments.containsKey(key))
        {
            mFragments.remove(key);
        }
    }

    @Override
    public void notifyDataSetChanged()
    {
        super.notifyDataSetChanged();
        for (Integer position : mFragments.keySet())
        {
            //Make sure we only update fragments that should be seen
            if (position != null && mFragments.get(position) != null && position.intValue() < getCount())
            {
                updateFragmentItem(position, mFragments.get(position));
            }
        }
    }

    @Override
    public int getItemPosition(Object object)
    {
        //If the object is a fragment, check to see if we have it in the hashmap
        if (object instanceof Fragment)
        {
            int position = findFragmentPositionHashMap((Fragment) object);
            //If fragment found in the hashmap check if it should be shown
            if (position >= 0)
            {
                //Return POSITION_NONE if it shouldn't be display
                return (position >= getCount()? POSITION_NONE : position);
            }
        }

        return super.getItemPosition(object);
    }

    /**
     * Find the location of a fragment in the hashmap if it being view
     * @param object the Fragment we want to check for
     * @return the position if found else -1
     */
    protected int findFragmentPositionHashMap(Fragment object)
    {
        for (Integer position : mFragments.keySet())
        {
            if (position != null &&
                mFragments.get(position) != null &&
                mFragments.get(position) == object)
            {
                return position;
            }
        }

        return -1;
    }

    public abstract Fragment getFragmentItem(int position);
    public abstract void updateFragmentItem(int position, Fragment fragment);
}

Copy that code into a file name "FragmentAdvanceStatePagerAdapter.java". Now in your adapter, extend from this one and override "getFragmentItem()" & "updateFragmentItem()". Whenever you call notifydatachange(), updateFragmentItem() will be called with all the fragment already created. When the adapter need to create a new fragment, getFragmentItem() will be called.

I hope that save and help a lot of people :)

Good Luck and happy Programming!!!

P.S. your adapter "getItem()" should be "getFragmentItem()" if you use this class.

Addy answered 17/9, 2015 at 21:0 Comment(0)
B
1

Instead of returning POSITION_NONE and creating all fragments again, you can do as I suggested here: Update ViewPager dynamically?

Bighorn answered 25/7, 2013 at 10:42 Comment(0)
H
1

Never just use POSITION_NONE use

if(fragmentManager.getFragments().contains(object))
    return POSITION_NONE;
else
    return POSITION_UNCHANGED;

to avoid Fatal Exception: java.lang.IllegalStateException Fragment {} is not currently in the FragmentManager

Hebner answered 23/9, 2014 at 23:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.