Home > DeveloperSection > Forums > Android ViewPager having same instance every time
Sanjay Sharma
Sanjay Sharma

Total Post:45

Posted on    October-30-2015 4:35 AM

 Android Android  Android Controls 

 1 Reply(s)
 347  View(s)
Rate this:
I have a viewPager with for 10 pages. In all of theses pages, I have a YouTubePlayer with a different id video.
The problem is that all the YouTubePlayer component has the same video at the same time.

Concretely :
When the first page is displayed, the YouTubePlayer show the first video, so all seems to be ok. When I try to scroll to the 2nd page, I can see that the 2nd YouTubePlayer show the same video. When the 2nd page is completely displayed (After scrolling), behind the view pager prepare the 3rd page. So on the 3rd page the 3rd id video is set to the YouTubePlayer component. At that moment the 2nd page currently displayed switch automatically to the 3rd video.

It was like if the instance of YouTubePlayer was single for all the pages. But on each page new FragmentYouTubePlayer() is correctly called.

I don't understand where is the problem. Finally, I wonder if it's possible to use severals YouTubePlayer component (in a viewpager) at the same time or not ?

Mayank Tripathi
Mayank Tripathi

Total Post:397

Posted on    October-30-2015 7:21 AM

 YouTubePlayer follows the Singleton pattern controlling all the different YouTubePlayerView instances. 

Just out of curiouslty i have implelemented a sample for this and it worked for me, so my code may help you analyze your problem

In my main activity, using PagerAdapter :
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
    public android.support.v4.app.Fragment getItem(int position) {
        fragmentYouTubeContent = FragmentYouTubeContent.create(position);
        return fragmentYouTubeContent;
    public int getCount() {
        int nb = 3;
        return nb;
My FragmentYouTubeContent.class
package com.orange.OrangeJobs;

import java.util.List;

import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubeStandalonePlayer;
import com.google.android.youtube.player.YouTubeThumbnailLoader;
import com.google.android.youtube.player.YouTubeThumbnailView;

import android.support.v4.app.Fragment;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

public class FragmentYouTubeContent extends Fragment implements YouTubeThumbnailView.OnInitializedListener {
      public static final int REQ_START_STANDALONE_PLAYER = 101;
      private static final int REQ_RESOLVE_SERVICE_MISSING = 2;
      private static final int RECOVERY_DIALOG_REQUEST = 1;
     * The fragment's page number.
    private int mPageNumber;
    private String urlYouTube;
    private boolean canHideStatusBar = false;
    private Dialog errorDialog;
    FrameLayout rl;
    private YouTubeThumbnailView thumbnailView;
     * Factory method for this fragment class. Constructs a new fragment for the given page number.
    public static FragmentYouTubeContent create(int pageNumber) {
        FragmentYouTubeContent fragment = new FragmentYouTubeContent();
        return fragment;
    public FragmentYouTubeContent() {
    public void onCreate(Bundle savedInstanceState) {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.youtube, container, false);
        urlYouTube = "YOUR_VIDEO_URL";
        if (!"".equals(urlYouTube)) {
            thumbnailView = (YouTubeThumbnailView) rootView.findViewById(R.id.youtubethumbnailview);
            thumbnailView.initialize(Params.YOUTUBE_KEY, this);
            thumbnailView.setOnClickListener(new OnClickListener(){
                public void onClick(View arg0) {
                    // Launch standalone YoutTube player
                    Intent intent = null;
                    intent = YouTubeStandalonePlayer.createVideoIntent(getActivity(), YOUTUBE_KEY, urlYouTube, 0, true, false);
                    if (intent != null) {
                      if (canResolveIntent(intent)) {
                          canHideStatusBar = true;
                          startActivityForResult(intent, REQ_START_STANDALONE_PLAYER);
                      } else {
                          // Could not resolve the intent - must need to install or update the YouTube API service.
                                .getErrorDialog(getActivity(), REQ_RESOLVE_SERVICE_MISSING).show();
        return rootView;
    public void onResume() {
        boolean isLandscape = false;
        int currentOrientation = getResources().getConfiguration().orientation;
        if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            isLandscape = true;
        else {
            isLandscape = false;
        if (canHideStatusBar && this.isVisible() && isLandscape) {
            canHideStatusBar = false;
    public void onPause() {

    public void onInitializationSuccess(YouTubeThumbnailView thumbnailView, YouTubeThumbnailLoader thumbnailLoader) {
    public void onInitializationFailure(YouTubeThumbnailView thumbnailView, YouTubeInitializationResult errorReason) {
        if (errorReason.isUserRecoverableError()) {
            if (errorDialog == null || !errorDialog.isShowing()) {
              errorDialog = errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST);
          } else {
            String errorMessage = String.format(getString(R.string.error_thumbnail_view), errorReason.toString());
            Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
    // ***** Private methods *************************************************************************************
    private boolean canResolveIntent(Intent intent) {
        List<ResolveInfo> resolveInfo = getActivity().getPackageManager().queryIntentActivities(intent, 0);
        return resolveInfo != null && !resolveInfo.isEmpty();
    // ***** Properties methods *************************************************************************************
     * Returns the page number represented by this fragment object.
    public int getPageNumber() {
        return mPageNumber;
     * @param pageNumber the pageNumber to set
    public void setPageNumber(int pageNumber) {
        this.mPageNumber = pageNumber;
     * @return the canHideStatusBar
    public boolean isCanHideStatusBar() {
        return canHideStatusBar;
     * @param canHideStatusBar the canHideStatusBar to set
    public void setCanHideStatusBar(boolean canHideStatusBar) {
        this.canHideStatusBar = canHideStatusBar;

My layout : youtube.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal" >

                android:layout_height="match_parent" />    

Don't want to miss updates? Please click the below button!

Follow MindStick