How to use android Youtube player to play specific Url? - android

The code is working fine , But i want to play my own url videos not from Youtube and i cant seem to see anywhhere to Parse the Url in the api. help The code is working fine , But i want to play my own url videos not from Youtube and i cant seem to see anywhhere to Parse the Url in the api. help
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;
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 TruitonYouTubeAPIActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "AIzaSyAc4bTnZDThXQUh3aTXnGFol4rWiGp6Cz0";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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) {
// how do i play my video from this place... NOT FROM YOUTUBE eg http://campusvibe.co.nf/clear.mp4
}
}
}

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" />
2.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);
}
}

Inside your '!wasRestored' condition write follwoing code:
yourPlayerObj.loadVideo("videocode");
Hope this helps!!

Related

Android: How to go back to previous screen after playing YouTube video

My app plays a specific YouTube video when a button is clicked.
After watching the video I want the YouTube video player to close and the app to go back to the previous screen instead of displaying more suggested videos.
Here is the code I have, how do I do that?
package com.newapp;
import android.os.Bundle;
import android.widget.Toast;
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 Level_1_Training extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "XXXXXXXXXXXXXXX";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
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) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
if (!wasRestored) {
player.loadVideo(VIDEO_ID);
}
}
}
You can get onVideoEnded() callback.
Youtube API link here https://developers.google.com/youtube/android/player/reference/com/google/android/youtube/player/YouTubePlayer.PlayerStateChangeListener#onVideoEnded()
You can add your logic in implemented method.
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
if (!wasRestored) {
player.loadVideo(VIDEO_ID);
player.setPlayerStateChangeListener(new PlayerStateChangeListener() {
#Override
public void onAdStarted() { }
#Override
public void onError(ErrorReason arg0) { }
#Override
public void onLoaded(String arg0) { }
#Override
public void onLoading() { }
#Override
public void onVideoEnded() {
//your logic ,if the previous activity to be called ,
// you can perform backpress() or intent to call other activity.
// also dont forget to remove player in the
// onStop() method of the youtube activity.
}
#Override
public void onVideoStarted() { }
});
}
}
Useful references
https://developers.google.com/youtube/v3/code_samples/java
https://developers.google.com/youtube/v3/
https://stacktips.com/tutorials/android/youtube-android-player-api-example

YouTube Video Starts to Buffer again on full screen in Android

