CardView is not showing Youtube Thumbnail view in Android - android

I have used the Youtube API in my application along with FirebaseRecyclerAdapter and RecyclerView and for some reasons my YouTube Thumbnail is not being shown in my application although I have added it in my CardView and my FirebaseRecyclerAdapter has code to access the CardView but when I start my application and go to that activity no thumbnail is shown over there. I have implemented it as hard coded without Firebase Adapter.
Steps I have tried:
Added layout manager
Adjusting the height and width of cardView and thumbnailView
I am using Android Studio
YouTube class file:
public class YoutubeVideos extends YouTubeBaseActivity {
private RecyclerView YouRecycler;
private DatabaseReference YDatabaseReference;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youtubed");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> YfirebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder>(
post2youtube.class,
R.layout.youtube_videos_card,
YoutubeViewHolder.class,
YDatabaseReference
) {
#Override
protected void populateViewHolder(YoutubeViewHolder viewHolder, post2youtube model, int position) {
viewHolder.setYoutube(model.getYoutube());
}
};
YouRecycler.setAdapter(YfirebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerView.ViewHolder {
View yView;
public YoutubeViewHolder(View YitemView) {
super(YitemView);
yView = YitemView;
}
public void setYoutube(final String youtube){
final YouTubePlayerView youPlay = (YouTubePlayerView) yView.findViewById(R.id.youtuber);
youPlay.initialize("Some key",
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo(youtube);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
}
}
YouTube RecyclerView 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">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id ="#+id/Youtube_recycler"/>
</LinearLayout>
YouTube cardView xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_cardView"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</android.support.v7.widget.CardView>

YoutubePlayer view is too large to be added to a recyclerview.So use a YouTubeThumbnailView instead to display the thumbnails. When the user clicks on one of them, you can start a YouTubePlayerFragment or an activity with a YouTubeplayerView view.
below is the reference code,
in xml :
<com.google.android.youtube.player.YouTubeThumbnailView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginBottom="#dimen/ten_dp"
android:visibility="gone"/>
in java :
// Initializing video player with developer key
youtube_view.initialize(Config.DEVELOPER_KEY, new YouTubeThumbnailView.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, final YouTubeThumbnailLoader youTubeThumbnailLoader) {
youTubeThumbnailLoader.setVideo(videoId);
youTubeThumbnailLoader.setOnThumbnailLoadedListener(new YouTubeThumbnailLoader.OnThumbnailLoadedListener() {
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
youTubeThumbnailLoader.release();
Toast.makeText(getActivity(), "It's a valid youtube url.", Toast.LENGTH_SHORT).show();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
try {
Toast.makeText(getActivity(), "Not a valid youtube url.", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
});

Related

html5 video not work in android native webview

I have the following link
http://stage.diabetesmasterclass.org/Upload/myclinic/SAM/visit1/sam_storyline_output/story_html5.html
it contains an html5 video and I have tried to load it inside a webview in my android app
it keep loading and never run, I tried to enable javascript and to add a lot of configuration but did not work also
I even tried to use AdvancedWebView sdk to render it, and in this case it loads but did not run anything
can anyone help please ?
You can load page using below code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
protected AgentWeb mAgentWeb;
private LinearLayout mLinearLayout;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
mLinearLayout = findViewById(R.id.web_content);
mAgentWeb = AgentWeb.with(this)
.setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))
.closeIndicator()
.setWebChromeClient(mWebChromeClient)
.setWebViewClient(mWebViewClient)
.setMainFrameErrorView(R.layout.agentweb_error_page, -1)
.setAgentWebWebSettings(getAgentWebSettings())
.setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
.setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)
//.interceptUnkownUrl()
.createAgentWeb()
.ready()
.go("http://stage.diabetesmasterclass.org/Upload/myclinic/SAM/visit1/sam_storyline_output/story_html5.html");
}
private WebChromeClient mWebChromeClient = new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
}
};
private WebViewClient mWebViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.i("Info", "BaseWebActivity onPageStarted");
}
};
public #Nullable
IAgentWebSettings getAgentWebSettings() {
return AgentWebSettingsImpl.getInstance();
}
#Override
protected void onPause() {
mAgentWeb.getWebLifeCycle().onPause();
super.onPause();
}
#Override
protected void onResume() {
mAgentWeb.getWebLifeCycle().onResume();
super.onResume();
}
#Override
protected void onDestroy() {
super.onDestroy();
mAgentWeb.getWebLifeCycle().onDestroy();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == 2) {
mAgentWeb.getIEventHandler().back();
}
}
}
activity_main.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"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Top"
android:textSize="22dp" />
</LinearLayout>
<LinearLayout
android:id="#+id/web_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:orientation="horizontal"></LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Bottom"
android:textSize="22dp" />
</LinearLayout>
</LinearLayout>
using this Webview
update Output look like this

How to autoplay video through YouTube Player

