First fragment in view pager not showing because of rest api delay

viewpager2
viewpager2 & tablayout
viewpager2 example
viewpager2 adapter
viewpager2 kotlin
updating viewpager with new data dynamically
android-viewpager change page from fragment
viewpager android

I have a navigation drawer activity, with one fragment having a view pager and tabs. All 4 fragments are fetching data from a server. My problem is that the view pager is loading the first 2 fragments therefore my first fragment doesn't show a content at first because of the delay of the rest api. So the second fragment is being created and shown before the data in the first fragment is parsed and shown. How can I solve this?

This is my fragment container

public class FragmentMoviesContainer extends KFragment {
private MainActivity activity;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_movies_container, container, false);
    activity = (MainActivity) getActivity();
    assert activity != null;
    activity.setVisibleFragment(this);
    SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
    // Set up the ViewPager with the sections adapter.
    ViewPager mViewPager = rootView.findViewById(R.id.container);
    TabLayout tabLayout = rootView.findViewById(R.id.tabs);

    mViewPager.setAdapter(mSectionsPagerAdapter);
    tabLayout.setupWithViewPager(mViewPager);

    return rootView;
}

@Override
public void onResume() {
    super.onResume();
    ActionBar actionBar = activity.getSupportActionBar();
    if (actionBar != null)
        actionBar.setTitle(R.string.movies);

    activity.getNavigationView().setCheckedItem(R.id.nav_movies);
    activity.setElevation(true);
}

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }


    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return replaceFragmentMovies(Constants.STRINGS.UPCOMING);
            case 1:
                return replaceFragmentMovies(Constants.STRINGS.NOW_PLAYING);
            case 2:
                return replaceFragmentMovies(Constants.STRINGS.POPULAR);
            case 3:
                return replaceFragmentMovies(Constants.STRINGS.TOP_RATED);
            default:
                return null;
        }
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getString(R.string.coming_soon);
            case 1:
                return getString(R.string.now_playing);
            case 2:
                return getString(R.string.popular);
            case 3:
                return getString(R.string.top_rated);
            default:
                return "";
        }
    }

    @Override
    public int getCount() {
        return 4;
    }


    private FragmentMovies replaceFragmentMovies(String type) {
        FragmentMovies fragmentMovies = new FragmentMovies();
        fragmentMovies.setType(type);
        return fragmentMovies;
    }
}

@Override
public void serviceResponse(int responseID, List<KObject> objects) {

}

@Override
public void update(ModelService service, boolean reload) {
}
}

Here's my fragment showed in the tabs

public class FragmentMovies extends KFragment implements MoviesAdapter.OnLoadMoreListener {
private MainActivity activity;
private ModelService service;

private RecyclerView moviesRv;
private String type;

public void setType(String type) {
    this.type = type;
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
    activity = (MainActivity) getActivity();

    if (activity != null) {
        service = activity.getService();
        activity.setVisibleFragment(this);
    }

    moviesRv = rootView.findViewById(R.id.movies_list);
    moviesRv.setLayoutManager(new LinearLayoutManager(getContext()));
    this.update(service, false);

    return rootView;
}


@Override
public void serviceResponse(int responseID, List<KObject> objects) {
    if ((objects != null && !objects.isEmpty()) && (responseID == Constants.UPCOMING || responseID == Constants.NOW_PLAYING || responseID == Constants.POPULAR
            || responseID == Constants.TOP_RATED)) {
        Section section = (Section) objects.get(0);
        MovieListAdapter adapter = new MovieListAdapter(getContext(), section.getMovieList());
        moviesRv.setAdapter(adapter);
    }
}

@Override
public void update(final ModelService service, final boolean reload) {
    boolean hasConnection = Connection.isNetworkAvailable(getContext());
    if (hasConnection && service != null) {
        final int responseId = getResponseID();
        service.getMovies(type, "", false, responseId, reload);
    } else {
//            progressBar.setVisibility(View.GONE);
        DialogHelper.noConnectionDialog(getContext());
    }
}

private int getResponseID() {
    switch (type) {
        case Constants.STRINGS.UPCOMING:
            return Constants.UPCOMING;
        case Constants.STRINGS.NOW_PLAYING:
            return Constants.NOW_PLAYING;
        case Constants.STRINGS.POPULAR:
            return Constants.POPULAR;
        case Constants.STRINGS.TOP_RATED:
            return Constants.TOP_RATED;
        default:
            return 0;
    }
}

@Override
public void onLoadMore(MoviesAdapter adapter) {
}

@Override
public void onResume() {
    super.onResume();
    if (activity.getSupportActionBar() != null)
        activity.getSupportActionBar().setTitle("Movies");

    activity.getNavigationView().setCheckedItem(R.id.nav_movies);
    activity.setElevation(true);
    activity.getAddFab().hide();
}

@Override
public void onDestroy() {
    super.onDestroy();
}
}

The method update calls the rest api url and fetches the data. This is a framework I created based on AsyncTask. The list of objects then is returned to the fragment parsed in the method onServiceResponse where I create the adapter and show the data. The problem is that the second fragment is being created before the method onServiceResponse of the first fragment.

You should make api call from the first fragment and after getting the result you should make the rest of the calls. Let me know if you need any help with the code. I think this should be straight forward.

