Trying to add a youtube video to a ListItem - android

I am creating a listview in Android. When I click on the item in the listview, it goes to second activity with the Youtubeplayer. But instead of playing the video, a message appears inside the Youtube player saying
An error occurred while initializing the youtube player
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final String[] sublectures = {"Part 1", "Part 2"};
ListAdapter appadapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, sublectures);
ListView list2 = findViewById(R.id.list2);
list2.setAdapter(appadapter1);
list2.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String lecture = String.valueOf(parent.getItemAtPosition(position));
Intent startintent = new Intent(getApplicationContext(),Main3Activity.class);
startActivity(startintent);
}
});
}}
This is Main3Activity
public class Main3Activity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyBdVOqvu3C-MTnmO0iNOgeKBCSmb9ULrXc";
public static final String VIDEO_ID = "W2TYS_Jvzjc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
YouTubePlayerView youTubePlayerView = findViewById(R.id.youtubePlayerView);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure (YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult){
Toast.makeText(this, "Fail to Load", Toast.LENGTH_LONG).show();
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
player.cueVideo(VIDEO_ID);
}
}
}

Try out this code works for me
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;
public class VideoActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
YouTubePlayerView youTubePlayerView;
String API_KEY="AIzaSyB2TtG6UjEtDWfzxHvQCf2DJxkUPfJI1Lc";
private static final int RECOVERY_REQUEST = 1;
String TAG="VideoActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video);
youTubePlayerView=(YouTubePlayerView)findViewById(R.id.youtube);
youTubePlayerView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Bundle bundle = getIntent().getExtras();
String showVideo = bundle.getString("videoId");
youTubePlayer.cueVideo(showVideo);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
Toast.makeText(this, "Error Intializing Youtube Player", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
getYouTubePlayerProvider().initialize(API_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return youTubePlayerView;
}
}

Related

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>

YouTube API Playlists in Fragments?

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.

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.

Reload youtubeplayer in activity? [closed]

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);
}
}
}

How to use YouTubePlayer api in fragments?

I am using youtube player api in my application,I have used the following code
xml:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel1"
android:background="#edeae5">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</RelativeLayout>
my Activity:
public class EditBloop extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_bloop);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
}
But here I am using YouTubeBaseActivity,but in my application I want youTubePlayer in a Fragment.
How can I achieve this? I have seen some of the links using YouTubePlayerSupportfragment but I didnt understand them.
Please suggest.
You can do as below
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "key";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
if (result.isUserRecoverableError()) {
result.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,
"YouTubePlayer.onInitializationFailure(): " + result.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
youTubePlayer = player;
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationSuccess()",
Toast.LENGTH_LONG).show();
youTubePlayer.setPlayerStateChangeListener(myPlayerStateChangeListener);
youTubePlayer.setPlaybackEventListener(myPlaybackEventListener);
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
private final class MyPlayerStateChangeListener implements PlayerStateChangeListener {
private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onAdStarted() {
updateLog("onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}
#Override
public void onLoading() {
updateLog("onLoading()");
}
#Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}
#Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements PlaybackEventListener {
private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
updateLog("onPaused()");
}
#Override
public void onPlaying() {
updateLog("onPlaying()");
}
#Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}
#Override
public void onStopped() {
updateLog("onStopped()");
}
}
}
The xml
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="3"/>

Categories

Resources