I am developing an app in which I have shown YouTube videos thumbnails in RecyclerView and there is YouTube Player fragment on top which plays the user selected video. I succeed in doing so. but the problem is that I want to auto play the user selected video.
below is my code:
main_activity.xml:
<RelativeLayout 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"
android:weightSum="2"
android:orientation="vertical"
tools:context="com.example.pc.fkidshell.Main2Activity">
<fragment
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/VideoFragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_below="#+id/my_thirdtoolbar"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/VideoList"
android:layout_below="#+id/VideoFragment"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
secvideo_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/thumbnailView"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
Main_Activity.java:
public class Main2Activity extends AppCompatActivity implements YouTubeThumbnailView.OnInitializedListener, YouTubeThumbnailLoader.OnThumbnailLoadedListener, YouTubePlayer.OnInitializedListener {
YouTubePlayerFragment playerFragment;
YouTubePlayer Player;
YouTubeThumbnailView thumbnailView;
YouTubeThumbnailLoader thumbnailLoader;
RecyclerView VideoList;
RecyclerView.Adapter adapter;
List<Drawable> thumbnailViews;
List<String> VideoId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
thumbnailViews = new ArrayList<>();
VideoList = (RecyclerView) findViewById(R.id.VideoList);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
VideoList.setLayoutManager(layoutManager);
adapter = new Main2Activity.VideoListAdapter();
VideoList.setAdapter(adapter);
VideoId = new ArrayList<>();
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize("AIzaSyAXlMCst9tNrTGz4xAZ0mY6mJlkNU-3DAs", this);
playerFragment = (YouTubePlayerFragment) getFragmentManager().findFragmentById(R.id.VideoFragment);
playerFragment.initialize("AIzaSyAXlMCst9tNrTGz4xAZ0mY6mJlkNU-3DAs", this);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
thumbnailLoader = youTubeThumbnailLoader;
youTubeThumbnailLoader.setOnThumbnailLoadedListener(Main2Activity.this);
thumbnailLoader.setPlaylist("PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40");
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
public void add() {
adapter.notifyDataSetChanged();
if (thumbnailLoader.hasNext())
thumbnailLoader.next();
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
thumbnailViews.add(youTubeThumbnailView.getDrawable());
VideoId.add(s);
add();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Player = youTubePlayer;
Player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
VideoList.setVisibility(b ? View.GONE : View.VISIBLE);
}
});
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.MyView> {
public class MyView extends RecyclerView.ViewHolder {
ImageView imageView;
public MyView(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.thumbnailView);
}
}
#Override
public VideoListAdapter.MyView onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.secvideo_row, parent, false);
return new MyView(itemView);
}
#Override
public void onBindViewHolder(VideoListAdapter.MyView holder, final int position) {
holder.imageView.setImageDrawable(thumbnailViews.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Player.loadVideo(VideoId.get(position));
//Player.loadVideo(VideoId.get(position));
}
});
}
#Override
public int getItemCount() {
return thumbnailViews.size();
}
}
}
When the Youtube player is initialized, set a player state change listener so that you can play the video when the video is loaded and make sure your activity implements player state callbacks.
Detailed code :
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
Player = youTubePlayer;
Player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
VideoList.setVisibility(b ? View.GONE : View.VISIBLE);
}
});
Player.setPlayerStateChangeListener(this); //set player state change listener
}
#Override
public void onAdStarted() {
}
#Override
public void onLoaded(String videoId) {
if(!TextUtils.isEmpty(videoId) && Player != null)
Player.play(); //auto play
}
#Override
public void onLoading() {
}
#Override
public void onVideoEnded() {
}
#Override
public void onVideoStarted() {
}
#Override
public void onError(ErrorReason reason) {
Log.e("onError", "onError : " + reason.name());
}
i hade the same problem, i use YouTubePlayerFragment though and this is what i did.
public async void PlayVideo(params string[] videoId)
{
if (YoutubePlayer != null && videoId != null && videoId.Length > 0)
{
YoutubePlayer.CueVideos(videoId);
await Task.Delay(TimeSpan.FromSeconds(5)); // whait untill the files load.
YoutubePlayer.Play();
}
}
and the player get assigned here
public void OnInitializationSuccess(IYouTubePlayerProvider provider, IYouTubePlayer player, bool wasRestored)
{
if (!wasRestored)
{
YoutubePlayer = player;
PlayVideo(elemnt.VideoSource.ToArray());
}
}

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>

Video is playing for a millisecond implemented using youtubeplayer view

I am trying to implement to play youtube video in my app using youtubeplayer view when user clicks on button but its just playing for a millisecond,after that it just stop.App is not crashing but video is also not playing.
Code for the same is-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "xxxx";
String videoId;
String url="http://www.youtube.com/xxx";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** attaching layout xml **/
setContentView(R.layout.activity_video_view);
/** Initializing YouTube player view **/
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.initialize(API_KEY, this);
videoId=getYoutubeVideoId(url);
Log.e("id",videoId);
//videoId=getIntent().getExtras().getString("url");
}
#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(videoId);
}
}
private PlaybackEventListener playbackEventListener = new PlaybackEventListener() {
#Override
public void onBuffering(boolean arg0) {
Log.e("on","buffer");
}
#Override
public void onPaused() {
Log.e("on","pause");
}
#Override
public void onPlaying() {
Log.e("on","play");
}
#Override
public void onSeekTo(int arg0) {
Log.e("on","seekto");
}
#Override
public void onStopped() {
Log.e("on","stop");
}
};
private PlayerStateChangeListener playerStateChangeListener = new PlayerStateChangeListener() {
#Override
public void onAdStarted() {
Log.e("on","ad");
}
#Override
public void onLoaded(String arg0) {
Log.e("on","loaded");
}
#Override
public void onLoading() {
Log.e("on","loading");
}
#Override
public void onVideoEnded() {
Log.e("on","vidEnd");
}
#Override
public void onVideoStarted() {
Log.e("on","vidStart");
}
#Override
public void onError(ErrorReason arg0) {
// TODO Auto-generated method stub
}
};
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
xml file-
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.youtube.player.YouTubePlayerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:padding="5dp" />
warning in logcat-
W/YouTubeAndroidPlayerAPI(8722): YouTube video playback stopped due to unauthorized overlay on top of player. The YouTubePlayerView is not contained inside its ancestor com.google.android.youtube.player.YouTubePlayerView{41c88550 V.E..... ........ 0,0-480,270 #7f05003d app:id/youtube_player}. The distances between the ancestor's edges and that of the YouTubePlayerView is: left: -8, top: -8, right: -8, bottom: -8 (these should all be positive).
This issue is solved by using youtubeplayer fragment rather than youtubeplayer view.Code for the same is-
xml-
<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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
java file-
public class PlayVideo extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String DEVELOPER_KEY = "your api key";
private static final int RECOVERY_DIALOG_REQUEST = 1;
String url="your video url";
String VIDEO_ID;
YouTubePlayerFragment myYouTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_view);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
VIDEO_ID=getYoutubeVideoId(url);
}
#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
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
#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);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
public static String getYoutubeVideoId(String youtubeUrl)
{
String video_id="";
if (youtubeUrl != null && youtubeUrl.trim().length() > 0 && youtubeUrl.startsWith("http"))
{
String expression = "^.*((youtu.be"+ "\\/)" + "|(v\\/)|(\\/u\\/w\\/)|(embed\\/)|(watch\\?))\\??v?=?([^#\\&\\?]*).*"; // var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
CharSequence input = youtubeUrl;
Pattern pattern = Pattern.compile(expression,Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(input);
if (matcher.matches())
{
String groupIndex1 = matcher.group(7);
if(groupIndex1!=null && groupIndex1.length()==11)
video_id = groupIndex1;
}
}
return video_id;
}
}
Add internet permission in your manifest file.

trouble with running YoutubeAndroidAPIDemo app

I checked stackoverflow for similiar problems and didn't found anything.
so here's my problem, I'm building an android app and I need to use YouTube API.
I followed this guide:
https://developers.google.com/youtube/android/player/
but I can't seem to run the Demo App.
the entire project is full of errors and I can't understand why,
all of the "R.id.blabla" items are having an error saying:
"blabla cannot be resolved or is not a field"
I checked those Questions - Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties
and : YouTubeAndroidAPIDemo does not run
tried everything there, didn't helped much.
I'm pretty sure I am missing something but I have no idea what.
anyone else encountered something like this before?
plz help :D
Try this:
layoutfile.xml
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_player"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/teacherName"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp"
android:background="#fff"
android:padding="5dp" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/date"
android:layout_centerHorizontal="true"
android:layout_marginTop="115dp"
android:visibility="gone"
/>
<TextView
android:id="#+id/progressBarText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progressBar1"
android:layout_centerHorizontal="true"
android:maxLines="3"
android:visibility="gone"
android:text="Video Loading..." />
TutorialVideoView.java
public class TutorialVideoView extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener
{
private VideoView videoView;
private MediaController mController;
private Uri uriYouTube;
ProgressBar progressBar1;
TextView progressBarText;
String v_title,v_date,v_id,v_url,v_teacher;
public static final String API_KEY = "Your API key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tutorialvideo_view);
progressBar1 = (ProgressBar)findViewById(R.id.progressBar1);
progressBarText=(TextView)findViewById(R.id.progressBarText);
v_id="Your YouTube Video ID";
YouTubePlayerView youTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_player);
youTubePlayerView.setVisibility(View.VISIBLE);
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(v_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() {
}
};
}
Hope this may help you!
I had a similar problem, try deleting the: import R.java line, if it's there.

Categories

Resources