I have integrated YouTube Video in my Android app. Now the problem is when video is turned into full screen (landscape) mode, it starts to buffer again. How to solve this problem?
Below is the whole code I have used.
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);
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 {
Toast.makeText(this, "Error!", 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(Config.YOUTUBE_VIDEO_CODE);
// Hiding player controls
//player.setPlayerStyle(YouTubePlayer.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(Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}
Step 1: Add the below lines to your AndroidMenifest File:
<uses-permission android:name="android.permission.INTERNET"/>
<activity android:name=".MainActivity" android:configChanges="orientation|keyboardHidden|screenSize|screenLayout|uiMode|screenLayout|keyboard">
Step 2: activity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context=".MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true"/>
</RelativeLayout>
Step 3: Create New Class and Named as "Config" you can name as your wish and class must be as below and this "Config" class for your "YouTubeApi" Key and "Video Id"
public class Config {
public static final String YOUTUBEAPI_KEY = "AIzaSyC5lyioipD0SpJ0UJ5hxz-EDVnO1gZyeI4";
public static final String YOUTUBE_VIDEO_ID = "fhWaJi1Hsfo";
}
MainActivity.java file as below:
package com.example.tulasi.youtube2;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.view.WindowManager;
import android.widget.Toast;
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 implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private boolean mAutoRotation = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAutoRotation = Settings.System.getInt(getContentResolver(),
Settings.System.ACCELEROMETER_ROTATION, 0) == 1;
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube5);
youTubeView.initialize(Config.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if(mAutoRotation) {
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION
| YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI
| YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE
| YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
}else {
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION
| YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI
| YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
}
if (!wasRestored) {
player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
// String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
}
try to add this in your manifest
android:configChanges="orientation|keyboard|keyboardHidden|screenSize|screenLayout|uiMode"
inside oncreate add this
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
and inside anywhere in activity just add
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
Hope this will work
<activity
android:configChanges="keyboardHidden|orientation|screenSize"
android:name="com.example.MainActivity">
Put this in your manifest, referencing your main activity.

Youtube video can't play over 2G or 3G network

I have created an app in which I am playing youtube video using YouTube API. Over wifi, it works fine but when I play using 2g or 3g network it displays error message "An Error occurred, touch to retry."
Here my YouTube API code.
package com.example.userone.asianconnections.Activity;
import android.app.ActionBar;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.Toast;
import com.example.userone.asianconnections.Config;
import com.example.userone.asianconnections.R;
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.YouTubePlayerView;
/**
* Created by userone on 3/14/16.
*/
public class YouTubeVideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
String video_url;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.youtube_video);
youTubeView = (YouTubePlayerView)findViewById(R.id.youtubevideoId);
youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
Intent intent = getIntent();
video_url = intent.getStringExtra("videoLink");
Log.e("link is ", video_url+"");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if(!b){
youTubePlayer.cueVideo(video_url);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if(!youTubeInitializationResult.isUserRecoverableError()){
youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
}else{
String error = String.format(getString(R.string.player_error), youTubeInitializationResult.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RECOVERY_REQUEST){
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected YouTubePlayerView getYouTubePlayerProvider() {
return youTubeView;
}
private void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
#Override
public void onPlaying() {
// Called when playback starts, either due to user action or call to play().
showMessage("Playing");
}
#Override
public void onPaused() {
// Called when playback is paused, either due to user action or call to pause().
showMessage("Paused");
}
#Override
public void onStopped() {
// Called when playback stops for a reason other than being paused.
showMessage("Stopped");
}
#Override
public void onBuffering(boolean b) {
// Called when buffering starts or ends.
}
#Override
public void onSeekTo(int i) {
// Called when a jump in playback position occurs, either
// due to user scrubbing or call to seekRelativeMillis() or seekToMillis()
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
#Override
public void onLoading() {
// Called when the player is loading a video
// At this point, it's not ready to accept commands affecting playback such as play() or pause()
}
#Override
public void onLoaded(String s) {
// Called when a video is done loading.
// Playback methods such as play(), pause() or seekToMillis(int) may be called after this callback.
}
#Override
public void onAdStarted() {
// Called when playback of an advertisement starts.
}
#Override
public void onVideoStarted() {
// Called when playback of the video starts.
}
#Override
public void onVideoEnded() {
// Called when the video reaches its end.
}
#Override
public void onError(YouTubePlayer.ErrorReason errorReason) {
// Called when an error occurs.
}
}
}
and here is my Layout XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="match_parent"
android:layout_height="300dp"
android:id="#+id/youtubevideoId">
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>

SharedPreferences in Non-Activity

Hi I need to get a String from an Activity to another Class. I need the String VideoID in the Test2 class. I wanted to use sharedpreferences, but this does not work. How can i use sharedpreferences here? Or any other idea how i can get the String? Thanks
In my Activity I have this Button:
// Video Button
final Button videobutton = (Button) findViewById(R.id.videobutton);
videobutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Video ID save
SharedPreferences.Editor editor = getSharedPreferences("VideoID_saver", MODE_PRIVATE).edit();
editor.putString("VideoID", current_video);
editor.commit();
Intent OpenTest = new Intent(Questions.this, Test2.class);
startActivity(OpenTest);
}
});
The Test2.class looks like this:
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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.ErrorReason;
import com.google.android.youtube.player.YouTubePlayer.PlaybackEventListener;
import com.google.android.youtube.player.YouTubePlayer.PlayerStateChangeListener;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import com.google.android.youtube.player.YouTubePlayerView;
public class Test2 extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyCb2pCHbqhBDKaYzFvU7g1SBG14YrM3XWE";
//Test
SharedPreferences prefs = getSharedPreferences("VideoID_saver", MODE_PRIVATE);
String testtext = prefs.getString("VideoID", "");
//http://youtu.be/<VIDEO_ID>
public final String VIDEO_ID = testtext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult result) {
Toast.makeText(this, "Failured to Initialize!", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
/** add listeners to YouTubePlayer instance **/
player.setPlayerStateChangeListener(playerStateChangeListener);
player.setPlaybackEventListener(playbackEventListener);
/** Start buffering **/
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {}
#Override
public void onPaused() {}
#Override
public void onPlaying() {}
#Override
public void onSeekTo(int arg0) {}
#Override
public void onStopped() {}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {}
#Override
public void onError(ErrorReason arg0) {}
#Override
public void onLoaded(String arg0) {}
#Override
public void onLoading() {}
#Override
public void onVideoEnded() {}
#Override
public void onVideoStarted() {}
};
You're probably somehow accessing different SharedPreferences instances. It's easier to make sure this doesn't happen using the getDefaultSharedPreferences() method:
In you Activity:
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putString("VideoID", current_video)
.apply();
In your Test2 onCreate method:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String testtext = prefs.getString("VideoID", "");
Couple of things. Test2 is inheriting an activity it seems, so not sure why your title says Non-Activity. SharedPreferences reading and writing seems ok but maybe reading the sharedpreferences even before the constructor on the activity has had change to run is too early.
Your goal is to get a string from button to test2. It seems like it would be better to avoid shared preferences entirely and pass the string to the next activity directly via the put/getExtra function.
Like so:
Intent OpenTest = new Intent(Questions.this, Test2.class);
i.putExtra("VideoID", current_video);
startActivity(OpenTest);
Then extract it from your new activity in your OnCreate method:
//http://youtu.be/<VIDEO_ID>
public final String VIDEO_ID;
#
Override
protected void onCreate(Bundle savedInstanceState) {
//Test
Intent intent = getIntent();
VIDEO_ID = intent.getExtras().getString("VideoID");
}

Android YouTube API access player from onClickListener

I'm following this tutorial to set up a custom YouTube player via YouTube API: http://www.techrepublic.com/blog/android-app-builder/using-googles-youtube-api-in-your-android-apps/
Here's the code for loading a pre-set YouTube video:
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.YouTubePlayerView;
import com.google.android.youtube.player.YouTubePlayer.Provider;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
Now I'm trying to load a different YouTube video by clicking a button. So I setup an onClickListener for my button1 and try to access the YouTube player, but it won't work.
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
static private final String DEVELOPER_KEY = "mykey";
static private final String VIDEO = "Yc8YrVc47TI";
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, this);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
youTubeView.loadVideo("Erd2k6EKxCQ");
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult error) {
Toast.makeText(this, "Oh no! "+error.toString(), Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
player.loadVideo(VIDEO);
}
}
How do I load a specific video from button1's onClickListener to the YouTubePlayer player.component?
public class Community extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener,View.OnClickListener{
final static String youtube_key = " you key ";
YouTubePlayerView youTubePlayerView;
YouTubePlayer.OnInitializedListener onInitializedListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_community);
youTubePlayerView = (YouTubePlayerView) findViewById(R.id.home_community_youtubeview);
youTubePlayerView.initialize(youtube_key,this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("vk1Rk5AaDO4");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
public void onClick(View view) {
}
}
You need to create a new activity to extend the YouTubePlayerView Context. This is what my activity looks like, but you need to create an intent from main to call it. IE this is a different class than main.
public class Beat extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener, OnClickListener{
static private final String DEVELOPER_KEY = "your key here";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beat);
// changes to xml file named beat
// initializes the video
YouTubePlayerView yt2 = (YouTubePlayerView)findViewById(R.id.youtube_view2);
yt2.initialize(DEVELOPER_KEY, this);
setupActionBar();
}
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
player.loadVideo(Main.VIDEO[0]);
}

Categories

Resources