TabLayout inside fragment fetch data from web, I have three tabs that fetch data from web service. A5 I am not sure this time but I prefer SwipeRefreshLayout as user can refresh any Q7 why some items show different behaviour as I mention ? A7 its the most important answer to me , why adapter give wrong view , it cause of using if statement , when using if in adapter � Custom Pages without Fragments. While a ViewPager is often coupled with a Fragment for each page using the FragmentPagerAdapter, there are cases where the pages are better off as plain views. A good example is an image gallery, where the user can swipe between different pictures. To achieve this, we can extend from PagerAdapter:

After Looking your code, there are Two things to inflate Fragments on to tabs.

  1. Use single Fragment for all tabs.
  2. Use individual fragment for every tab.

in the First case, if you are calling APIs form fragment that kind of problem occurs(As yours).

in the Second case APIs, the call will be in individual fragment and there will not be such kind of problem. So the first solution to your problem is to use individual fragment for every tab. And if really want to use single fragment for every tab then maintain the sequence of API calling for every instance of the fragment for every tab.

As you are doing in fragment like:

if (activity != null) {
        service = activity.getService();
        activity.setVisibleFragment(this);
    }

    moviesRv = rootView.findViewById(R.id.movies_list);
    moviesRv.setLayoutManager(new LinearLayoutManager(getContext()));
    this.update(service, false);

in this case you are calling service and and then you are reading setting your view. The scenario is that here API call will be in the background but the code below API call will execute. Due to that if the response of API any fragment comes then that fragment view will be populated. So Solution of that scenario is that put your API call method in fragment and then call APIs and maintain calls. if any help just comments. thanks.

Migrate from ViewPager to ViewPager2, Vertical orientation support; Right-to-left support; Modifiable fragment collections; DiffUtil is receiving active development support and ViewPager is not. modify the fragment collection at runtime, and ViewPager2 will correctly display First, replace the ViewPager elements in your XML layout files with� I can actually also swipe the ViewPager in this fragment. When I swipe to the right I can see the blue indicator appearing on the left that I'm at the first Fragment and when I swipe to the left a few times this indicator appears on the right side. So the ViewPager is actually there, the Fragments just do not appear.

I think the accepted answer is not very explanatory, so for anyone coming across this in future, this is what I did. I am calling my REST API from the on create method of the activity hosting the fragments and viewpager and using a single fragment class for 6 tabs by creating 6 instances of the fragment class. But the catch here is, dont set up the viewpager in onCreate, rather set it after the API call receives a successful response, after the data has been saved inside some object. So now the data is ready to be displayed within the fragment when it is first presented.

Android Tab Layout with Swipeable Views, Even though you are not familiar with ViewPager or Fragments, don't worry. In order to display tabs we don't have to use any other UI element This is because ViewPager didn't know about the tab change event. I have the feeling that the first fragment are not remove or update. But it's working slow. ViewPager is a layout manager that allows the user to scroll left and right to navigate through multiple Fragments with a sliding animation. An adapter handles all the transactions between

You should add this code on your one of your fragment.

Handler().postDelayed({

//api call 

}, 3000)

So that two fragment can not do api call at same time when you use viewpager.

Android Image Slider Using Viewpager Github, How to add Dots Indicator to Image Slider with ViewPager in Android Studio I did not find any simple and useful solution to this that I could easily follow and implement in my app. We will use Fragment and ViewPager to display the images. I am getting a response from rest API in these API to have a JSONArray for� 2.2 Create Fragment Pages to be used in the viewPager. In this application, we will add three pages in viewPager. So, we need to create three fragment and it’s xml file. Below are the three fragments name that we are going to create now. (1) FirstFragment.java and first_fragment.xml file (2) SecondFragment.java and second_fragment.xml file

Video Still Playing after switching to new Tab Fragment inside , Viewpager First Tab having video Recylerview using Toro Rest two also have GitHub is home to over 50 million developers working together to host of toro in small config android devices and on the slow network? Now after few seconds Video automatically start playing even it is not in visible area� this code will get access to first fragment of ViewPager. and then you can type cast that Fragment into your Fragment. for example MyFragment mFragment = ( MyFragment ) page ; if above given solution not work for you then you can also try this method.

MVP for Android: how to organize the presentation layer, MVP (Model-View-Presenter) is a software design pattern that works pretty well in Android The first thing to clarify is that MVP is not an architecture by itself, it's only Delivery system : Activity, Fragment, Service and other Android related stuff. Can you show how to implement this pattern in a rest Client with SQLite� I'm able to build an activity with a viewpager from the various examples on the web, but can I no longer use the views as they were in the original activity? Take for example the following: public class SimpleViewPagerActivity extends Activity { LinearLayout thisIsWhatBreaks; @Override public void

Release Notes - Helpshift for Android, Fixed a bug where styling for Answer Bot suggestions was not working as Added new API for changing the Helpshift SDK theme at runtime.. Added support for embedding SDK fragments inside a host fragment. that would occur when user swipes through the FAQ sections view pager very quickly December 1st, 2015. - An Activity with a ViewPager in it. - There are 3 Fragments (pages) in ViewPager: DownLoadFragment, DateTimeFragment and a BlankFragment to "test". - Includes 2 Services run in background: Download file Service (show it's status to DownloadFragment) and getting DateTime Service (show curent date/time to UI in DateTimeFragment).

Comments
  • please provide some code.
  • @singh.indolia I added some code
  • i had a problem like this for a long time, i solved it by assigning the fragment to the Activity after finishing all the requests
  • You should use Android networking library such as Fast Android Networking Library to make the request asynchronously