I am try to play video using youtube video API
When I put static ID means declare ID in file at that time code is working.
But when I try to fetch ID from getIntent() I also got ID but video not play.
I got There was problem with network.
Below is my code. Its working in this condition.
public String VIDEO = "QqnBjKnwCwE";
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, Videosshow.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(String.valueOf( VIDEO));
}
Now When I used
Bundle data = getIntent().getExtras();
VIDEO=data.getString("videourl");
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(DEVELOPER_KEY, Videosshow.this);
not working I got 400 Network problem error
Check your id .I think there is space in id or youtube url either start or end .I have similar problem and solved by this .You should also try .It may be help for if you have setup all properly .
I figured out that the id I was sending was incorrect, it had an extra = (say =hdeFZ6nt9tc)which was not to be sent. The problem occurred as I was extracting it from the youtube's actual URL(say https://www.youtube.com/watch?v=hdeFZ6nt9tc). I hope even you too might have been sending the wrong id.
Double check it again even if you are pretty sure.
What I think is youtube must send a 404(which generally refers to "Page Not Found" on the web) for such requests.
I had same the problem but retrieving video id from url solved my problem.
String video_id=jsonObject.getString("id");
Thank You ritesh.
Related
When I pass youtube ID from recycleview onClick then it shows "This video is unavailable". But same video id works fine when I hard code it. I tried every possible way but could not find any solution. Please, help if anyone can.
This is the code for sending video key,
intent.putExtra("vUrl", adListModel.getUrl());
Getting the video key,
vUrl = getIntent().getStringExtra("vUrl");
Here, I am trying to load video from the video key,
youTubePlayerView.initialize(getResources().getString(R.string.google_api_key), new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
String videoId = vUrl;
Log.e("YOUTUBE_KEYS", videoId);
youTubePlayer.cueVideo(videoId);
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
youTubePlayer.play();
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
Whenever I'm trying to open Youtube player in my app, onInitializationSuccess() function is always called. But it shows a blank screen.
First this error appears:
W/YouTubeAndroidPlayerAPI: Forcefully created overlay:affq#82a17f5 helper:Lazy#9b7098a view:null status: ....... {...}
and then:
E/YouTubeAndroidPlayerAPI: Embed config is not supported in RemoteEmbeddedPlayer.
Here is my code:
FragmentManager fragmentManager = ((AppCompatActivity)this.context).getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment youtubeFragment = new YouTubePlayerSupportFragment();
fragmentManager.beginTransaction().add(R.id.GlideLayout ,youtubeFragment).commit();
utubevw = (YouTubePlayerSupportFragment) youtubeFragment;
utubecontainer = imageLayout.findViewById(R.id.youtubecontainer);
utubecontainer.setVisibility(View.VISIBLE);
mOnInitializeListener = new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo("_8kExcHqFi4");
Log.i("youtube", "Successful");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Log.i("youtube:Fail", youTubeInitializationResult.toString());
}
};
utubevw.initialize(String.valueOf(R.string.googleapikey), mOnInitializeListener);
Searched everywhere, even posted in Github, but couldn't find a solution.
FYI - I don't want to use Webview to play Youtube.
I had the same problem just now and i was able to solve it by removing all possible overlaying views.
I had a FAB just closely overlaying the youtube fragment. After moving the FAB away the error was fixed.
Try using youTubePlayer.loadVideo(" ") instead of youTubePlayer.cueVideo(" ") to auto play the video when the fragment is started.
According to the docs, if you use the cueVideo() function, you need to call play() or it does not download any of the video stream. Whereas the loadVideo() auto plays the video.
I tried the answer of #PeterOla, it worked for sometime but after sometime the error came back, and after hours of struggle, i found that i had to parse just the key url (without the youtube/) in the youTubePlayer.cueVideo(""), and it worked well for me.
Edit: Strangely works when duplicating the loadUrl() line
I'm working with WebViews to gather data from a webpage. Sometimes, the webview just does nothing. I tried many proposes, but actually, none of them works....
Strange: webview.loadUrl("url...") doesn't work, but as soon as I call it twice, it works...
checkLogin()
void checkLogin(final Context context) {
Log.d("checkLogin()", "Begin of checkLogin()");
WebView webview = returnNewWebView(context, false);
webview.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
Log.d("url", url);
// GOOGLE.COM ACTUALLY WORKS!
if(url.equals("https://www.google.com/"))
return;
Log.d("checkLogin()", "Loading of checkpage finished");
if(url.contains("loginto.php")) {
Log.d("checkLogin()", "User is logged out");
OnLoginCheckListener.onLoginCheckLoggedOut();
} else {
Log.d("checkLogin()", "User is logged in");
OnLoginCheckListener.onLoginCheckLoggedIn();
}
}
});
String id = sharedPref.getString("id", null);
String transid = sharedPref.getString("transid", null);
if(TextUtils.isEmpty("id") || TextUtils.isEmpty("transid")) {
Log.d("checkLogin()", "No login found, starting LoginActivity()");
Intent myIntent = new Intent(context, LoginActivity.class);
context.startActivity(myIntent);
} else {
Log.d("checkLogin()", "Probably logged in, checking by loading startpage");
webview.loadUrl("https://www.google.com");
// google actually works -.-
webview.loadUrl("https://my.login-page.com/index.php?pageid=1&id=" + id + "&transid=" + transid);
}
}
returnNewWebView()
private WebView returnNewWebView(Context context, Boolean JSInterface) {
// Prepare a webview
WebView WebView = new WebView(context);
if(JSInterface) {
WebView.getSettings().setJavaScriptEnabled(true);
WebView.addJavascriptInterface(new JavaScriptInterface(), "AndroidInterface");
}
// We don't need images for data scraping...
WebView.getSettings().setLoadsImagesAutomatically(false);
WebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
// Allow cookies
CookieManager.getInstance().acceptCookie();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
CookieManager.getInstance().acceptThirdPartyCookies(WebView);
}
// Prevent webview not loading
// or try it...
WebView.clearCache(true);
WebView.destroyDrawingCache();
return WebView;
}
As you see, I already tried some stuff in order to prevent it but still, it doesn't work. In that cases, as soon I'm going to put the loadUrl() / postUrl()twice, it works.
What can I do that it works in every single case?
I would appreciate any tip!
Thank you very much in advance
logcat (non-filtered)
I actually see this message then..
03-09 07:36:19.061 4111-24251/? E/ctxmgr: [ProducerActiveIntervalImpl]closeActiveInterval: Error: ongoing, trying to close
and this one:
03-09 07:36:28.864 29862-3249/? E/accs.GcmPush: initializeApp occur error!
java.lang.IllegalStateException: FirebaseApp name [DEFAULT] already exists!
at iv.a(Unknown Source)
at com.google.firebase.FirebaseApp.a(Unknown Source)
at com.google.firebase.FirebaseApp.a(Unknown Source)
at org.android.agoo.gcm.GcmRegister$1.run(GcmRegister.java:32)
and this one too:
E/libEGL: validate_display:99 error 3008 (EGL_BAD_DISPLAY)
But I can't tell you if they are fired by the app....
I have gone through the full code for so long and pointed out this :
You are using this -
webview.loadUrl("https://www.google.com");
// google actually works -.-
webview.loadUrl("https://my.login-page.com/index.php?pageid=1&id=" + id + "&transid=" + transid);
in your checkLogin() method which is simply wrong as because one webview can not display the two urls at same time (as you mentioned it you want to achieve that).
Now according to your code the loading of the first url is overridden by the second url.
In order to achieve the loading of two urls in same webview try to implement this using :
Threads or some sessionTimeout methods.
OR
You can achieve this by using okhttp package.
Hope this helps!
onPageFinished is called when the webpage finished loading, but not after all the javascript on the page finished running. Depending on what the page is doing and what you are trying to achieve, it might be that your code is sometimes being executed before some essential javascript is executed on that page.
It's not a pretty solution but try adding some delay (like a Handler's postDelayed() or SystemClock.sleep() - but never on the UI thread!) to your code to see if that is indeed your problem.
I would like to interact with YouTube app on android.
My app is basically a service that is running all the time.
I wanna detect if user was watching YouTube and then lock the phone, when he come back the last watched video should continue playing.
Any suggestions? Where to start?
I am thinking to implement a software touch on play button. Is there any other way to do it?
Here is how you can force a video:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + id));
startActivity(intent);
Obtaining the Android API Key
First we need to get the SHA-1 fingerprint on your machine using java keytool. Execute the below command in cmd/terminal to get the SHA-1 fingerprint.
Go to Google Developer Console and select or create a new project.
On the left sidebar, select APIs under APIs & auth and turn the status ON for YouTube Data API v3.
On the left sidebar, select Credentials and Create new key under Public API acess.
When popup comes asking you to choose platform, select Android Key.
Paste the SHA-1 key and your project’s package name separated by semicolon(;).
Click on create. Now you should see the API KEY on the dashboard.
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(Config.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(Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
}
i am trying to embed a youtube api for android, everything for good except the fact, that video play for a one second only and then stop automaticly. but when i am going to the fullScreenMode, the video playing as expected.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_show);
ivThumbnail = (ImageView) findViewById(R.id.ivThumbnail);
tv = (ImageView) findViewById(R.id.tv);
Intent i = getIntent();
screenCase = i.getIntExtra("screenCase", -1);
selectedVideoId = Splash.playlists[screenCase].getItems().get(0).getVideo().getId();
setProperTvImage();
createButtons();
ivThumbnail.setImageBitmap(Splash.playlists[screenCase]
.thumbnails[0]);
youtubeLV = (ListView)findViewById(R.id.lvPlaylist);
adapter = new MyYoutubeListAdapter(this, Splash.playlists[screenCase].getItems(), screenCase);
youtubeLV.setAdapter(adapter);
youtubeLV.setOnItemClickListener(this);
youtubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youtubePlayerView.initialize(DeveloperKey.DEVELOPER_KEY, this); //init Player
}
onInitializationSuccess
public void onInitializationSuccess(Provider arg0, YouTubePlayer _player,
boolean wasRestored) {
this.player = _player;
//player.setPlayerStyle(PlayerStyle.CHROMELESS);
if(!wasRestored){
playVideoAtSelection();
}
}
and finally playVideAtSelection methode
private void playVideoAtSelection() {
if(player != null){
Log.e("player ", "not null");
player.cueVideo(selectedVideoId);
}else{
Log.e("player ", "null");
}
}
Any suggestions?
Well, its a bit late for answer, but someone might stumble on this post and might get an insight.
I was facing the same issue and 1st option below solved my problem.
After a lot of search regarding the similar issue, I came across two things.
1) Check if your YoutubePlayerView (in activity XML) has padding option. Remove the padding if its there.
2) As per youtube Api documentation, the minimum size specified is 200 x 110 dp for YoutubePlayerView. Make suitable changes in size if that is the case.
Hope it helps somebody.