Android YouTubePlayerApi: YouTubePlayer keeps on loading - android

I'm using YouTubePlayerAPI and YouTubePlayerSupportFragment in my app. Recently, I found that YouTubePlayer keeps on loading in first page when backed from secondary page. But I couldn't find out what is causing it. I've been looking for information but I haven't found anything useful.
My testing methodology:
Click the TextView to start the secondary page. Go back, the question has appeared.
Here is my code:
public class FragmentDemoActivity extends Activity implements YouTubePlayer.OnInitializedListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragments_demo);
TextView tvDes = (TextView) findViewById(R.id.tv_start_another);
tvDes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(v.getContext(), FragmentDemoActivity.class));
}
});
YouTubePlayerFragmentWrap youTubePlayerFragment =
(YouTubePlayerFragmentWrap) getFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}

Related

Youtube Player video not loading when returning to Fragment

I have set up a YouTubePlayerView which works perfectly but I face a weird problem. When I go to another Fragment and then go back, YouTubePlayerView can't load the video, even if the exact code is executed.
private String currentVideoID "p450mjB3mxc";
private YouTubePlayerView youtubeView;
private void init(View view)
{
youtubeView = view.findViewById(R.id.youtubeView);
new YoutubeHelper(youtubeView,currentVideoID,this);
}
public void setYoutubePlayer(YouTubePlayer youtubePlayerPublic)
{
this.youtubePlayer = youtubePlayerPublic;
youtubePlayer.loadVideo(currentVideoID);
}
YoutubeHelper.class:
public class YoutubeHelper {
public final static String YoutubeAPIKey="MY_API_KEY";
public YouTubePlayer youtubePlayerPublic;
private YouTubePlayerView youTubeView;
public YoutubeHelper(YouTubePlayerView youTubeView, String initialVideo, MainFragment fragment)
{
this.youTubeView = youTubeView;
init(initialVideo,fragment);
}
private void init(String initialVideo,final MainFragment fragment)
{
youTubeView.initialize(YoutubeAPIKey,
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
final YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(initialVideo);
youtubePlayerPublic = youTubePlayer;
fragment.setYoutubePlayer(youTubePlayer);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
Log.d("Youtube Error:", youTubeInitializationResult.toString());
}
});
}
}
I have tried this answer with no success at all.
Any ideas?
I found the solution if anyone facing the same problem. Before leaving the fragment do:
youtubePlayer.pause();
youtubePlayer.release();

How to refresh a fragment Activity?

I am developing a mobile application and this one has a YoutubePlayerView in a fragment. When the app load the fragment who has the YoutubePlayerView for first time, it works well, but when I move to other fragment and then back to the fragment the video can't be played.
I think this happens because the fragment never goes.
I would like to someone help me to reload the fragment or reload the
YoutubePlayerView.
Here is method:
private void loadYoutubeVideo(){
youTubePlayerView.initialize(Constant.API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b){
youTubePlayer.cueVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(NewPortApplication.getAppContext(), "Falló al inicializar el video", Toast.LENGTH_LONG).show();
}
});
}
Use this in your Fragment
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
if(isVisibleToUser){
loadYoutubeVideo();
}
}

How to refresh Youtube Player View onItemClickListener() in a ListView

