How to refresh data in ViewPager Fragment

0 votes

This is what I am trying to do:

I have ViewPager in my Activity which hosts 6 Fragment. I disabled paging by swiping with finger, so whenever I want to swipe I use related button and :

viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);

In each fragment that is swiped (after swipe is finished) I want to send a GET request to my server and fetch some data and show it in that fragment. for doing that:

First Approach : I used this code in my fragments which runs as soon as fragment become visible:

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser)
        {
          sendGetRequest();
        }
}

But , here was a problem : that setUserVisibleHint executes exactly whene the fragment visible , and because of that the animation of swiping came with some lag(it wasn't smooth enough).

So I used Second Approach : I added an OnPageChangeListener() to ViewPager in hosted activity like this :

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            int CurrentPossition = 0;
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
            @Override
            public void onPageSelected(int position) {
                CurrentPossition = position;
            }
            @Override
            public void onPageScrollStateChanged(int state) {
                if(state == ViewPager.SCROLL_STATE_IDLE && CurrentPossition != 0){
                    Toast.makeText(getBaseContext(),"finished" , Toast.LENGTH_SHORT).show();

                    try{
                        new fragment_two().sendGetRequest();;
                    }catch(Exception ex){
                        ex.printStackTrace();
                    }
                }
            }
        });

It works great, and toast shows as soon as swipe finished, but unlike fragment which visible completely , when sendGetRequest() runs i get NullPointerException.

here is StackTrace :

04-08 20:15:37.840 12848-12848/com.example.mohamad.travelagency W/System.err: java.lang.NullPointerException
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err:     at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:152)
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err:     at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:103)
04-08 20:15:37.850 12848-12848/com.example.mohamad.travelagency W/System.err:     at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:143)
any idea would be great. 

Thanks in advance !!!

Mar 7, 2019 in Java by Sushmita
• 6,920 points
37,443 views

1 answer to this question.

0 votes

Using the ViewPager.OnPageChangeListener is the correct way to go, but you will need to refactor your adapter a bit in order to keep a reference to each Fragment contained in the FragmentPagerAdapter.

You do that using the instantiateItem() method override in the adapter, here is a simplified example:

 class PagerAdapter extends FragmentPagerAdapter {
        String tabTitles[] = new String[] { "One", "Two", "Three", "Four"};
        Context context;

        //This will contain your Fragment references:
        public Fragment[] fragments = new Fragment[tabTitles.length];

        public PagerAdapter(FragmentManager fm, Context context) {
            super(fm);
            this.context = context;
        }
        @Override
        public int getCount() {
            return tabTitles.length;
        }
        @Override
        public Fragment getItem(int position) {
            switch (position) {
            case 0:
                return new FragmentOne();
            case 1:
                return new FragmentTwo();
            case 2:
                return new FragmentThree();   
            case 3:
                return new FragmentFour();
            }
            return null;
        }

        //This populates your Fragment reference array:
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            Fragment createdFragment = (Fragment) super.instantiateItem(container, position);
            fragments[position]  = createdFragment;
            return createdFragment;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }         
 }

Then, instead of creating a new Fragment, use the one contained in the adapter:

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  @Override
  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

  @Override
  public void onPageSelected(int position) {

        // do this instead, assuming your adapter reference
        // is named mAdapter:
        Fragment frag = mAdapter.fragments[position];
        if (frag != null && frag instanceof FragmentTwo) {
          ((FragmentTwo)frag).sendGetRequest();
        }
  }

  @Override
  public void onPageScrollStateChanged(int state) {  }
});

Note that if you're using different Fragment classes in your adapter, you can implement an interface that defines sendGetRequest(), and in each of your Fragment classes implement the sendGetRequest() method.

If you don't go with the interface approach, you will need to cast the Fragment to your own Fragment type as shown in the example above, i.e.:

if (frag instanceof FragmentTwo) {
    ((FragmentTwo)frag).sendGetRequest();
}
answered Mar 7, 2019 by developer_1
• 3,350 points

Related Questions In Java

0 votes
1 answer

How to decode Base64 data in Java?

Java SE has the parser called JAXB, ...READ MORE

answered May 30, 2018 in Java by sharth
• 3,370 points
1,216 views
0 votes
1 answer

How to encode data using Base64 in Java?

import org.apache.commons.codec.binary.Base64; We can not use sun.* packages ...READ MORE

answered May 30, 2018 in Java by Sushmita
• 6,920 points
1,066 views
0 votes
1 answer

In Java, how to find out the min/max values from array of primitive data types?

import java.util.Arrays; import java.util.Collections; import org.apache.commons.lang.ArrayUtils; public class MinMaxValue { ...READ MORE

answered Jun 12, 2018 in Java by Daisy
• 8,140 points
1,650 views
0 votes
1 answer

How to refresh a JTable model after insert delete or update the data

In my opinion, you can notify your ...READ MORE

answered Oct 11, 2018 in Java by code.reaper12
• 3,500 points
24,953 views
0 votes
1 answer

How can we get the current location in Android?

First you need to define a LocationListener to handle ...READ MORE

answered Sep 25, 2018 in Java by Parth
• 4,640 points
927 views
0 votes
1 answer

Can't find class CognitoUserPoolsSignInProvider: Issue with Sign In integration

CognitoUserPoolsSignInProvider is ditributed as part of aws-android-sdk-auth-userpools library. Please import ...READ MORE

answered Sep 28, 2018 in AWS by Priyaj
• 58,020 points
937 views
0 votes
1 answer

How to Read/Write String from a File in Android

Writing a File in android: private void writeToFile(String ...READ MORE

answered Oct 3, 2018 in Java by sharth
• 3,370 points
7,372 views
0 votes
3 answers

How can I add new elements to an Array in Java

String[] source = new String[] { "a", ...READ MORE

answered Sep 19, 2018 in Java by Sushmita
• 6,920 points
13,212 views
0 votes
1 answer

How to parse invalid XML in Java ?

That "XML" is worse than invalid – it's not well-formed. An ...READ MORE

answered Mar 7, 2019 in Java by developer_1
• 3,350 points
5,463 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP