I stumble upon issue playing more than 1 video using youtube API.
I found this article: Playing different youtube videos using Youtube Player API
Problem:
I cant find how it solved by keep more than 1 player on same page.
I'm trying to init 2 player with 2 different video code, but when i
tried to play 1 video, both run, then after 1 second, both stopped.
How can i fix it? Can anyone guide me?
Here's my code:
public class YoutubeTvFragment extends Fragment {
private static final String LOG = "Youtube TV";
private FragmentActivity myContext;
private YouTubePlayer YPlayer, YPlayer2;
private static final String YoutubeDeveloperKey = "";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
public void onAttach(Activity activity) {
if (activity instanceof FragmentActivity) {
myContext = (FragmentActivity) activity;
}
super.onAttach(activity);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
// Defines the xml file for the fragment
View rootView = inflater.inflate(R.layout.fragment_tv_youtube, container, false);
YouTubePlayerSupportFragment youTubePlayerSupportFragment = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.youtube_fragment, youTubePlayerSupportFragment).commit();
youTubePlayerSupportFragment.initialize(YoutubeDeveloperKey, new OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
YPlayer = youTubePlayer;
YPlayer.cueVideo("eCdXcZeKgxU");
//YPlayer.setShowFullscreenButton(false);
//YPlayer.pause();
//YPlayer.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
YouTubePlayerSupportFragment youTubePlayerSupportFragment2 = YouTubePlayerSupportFragment.newInstance();
FragmentTransaction transaction2 = getChildFragmentManager().beginTransaction();
transaction2.add(R.id.youtube_fragment2, youTubePlayerSupportFragment2).commit();
youTubePlayerSupportFragment2.initialize(YoutubeDeveloperKey, new OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider arg0, YouTubePlayer youTubePlayer, boolean c) {
if (!c) {
YPlayer2 = youTubePlayer;
YPlayer2.cueVideo("jgnGD74BKoA");
//YPlayer2.setShowFullscreenButton(false);
//YPlayer2.pause();
//YPlayer2.play();
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider arg0, YouTubeInitializationResult arg1) {
// TODO Auto-generated method stub
}
});
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Related
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();
I am implementing Cwac-camera for video recording within my application. I am trying to figure out how can I setup my Video Preview Fragment which will playback the Video Recorded within the fragment with replay in infinite until the user has accepted or rejected the video preview.
This is my Activity where it calls for the video fragment.
#Override
public void onVideoRecorded(File video) {
videoPreviewFragment = VideoPreviewFragment.newInstance(video);
getSupportFragmentManager().beginTransaction().replace(R.id.sc_camera_container, picturePreviewFragment).commit();
}
And the VideoPreviewFragment I am using File to instead of URi
public class VideoPreviewFragment extends Fragment implements MediaPlayer.OnCompletionListener {
private static final String EXTRA_VIDEO_LOCATION = "extra_video_location";
public static VideoPreviewFragment newInstance(File video) {
VideoPreviewFragment fragment = new VideoPreviewFragment();
Bundle args = new Bundle(1);
args.putString(EXTRA_VIDEO_LOCATION, video.toString());
fragment.setArguments(args);
return fragment;
}
private VideoView videoView;
private File video;
private ImageButton btnAccept;
private ImageButton btnReject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sc_video_preview, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoView = (VideoView) view.findViewById(R.id.sc_video);
btnAccept = (ImageButton) view.findViewById(R.id.sc_btn_accept);
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCameraActivity().onAccept(video);
}
});
btnReject = (ImageButton) view.findViewById(R.id.sc_btn_reject);
btnReject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCameraActivity().onReject(video);
}
});
video = new File(getArguments().getString(EXTRA_VIDEO_LOCATION));
}
public SimpleCameraActivity getCameraActivity() {
return (SimpleCameraActivity) getActivity();
}
#Override
public void onSuccess() {
btnAccept.setEnabled(true);
btnReject.setEnabled(true);
}
#Override
public void onError() {
btnAccept.setEnabled(false);
btnReject.setEnabled(false);
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.e("VIDEO PLAY", "END VIDEO PLAY");
}
}
So I've been trying to put a YouTube playlist into my app for days now, and I can't seem to figure it out. I have been following this tutorial, but the problem is my app is in fragments because of the tab view, like this:
public class FragmentTab2 extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
View view = inflater.inflate(R.layout.fragmenttab2, container, false);
}
}
How would I do to have the code below, provided by the tutorial, to work on my fragment?
public class TruitonYouTubeAPIActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "AIzaSyDhEeq_FYAdCzMMSigmMcRwF_nQEhUXS-0";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_you_tube_api);
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) {
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.
*/
if (!wasRestored) {
YPlayer.cueVideo("2zNSgSzhBfM");
}
}
}
Thanks in advance.
I have problem with "YouTubePlayerSupportFragment"
I get error here :
`YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.youtubeplayerview);`
Here is the full code:
I tried to change a few things, and now I have a little more understandable error.
If I find it I will post solcuón.
Update Code 11/06/2015, and I get new Error :
5429-5429/com.onpocket.activamutua E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.google.android.youtube.player.YouTubePlayerSupportFragment.onStart(Unknown Source)
Code :
public class Activity_demo extends YouTubePlayerSupportFragment /*implements YouTubePlayer.OnInitializedListener */{
private static final int RECOVERY_DIALOG_REQUEST = 10;
public static final String API_KEY = "AIzaSyBHZjt1vrkjuwCp4YqTsADNQVDf6KvAXr0";
private String VIDEO_ID = "c_eHTMhEsHU";
JustifiedTextView tv1;
ConfigActiva cfg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_own, container, false);
TypefaceUtil.overrideFont(getActivity(), "SERIF", ConfigActiva.nameFontStatic);
ConfigActiva.languageCustom(ConfigActiva.defaultLanguageForce, getActivity());
init(rootView);
return rootView;
}
public void init(View vRoot){
//YouTubePlayerView youTubeView = (YouTubePlayerView) getActivity().findViewById(R.id.youtubeplayerview);
//youTubeView.initialize(API_KEY, this);
YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getChildFragmentManager().findFragmentById(R.id.youtubeplayerview);
//YouTubePlayerSupportFragment youTubePlayerFragment = (YouTubePlayerSupportFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.youtubeplayerview);
//youTubePlayerFragment.initialize(API_KEY, this);
youTubePlayerFragment.initialize(API_KEY, new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.cueVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format("YouTube Error (%1$s)", errorReason.toString());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
}
});
}
/* #Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format("YouTube Error (%1$s)",errorReason.toString());
Toast.makeText(getActivity(), errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}*/
My XML
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
With this line Works, but not load video : updated 11/06/2015 22:21
YouTubePlayerSupportFragment youTubePlayerFragment = YouTubePlayerSupportFragment.newInstance();
You have to add your fragment dynamically because: Nested fragments
Just add some container with id and use this id in Transaction.replace. Also use onCreateView only for inflating and building layout. After that find for views in onViewCreated(View view, ...) from view param, it will make code cleaner.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Please help me,
I want when user click item in listview -> Reload activity with video clicked (Like youtube app android)
Pleale help me the idea. Thanks
You can view here
Update my source code:
public class YoutubePlayerActivity extends AppCompatActivity
implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
private Toolbar mToolbar;
private String name;
private String countView;
private String youtubeId = "fhWaJi1Hsfo";
private String cate;
private RecyclerView mRecyclerView;
private LinearLayoutManager mLayoutManager;
private ClipAdapter mClipAdapter;
private List<ClipItemData> clipItemDatas = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube_player);
mRecyclerView = (RecyclerView) findViewById(R.id.youtube_recycler_view);
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
final LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
for (int i = 0; i < 50; i++) {
ClipItemData clipItemData = new ClipItemData("To0tJu75ugg",
"Test",
"123",
"XE",
"http://img.youtube.com/vi/" + "To0tJu75ugg" + "/0.jpg");
clipItemDatas.add(clipItemData);
}
// specify an adapter (see also next example)
mClipAdapter = new ClipAdapter(this, clipItemDatas);
mRecyclerView.setAdapter(mClipAdapter);
Bundle getBundle = null;
getBundle = this.getIntent().getExtras();
youtubeId = getBundle.getString("id");
name = getBundle.getString("name");
countView = getBundle.getString("count_view");
cate = getBundle.getString("cate");
myYouTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(AppConfig.YOUTUBE_ANDROID_KEY, this);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this, mRecyclerView, new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
youtubeId = "To0tJu75ugg";
Toast.makeText(getApplicationContext(), youtubeId, Toast.LENGTH_SHORT).show();
}
#Override
public void onItemLongClick(View view, int position) {
}
}));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
super.onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
youTubePlayer.loadVideo(youtubeId);
}
}
#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 (%1$s)",
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(AppConfig.YOUTUBE_ANDROID_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtubeplayerfragment);
}
}
This can be done in different ways.
You can use a simple WebView to load those videos.
You can also use the official "YouTube Android Player API"
YouTube Android Player API
Implementing Youtube's API is easy,
First create a YouTubePlayerViewin your xml,
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Then show a video like this,
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "YOUR_API_KEY";
public static final String VIDEO_ID = "YOUR_VIDEO_ID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
}