I am using YouTubePlayerView to load the video.The video plays successfully, but when the screen is rotated, the it stops playing.How do I overcome this problem?It may be a simple thing.I googled but didn't get help but your help is needed...
Below is my code.
Code:
youTubePlayerView=findViewById(R.id.youtube_view);
onInitializedListener=new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayers=youTubePlayer;
youTubePlayers.loadVideo("9ZaEPeaucIU");
youTubePlayers.setFullscreenControlFlags(FULLSCREEN_FLAG_CONTROL_ORIENTATION);
youTubePlayers.setOnFullscreenListener(onFullscreenListener);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
onFullscreenListener=new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
if (b){
time=youTubePlayers.getCurrentTimeMillis();
}
}
};
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
youTubePlayerView.initialize("AI&*$^$^$3634HxbhVM##$%%^%&%$",onInitializedListener);
}
});
Layout:
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="250dp"
android:id="#+id/youtube_view"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent">
</com.google.android.youtube.player.YouTubePlayerView>
Add this on your activity declaration in AndroidManifext.xml so that, the activtiy doesn't recreate on orientation change.
<activity
android:name=".NameOfYourActivitiy"
android:configChanges="orientation|screenSize">
</activity>
Added the configChanges in the AndroidManifest file and it worked.
Eg
<activity android:label=Activity Name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:name="com.example.blahblah">
Related
I am trying to initialize youtubeplayer fragment within a fragment. I successfully implemented the fragment within an activity but getting problem to initialize it in a fragment.
the code snippet for activity is as below
public class MainActivity extends AppCompatActivity {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
//print or show error if initialization failed
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
To convert this code into fragment, I tried this
public class Welcome extends Fragment {
private YouTubePlayerSupportFragmentX youTubePlayerFragment;
private YouTubePlayer youTubePlayer;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_welcome, container, false);
initializeYoutubePlayer();
private void initializeYoutubePlayer() {
youTubePlayerFragment = (YouTubePlayerSupportFragmentX) getSupportFragmentManager().findFragmentById(R.id.youtube_player_fragment);
if (youTubePlayerFragment == null)
return;
youTubePlayerFragment.initialize(Constants.DEVELOPER_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer = player;
//set the player style default
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
//cue the 1st video by default
youTubePlayer.cueVideo(youtubeVideoArrayList.get(0));
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.e(TAG, "Youtube Player View initialization failed");
}
});
}
private void getSupportFragmentManager() {
}
}
but getting error in finding the fragment layout. Can somebody guide me how to do this in fragment? The layout for Welcome fragment is as follows
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FCFDFF"
tools:context="com.currentmedia.channelslayout.Welcome">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="32dp"
android:layout_alignParentTop="true"
android:layout_marginTop="0dp"
android:background="#FF0000"
app:title="Punjabi News Live"
app:titleTextColor="#FFFFFF" />
<!-- Youtube Player Fragment -->
<LinearLayout
android:id="#+id/linearlayout01"
android:layout_width="fill_parent"
android:layout_height="220dp"
android:layout_below="#id/adView"
android:layout_marginTop="2dp"
android:background="#ccc"
android:orientation="vertical">
<fragment
android:id="#+id/youtube_player_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragmentX"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
In your layout, instead of using a < fragment > you should use a < FragmentContainerView > and replace the fragment in your activity using transaction.
Here is a tutorial if you're new with manipulating fragment in 2020:
FragmentContainerView explanation
I play video in MainActivityand video is playig fine. While playing video, if I open the same activity another time and come back to previous MainActivity youtube progressbar keeps turning and nothing happens. I read the documentation and couldn't find anything related this problem. Indeed, the documentation is very old (updated in 2015), and YouTubeAndroidPlayerApi library was updated in 2017. Guide me to right direction.
MainActivity.java
public class MainActivity extends YouTubeBaseActivity
implements YouTubePlayer.OnInitializedListener {
private String YOUTUBE_API_KEY = "api_key";
private YouTubePlayerView youtubePlayerView;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
youtubePlayerView = findViewById(R.id.youtubePlayer);
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Log.w("youtube_activity", "onInitialization success");
youTubePlayer.loadVideo("0KSOMA3QBU0");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(this, "Initialization failure", Toast.LENGTH_SHORT);
}
public void onClick(View view) {
startActivity(new Intent(this, MainActivity.class));
}
}
layout xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubePlayer"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="onClick"
android:text="Button" />
</LinearLayout>
Found solution with releasing YouTubePlayer when going to another youtubeplayeractivity. When came back to previous youtubeplayeractivity reninitialized YouTubePlayerView.
public void onClick(View view) {
youTubePlayer.release();
startActivity(new Intent(this, MainActivity.class));
}
#Override
protected void onRestart() {
super.onRestart();
youtubePlayerView.initialize(YOUTUBE_API_KEY, this);
}
I using youtube api and playing youtube video using below tag in xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.aspire.urdu.toddlers.poems.VideoListingActivity">
<include
android:id="#+id/toolbar"
layout="#layout/action_bar" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:hardwareAccelerated="true" />
</LinearLayout>
and i am using this code in activity.
public class VideoPlayerActivity extends YouTubeBaseActivity{
YouTubePlayer YTplayer;
YouTubePlayerView youTubePlayerView;
private String videoLink = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
videoLink = getIntent().getStringExtra("link");
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(getResources().getString(R.string.you_tube_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
YTplayer = youTubePlayer;
YTplayer.setShowFullscreenButton(false);
YTplayer.loadVideo(videoLink);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getApplicationContext(), ""+youTubeInitializationResult.name(), Toast.LENGTH_LONG).show();
}
});
}
}
but when video is playing it is showing on full screen..
What i need
i just need to display action with back button enabled Thanks.
Am new in android development.Am trying to implement youtube Api. But in my XML file it show error "could not be instantiated:
- com.google.android.youtube.player.YouTubePlayerView"
Here is My MAinActivity Code:-
public class MainActivity extends YouTubeBaseActivity {
Button b;
private YouTubePlayerView youtubeplayerview;
private YouTubePlayer.OnInitializedListener onInitializedListener;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_main);
youtubeplayerview=(YouTubePlayerView)findViewById(R.id.Youtube_view);
onInitializedListener=new YouTubePlayer.OnInitializedListener(){
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("wvjqFy33HVA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
b=(Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
youtubeplayerview.initialize("API KEY",onInitializedListener);
}
});
}
}
Here is my XML file Code:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY VEDIO"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="#+id/Youtube_view"
android:layout_alignParentTop="true"
android:layout_above="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Here is Error Screenshot
Did you add YouTube Android Player API to your library? Adding that fixed the issue for me..Try adding the same by following the steps given below :
1.Download YouTube Android Player API jar file from https://developers.google.com/youtube/android/player/downloads/
2.Extract the zip file, go to libs -> YouTubeAndroidPlayerApi.jar and copy it
3.Paste the jar file to /app/libs/ directory in android studio
Finally add compile files('libs/YouTubeAndroidPlayerApi.jar') to your app level build.gradle file
Sync,build and check if it works fine
Did you generate api key for android youtube player?
Link: https://console.developers.google.com
If yes, you must to change "API KEY " in this youtubeplayerview.initialize("API KEY",onInitializedListener); by your api key that you generated before.
Anyway, you can try to replace you class by this class with YoutubeDeveloperKey is the key you generated :
public class ActivityPlayYouTube extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "YOUR_DEVELOPER_KEY_GOES_HERE";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playyoutube);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(YoutubeDeveloperKey, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.you_tube_api, menu);
return true;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
"There was an error initializing the YouTubePlayer",
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(YoutubeDeveloperKey, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public void onInitializationSuccess(Provider provider,
YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
YPlayer = player;
/*
* Now that this variable YPlayer is global you can access it
* throughout the activity, and perform all the player actions like
* play, pause and seeking to a position by code.
*/
YPlayer.cueVideo("2zNSgSzhBfM");
}
}
}
I'm using the Youtube Android Player API as outlined here: https://developers.google.com/youtube/android/player/
However, I can't get more than one video into my activity at once. I tried simply putting two YouTubePlayerViews into the activity like so:
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/view_two"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
MainActivity.java
package com.example.multidemo;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeBaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((YouTubePlayerView) findViewById(R.id.view_one)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("RpwoN_XlN6Y");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
((YouTubePlayerView) findViewById(R.id.view_two)).initialize("API key", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(Provider arg0, YouTubePlayer arg1, boolean arg2) {
arg1.cueVideo("jkk2mMq2x8E");
}
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) {
}
});
}
}
When I try this, the first view just comes up black, while the second video loads. If I comment out the code in onCreate() for the second video, then just the first video will load.
Is there any way to get multiple YouTubePlayerViews into the same activity?
This might be too late for an answer, but i had the same issue recently. Hope this helps to someone who might face the same issue. The trick to get around this is Using YoutubePlayerFragments instead. As long as you use Youtube player view, you'll hit the limit imposed of only one initialization done out of multiple requests. Typically the initialization succeeds for last one.
I ended up dynamically generating gridlayout and placing my (dynamically generated)fragment's view in each of the cells. And then i initialize the instance of player inside onResume. Once initialization is sucessful, you'll get a handle to player, and you can cue different videos randomly on fragments.
I'll just paste the code that will give you an idea about how i am constructing fragments and doing initialization:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mLogger.i("Preparing Youtube view for fragment ..");
mFragmentHeight = CustomFragment.getFragmentHeight(mNumScreens,mNumColumns);
mFragmentWidth = CustomFragment.getFragmentWidth(mNumColumns);
LinearLayout linearLayout = new LinearLayout(getActivity());
GridLayout.LayoutParams gridparams = new GridLayout.LayoutParams();
gridparams.rowSpec = GridLayout.spec(mGridRow);
gridparams.columnSpec = GridLayout.spec(mGridColumn);
gridparams.height = mFragmentHeight;
gridparams.width = mFragmentWidth;
linearLayout.setLayoutParams(gridparams);
if(YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(getActivity())==
YouTubeInitializationResult.SUCCESS)
{
View ytView = super.onCreateView(inflater, container, savedInstanceState);
linearLayout.addView(ytView);
}
else
mLogger.e("Either youtube service is down," +
" or you dont have required version of YouTube app .." +
"\nYouTube Fragment will not work as expected..");
mView = linearLayout;
mLogger.i("Preparation youtube view for fragment complete..");
return mView;
}
#Override
public void onInitializationFailure(Provider arg0,
YouTubeInitializationResult arg1)
{
mLogger.e("Youtube player initialization failed");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player,
boolean wasRestored)
{
mLogger.i("You tube player initialized successfully.. will attempt to stream..");
mYoutubePlayer = player;
setListeners();
try
{
if (!wasRestored)
{
if(mPlayListFragment)
player.loadPlaylist(getResourceID());
else
player.loadVideo(getResourceID());
}
}
catch(Exception e)
{
mLogger.e("Error loading playlist/video .."+e);
}
}
public void onResume()
{
super.onResume();
initialize(API_KEY, this);
}