Arn
Arn

Reputation: 600

android ViewPager starts at a wrong random location after reload

I am writing a simple view pager test app that loads a bunch of data from a website and creates pages to display them. For the most part the displaying is pretty much all works. However, it falls apart when I load a new set of data to display. When I get a new set, it loads all the data perfectly well however, instead of starting from view 0 it starts at a random location. It could start at the end or somewhere in the middle. I want all the data to load from page 1, like a book. If you load a new book the book should start from page 1 not a random page.

Reloading calls

I've tried using GotCampDetails() which sets the local variable in the class.

viewPager.setCurrentItem(0);

in my fragment but it doesn't work. Also called notifydatasetchanged() on my adapter, still didn't work.

What am I missing?

public class ViewPagerFragment extends Fragment implements WebReadResultsListener {

private ArrayList<HashMap<String, String>> campDetails;
CustomPagerAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

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

    return inflater.inflate(R.layout.camp_viewpager, container, false);
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {

    if (campDetails != null && ! campDetails.isEmpty()) {
        ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        adapter = new CustomPagerAdapter(getActivity(), campDetails, viewPager);
        viewPager.setAdapter(adapter);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
    }
}

@Override
public boolean GotCampDetails(ArrayList<HashMap<String, String>> campDetails) {
    this.campDetails = campDetails;
    return true;
}

@Override
public boolean GotCampList(ArrayList<HashMap<String, String>> campDetails) {
    return false;
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    getFragmentManager().putFragment(outState,"fragmentInstanceSaved",getFragmentManager().findFragmentById(R.id.content));
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    // Handle orientation changes here
}
}

Adapter:

public class CustomPagerAdapter extends PagerAdapter implements ColorChangeListener {
private ArrayList<HashMap<String, String>> campDetails;
private ViewGroup collection;
private Context mContext;
private boolean isRunning = false;
private ColorChangeListener colorChangeListener;
private int color= pink;
private int currentposition;
private ViewPager viewPager;

public CustomPagerAdapter(Context context, final ArrayList<HashMap<String, String>> campDetails, ViewPager viewPager) {
    this.campDetails=campDetails;
    this.mContext = context;
    this.viewPager = viewPager;
    colorChangeListener = (ColorChangeListener) mContext;

    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int pos) {
            currentposition = pos;
            if (campDetails.get(currentposition).get("color").equals("green")) {
                color = green;
            } else {
                color = pink;
            }
            ColorAppBar(color);
        }
        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }
        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

@Override
public Object instantiateItem(ViewGroup collection, final int position) {
    LayoutInflater inflater = LayoutInflater.from(mContext);
    ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.child_item, collection, false);

    if (campDetails.size() <= 0) {
        Toast.makeText(mContext, "Error in getting camp details", Toast.LENGTH_SHORT).show();
        return null;
    }

    if (campDetails.get(position).get("description").equals("RD") ) {
        layout.setBackgroundColor(mContext.getResources().getColor(green));
    } else {
        layout.setBackgroundColor(mContext.getResources().getColor(pink));
    }

    collection.addView(layout);
    this.collection = collection;

    TextView eName = (TextView) layout.findViewById(R.id.en);
    TextView nEName= (TextView) layout.findViewById(R.id.nen);
    TextView textView6 = (TextView) layout.findViewById(R.id.textView6);
    // ImageView nextImg = (ImageView) groupLayout.get(index).findViewById(R.id.nextImg);

    eName.setText(campDetails.get(position).get("name"));
    if (position+1 < campDetails.size()) {
        nEName.setText(campDetails.get(position+1).get("name"));
        textView6.setVisibility(View.VISIBLE);
    } else {
        nEName.setText("You are DONE!!");
        textView6.setVisibility(View.INVISIBLE);
    }


    return layout;
}

@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
    collection.removeView((View) view);
}

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

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == object;
}

@Override
public CharSequence getPageTitle(int position) {
    return campDetails.get(position).get("name");
}

@Override
public void ColorAppBar(int color) {
    colorChangeListener.ColorAppBar(color);
}
}

Upvotes: 1

Views: 473

Answers (2)

Arn
Arn

Reputation: 600

I finally managed to get it done.

I had to delay the function call setCurrentItem by a few milliseconds. Race condition? I don't know why this is the case but now it works perfectly. Here is what I added in case someone else may find it useful:

    pager.postDelayed(new Runnable() {

        @Override
        public void run() {
            pager.setCurrentItem(pos);
        }
    }, 100);

Upvotes: 3

I'm having trouble following the details well enough to pinpoint the problem, but this guy seems to have accomplished what you're trying to do: dynamically add and remove view to viewpager

hope it helps

Upvotes: 0

Related Questions