title: TabLayout not properly displaying fragment
body: <p>I have an activity with a tablayout. When the activity is created, the viewpageradapter is created and adds 3 instances of the same fragment class to it. Then, then, I set the adapter to the view pager.</p>
  
  <p>I know that the fragment addition is happening correctly because my fragment executes an asyncTask and its logging statements appear in the console. For some reason, when I start the activity, I can see the app bar and the widget displaying the tabs, but the space where the fragment should appear is empty. What am I doing wrong?</p>
  
  <p>This is my code:</p>
  
  <p>MainActivity </p>
  
  <pre><code>import android.os.Bundle;
  import android.support.design.widget.FloatingActionButton;
  import android.support.design.widget.Snackbar;
  import android.support.design.widget.TabLayout;
  import android.support.v4.app.Fragment;
  import android.support.v4.view.ViewPager;
  import android.support.v7.app.AppCompatActivity;
  import android.support.v7.widget.Toolbar;
  import android.view.View;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.Spinner;
  
  import java.util.ArrayList;
  import java.util.List;
  
  public class MainActivity extends AppCompatActivity {
  
      private final String LIST_TAG = MovieListFragment.class.getSimpleName();
      private final String DETAIL_TAG = DetailActivityFragment.class.getSimpleName();
      private final String POPULAR = "POPULAR";
      private final String HIGHEST_RATED = "HIGHEST RATED";
      private final String FAVOURITE = "FAVOURITE";
      private boolean mTwoPane;
      private TabLayout mTabLayout;
      private ViewPager mViewPager;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
  
          //We check if the layout selected has two fragments
          if (findViewById(R.id.movie_detail_container) != null) {
              //If it has two, we update our member variable
              mTwoPane = true;
  
              /*If the activity has been recently created, we replace the placeholder
              frameview with the actual detail fragment
               */
              if (savedInstanceState == null) {
                  getSupportFragmentManager().beginTransaction()
                          .replace(
                                  R.id.movie_detail_container,
                                  new DetailActivityFragment(),
                                  DETAIL_TAG
                          ).commit();
              }
          } else {
              mTwoPane = false;
          }
  
          mViewPager = (ViewPager) findViewById(R.id.viewpager);
          setupViewPager(mViewPager);
  
          mTabLayout = (TabLayout) findViewById(R.id.tabs);
          mTabLayout.setupWithViewPager(mViewPager);
  
          Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
          setSupportActionBar(toolbar);
          /*If it's the first time we launch the activity, we create a fragment
          and tag it so we have a reference to find it later
           */
      }
  
      private void setupViewPager(ViewPager viewPager) {
          ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
          MovieListFragment popular = new MovieListFragment();
          MovieListFragment highestRated = new MovieListFragment();
          MovieListFragment favourites = new MovieListFragment();
  
          populateFragment(popular);
          populateFragment(highestRated);
          populateFragment(favourites);
  
          adapter.addFragment(popular, POPULAR);
          adapter.addFragment(highestRated, HIGHEST_RATED);
          adapter.addFragment(favourites, FAVOURITE);
          viewPager.setAdapter(adapter);
      }
  
      private void populateFragment(Fragment fragment) {
          getSupportFragmentManager().beginTransaction()
                  .add(R.id.container, fragment)
                  .commit();
      }
  
      @Override
      public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.menu_main, menu);
  
          return true;
      }
  
      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.
          int id = item.getItemId();
          //We identify the option clicked and act accordingly
          switch (id) {
              /* Not necessary at this stage of the project. Will be
              populated later.
               */
              case R.id.action_settings: {
                  return true;
              }
              /* If the sort method is changed we start an asynchronous task
              and fetch the appropriate movies.
               */
              case R.id.sort_popularity: {
                  MovieListFragment.setmSortOrder("popularity.desc");
                  MovieListFragment movieListFragment = (MovieListFragment)
                          getSupportFragmentManager().findFragmentByTag(LIST_TAG);
                  movieListFragment.retrieveMovies();
                  break;
              }
              case R.id.sort_highest_Rating: {
                  MovieListFragment.setmSortOrder("vote_average.desc");
                  MovieListFragment movieListFragment = (MovieListFragment)
                          getSupportFragmentManager().findFragmentByTag(LIST_TAG);
                  movieListFragment.retrieveMovies();
                  break;
              }
          }
  
          return super.onOptionsItemSelected(item);
      }
  }
  </code></pre>
  
  <p>ViewPagerAdapter </p>
  
  <pre><code>import android.support.v4.app.Fragment;
  import android.support.v4.app.FragmentManager;
  import android.support.v4.app.FragmentPagerAdapter;
  
  import java.util.ArrayList;
  import java.util.List;
  
  class ViewPagerAdapter extends FragmentPagerAdapter {
      private final List&lt;Fragment&gt; mFragmentList = new ArrayList&lt;&gt;();
      private final List&lt;String&gt; mFragmentTitleList = new ArrayList&lt;&gt;();
  
      public ViewPagerAdapter(FragmentManager manager) {
          super(manager);
      }
  
      @Override
      public Fragment getItem(int position)
      {
          return new MovieListFragment();
      }
  
      @Override
      public int getCount() {
          return mFragmentList.size();
      }
  
      public void addFragment(Fragment fragment, String title) {
          mFragmentList.add(fragment);
          mFragmentTitleList.add(title);
      }
  
      @Override
      public CharSequence getPageTitle(int position) {
          return mFragmentTitleList.get(position);
      }
  }
  </code></pre>
  
  <p>MovieListFragment </p>
  
  <pre><code>import android.content.Context;
  import android.content.Intent;
  import android.net.Uri;
  import android.os.AsyncTask;
  import android.os.Parcelable;
  import android.support.v4.app.Fragment;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.LayoutInflater;
  import android.view.Menu;
  import android.view.MenuInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.AdapterView;
  import android.widget.ArrayAdapter;
  import android.widget.GridView;
  import android.widget.ImageView;
  import android.widget.TextView;
  
  
  import com.squareup.picasso.Picasso;
  
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;
  
  import java.io.BufferedReader;
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.InputStreamReader;
  import java.net.HttpURLConnection;
  import java.net.URL;
  import java.util.ArrayList;
  import java.util.List;
  
  
  /**
   * A placeholder fragment containing a simple view.
   */
  public class MovieListFragment extends Fragment {
  
      //Defining size params for the images in the gridview
      private final int IMAGE_WIDTH = 450;
      private final int IMAGE_HEIGHT = 675;
  
      private static String mSortOrder = "popularity.desc";
  
      public final static String EXTRA_MOVIE = "com.example.android.movierating.EXTRA_MOVIE";
  
  
      private final String LOG_TAG = MovieListFragment.class.getSimpleName();
  
      MovieAdapter mMovieAdapter;
      private LayoutInflater mInflater;
  
      public MovieListFragment() {
      }
  
      @Override
      public void onCreate(Bundle SavedInstanceState) {
          super.onCreate(SavedInstanceState);
          // We want to add options to the Menu bar.
          setHasOptionsMenu(true);
      }
  
      public static String getmSortOrder() {
          return mSortOrder;
      }
      public static void setmSortOrder(String sortOrder) {
          mSortOrder = sortOrder;
      }
  
      @Override
      public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
          inflater.inflate(R.menu.movielist_fragment, menu);
      }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
                               Bundle savedInstanceState) {
          mInflater = inflater;
          // We inflate and store the rootView
          View rootView = inflater.inflate(R.layout.fragment_main, container, false);
          // We sotre the gridview and set a custom adapter to it. It is defined below
          GridView gridView = (GridView) getActivity().findViewById(R.id.gridview);
          mMovieAdapter = new MovieAdapter(
                  getContext(),
                  R.id.image_thumbnail,
                  new ArrayList&lt;Movie&gt;()
          );
          gridView.setAdapter(mMovieAdapter);
  
          /* The gridView will react to a user clicking on it by creating
             an intent and populating it with the movie object. That object
             will provide the data necessary to display facts about the movie
           */
          gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
                  Movie movie = mMovieAdapter.getItem(position);
                  Intent detailIntent = new Intent(getActivity(), DetailActivity.class)
                          .putExtra(EXTRA_MOVIE, (Parcelable) movie);
                  startActivity(detailIntent);
  
                  }
          });
          return rootView;
      }
  
      public void retrieveMovies() {
          if (getmSortOrder() == "popularity.desc" || getmSortOrder() == "vote_average.desc") {
              FetchMoviesTask moviesTask = new FetchMoviesTask();
              String sortOrderArray[] = {mSortOrder};
              moviesTask.execute(sortOrderArray);
          }
      }
  
      @Override
      public void onStart() {
          super.onStart();
          retrieveMovies();
      }
  
      // Custom adapter to display Movies on a gridView
      public class MovieAdapter extends ArrayAdapter&lt;Movie&gt; {
          //Context member variable
          private Context mContext;
          //Constructor
          public MovieAdapter(Context context, int imgViewResourceId,
                              ArrayList&lt;Movie&gt; items) {
              super(context, imgViewResourceId, items);
              mContext = context;
          }
          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
  
              View view = null;
              if (convertView == null) {
                  view = mInflater.inflate(R.layout.fragment_main,null);
              } else {
                  view = convertView;
              }
              ImageView imageView = (ImageView) view.findViewById(R.id.image_thumbnail);
              TextView textView = (TextView) view.findViewById(R.id.overlay_text);
  
              String url = getItem(position).getUrlPath();
              Picasso.with(mContext)
                      .load(url)
                      .resize(IMAGE_WIDTH,IMAGE_HEIGHT)
                      .centerCrop()
                      .into(imageView);
  
              String movieTitle = getItem(position).getOriginalTitle();
              textView.setText(movieTitle);
              textView.setBackgroundColor(getResources().getColor(R.color.translucid_black));
              textView.setTextColor(getResources().getColor(R.color.opaque_white));
  
              return view;
          }
  
      }
  
  
      // Nested class to fetch the Json information about the movies
      public class FetchMoviesTask extends AsyncTask&lt;String, Void, List&lt;Movie&gt;&gt; {
  
          //Log tag for debugging purposes
          private final String LOG_TAG = FetchMoviesTask.class.getSimpleName();
  
          // Method to take a JSON string and return a list of Movie
          // objects.
          private List&lt;Movie&gt; parseJSONtoArrayList(String stringJSON)
                  throws JSONException{
  
              // String constants and the arraylist holding the results
              final String MDB_RESULTS = "results";
              final String MDB_ID = "id";
              final String MDB_PATH = "poster_path";
              final String MDB_TITLE = "original_title";
              final String MDB_SYNOPSIS = "overview";
              final String MDB_RATING = "vote_average";
              final String MDB_VOTE_COUNT = "vote_count";
              final String MDB_RELEASE = "release_date";
  
              List&lt;Movie&gt; movieArrayList = new ArrayList&lt;&gt;();
  
              // We turn the results into a JSONObject and we extract the JSONObjects
              // into an array of objects.
              JSONObject dataJSON = new JSONObject(stringJSON);
              JSONArray movieArray = dataJSON.getJSONArray(MDB_RESULTS);
  
              /* We iterate over the array of JSONObjects, we create a new
                 Movie object and we append it to the arraylist holding the
                 results.
              */
              for (int i=0; i&lt;movieArray.length(); i++) {
                  // Select a JSONObject in every iteration.
                  JSONObject target = movieArray.getJSONObject(i);
                  /* Create a Movie Object by retrieving the necessary elements
                     of the JSONObject
                   */
                  Movie movie = new Movie(
                          target.getInt(MDB_ID),
                          createURL(target.getString(MDB_PATH)),
                          target.getString(MDB_TITLE),
                          target.getString(MDB_SYNOPSIS),
                          Float.parseFloat(target.getString(MDB_RATING)),
                          Integer.parseInt(target.getString(MDB_VOTE_COUNT)),
                          target.getString(MDB_RELEASE)
                  );
                  // Once we have created our object, we add it to the arrayList
                  movieArrayList.add(movie);
              }
              return movieArrayList;
          }
          /* Transform a relative path provided by the API into a fully functional
             URL path.
           */
          private String createURL(String relativePath) {
              final String BASE_IMAGE_URL = "http://image.tmdb.org/t/p/";
              final String PIX_MEASURE = "w185";
  
              return BASE_IMAGE_URL + PIX_MEASURE + relativePath;
          }
  
          @Override
          protected List&lt;Movie&gt; doInBackground(String... params) {
              // Our default sorting parameter, request declaration,
              // reader and empty string
              String sortMethod = params[0];
              HttpURLConnection connection = null;
              BufferedReader reader = null;
              String moviesJSON = null;
  
  
              try {
                  // We build the URI
                  final String BASE_URL =
                          "http://api.themoviedb.org/3/discover/movie?";
                  final String API_KEY = "api_key";
                  final String SORT = "sort_by";
  
                  String uri = Uri.parse(BASE_URL)
                          .buildUpon().appendQueryParameter(SORT, sortMethod)
                          .appendQueryParameter(API_KEY, getString(R.string.ApiKey))
                          .build().toString();
  
                  URL url = new URL(uri);
                  //Create the request and open the connection
                  connection = (HttpURLConnection) url.openConnection();
                  connection.setRequestMethod("GET");
                  connection.connect();
  
                  // Create objects to hold the results of the API call
                  InputStream inputStream = connection.getInputStream();
                  StringBuilder builder = new StringBuilder();
  
                  // If we don't receive anything, we just return
                  if (inputStream == null) {
                      return null;
                  }
                  reader = new BufferedReader(new InputStreamReader(inputStream));
  
                  // We write the api call results into the string builder
                  String line;
                  while ((line = reader.readLine()) != null) {
                      builder.append(line + '\n');
                  }
                  // We check that the result is not empty
                  if (builder.length() == 0) {
                      return null;
                  }
  
                  moviesJSON = builder.toString();
  
              } catch (IOException e) {
                  Log.e(LOG_TAG, "There was a problem fetching the movies");
                  e.printStackTrace();
              } finally {
                  if (connection != null) {
                      connection.disconnect();
                  }
                  if (reader !=null) {
                      try {
                          reader.close();
  
                      } catch (IOException e) {
                          Log.e(LOG_TAG, "We found a problem while closing the reader");
                          e.printStackTrace();
                      }
                  }
              }
              try {
                  return parseJSONtoArrayList(moviesJSON);
  
              } catch (JSONException e) {
                  Log.e(LOG_TAG, e.toString());
                  e.printStackTrace();
              }
  
              return null;
          }
  
          @Override
          protected void onPostExecute(List&lt;Movie&gt; movies) {
              super.onPostExecute(movies);
              if (movies != null) {
                  // Every time we call this task, we flush the Movies in the adaptor
                  // And fill it up again with the results of the API call.
                  mMovieAdapter.clear();
                  Log.e(LOG_TAG, movies.toString());
                  mMovieAdapter.addAll(movies);
              }
          }
  
      }
  }
  </code></pre>
  
  <p>Thank you very much in advance</p>