I am able to play Youtube videos using cuePlaylist() but I also want to allow user to tap on any of the list item and then I want to refresh YoutubePlayerView with the video user just tapped
I am using cuePlaylist() so getting previous and next buttons as default functionality of Youtube player
So can I refresh YoutubePlayerView with the one I have selected in a ListView?
Here is my complete code, still when I do tap on any of the list item, not getting any change in YoutubePlayerView but able to Log video Id which I just clicked in a ListView...
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
strVideoID = flowerList.get(i).getUrl();
Log.d("url:", strVideoID); // getting particular video id
youTubePlayerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
// YouTubeプレーヤーの初期化成功
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
player.loadVideo(strVideoID);
player.play();
}
}
// YouTubeプレーヤーの初期化失敗
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult error) {
// YouTube error
String errorMessage = error.toString();
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
Log.d("errorMessage:", errorMessage);
}
});
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.cuePlaylist(PLAYLIST_ID);
}
}
You are using the wrong approach here, you don't need to call initialize on YoutubePlayerFragment each time, the first initialization is enough which you done in onCreate method
YouTubePlayerFragment youTubePlayerFragment = YouTubePlayerFragment.newInstance();
youTubePlayerFragment.initialize(API_KEY, this);
In the initialization listener you implemented in Activity, You should keep the reference of YoutubePlayer in a class level attribute like this
//your class level attribute to keep reference of player
YouTubePlayer mYoutubePlayer;
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.cuePlaylist(PLAYLIST_ID);
//Save reference of initialized player in class level attribute
mYoutubePlayer = youTubePlayer;
}
}
And use this player attribute to load videos inside onItemClick instead of calling initialize again on YoutubePlayerFragment with new listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
strVideoID = flowerList.get(i).getUrl();
Log.d("url:", strVideoID); // getting particular video id
if(mYoutubePlayer!=null){
mYoutubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
mYoutubePlayer.loadVideo(strVideoID);
mYoutubePlayer.play();
}
}
});
step to play any you tube video
1 create a you tube view in xml file.
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp" />
inside java file
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
// YouTube player view
private YouTubePlayerView youTubeView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// Initializing video player with developer key
youTubeView.initialize(Config.DEVELOPER_KEY, this);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
player.loadVideo(YOUTUBE_VIDEO_CODE);
// Hiding player controls
player.setPlayerStyle(PlayerStyle.CHROMELESS);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}

Video is not playing in YoutubePlayer Fragment

I am making an app which uses Youtube player fragment. It is loaded but video is not getting played. Here is my code:
Youtube.java (Fragment)
public class Youtube extends YouTubePlayerFragment {
public Youtube() {
}
public static Youtube newInstance(String url) {
Youtube frag = new Youtube();
Bundle b = new Bundle();
b.putString("url", url);
frag.setArguments(b);
frag.init();
return frag;
}
private void init() {
initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
// player.play();
}
}
});
}
}
Activity:
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
Youtube f = Youtube.newInstance("https://www.youtube.com/watch?v=o49aHgzTOGw");
FragmentManager fragmentManager=getFragmentManager();
fragmentManager.beginTransaction().add(f,"Fragment").commit();
}
Layout:
<FrameLayout>
<fragment class="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/Fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
Where I am going wrong. I am not able to figure it out. Do I need to extend YoutubeBaseActivity? How to achieve this?
I think you should write the code in official way. Take look at here, and download the zip file(sample applications included in the YouTubeAndroidAPIDemo package) here to get the sample. And take look at FragmentDemoActivity.
Basically, you need to do the Activity which include YoutubePlayerFragment as follows:
public class FragmentDemoActivity extends YouTubeFailureRecoveryActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragments_demo);
YouTubePlayerFragment youTubePlayerFragment =
(YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(DeveloperKey.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo("nCgQDjiotG0");
}
}
#Override
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.youtube_fragment);
}
}
YouTubeFailureRecoveryActivity :
public abstract class YouTubeFailureRecoveryActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DeveloperKey.DEVELOPER_KEY, this);
}
}
protected abstract YouTubePlayer.Provider getYouTubePlayerProvider();
}
And the fragments_demo.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtube_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

how to use YouTubeBaseActivity in Fragment ,android

I useing the tabhost, I hope to use YouTubeBaseActivity in fragment
what can I do?
public class yutubemain extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayerView ytpv;
private YouTubePlayer ytp;
final String serverKey="AIzaSyBrNphq0HsQvQ5Rx4-Kenff-FhumNVMbnY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ytpv = (YouTubePlayerView) findViewById(R.id.youtubeplayer);
ytpv.initialize(serverKey, this);
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1) {
Toast.makeText(this, "Initialization Fail", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasrestored) {
ytp = player;
Intent gt =getIntent();
ytp.loadVideo(gt.getStringExtra("id"));
}
}
this code change in fragment...
Use YouTubePlayerSupportFragment if you are only playing a YouTube video in a single support.v4.app.Fragment rather than YouTubeBaseActivity.

Categories

Resources