For some reason, AppCompatActivity refuses to let me embed Youtube videos even though I am using the SupportFragment activity. The app crashes every time an activity contains a Youtube fragment. How can I fix this?
public class Insane1x1 extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
public static final String API_KEY = "AIzaSyBqaaaaaaa";
public static final String VIDEO_ID = "3MvnRsItEmg"; //1-1
//private YouTubePlayer youTubePlayer;
private YouTubePlayerSupportFragment youTubePlayerFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insane1x1);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
youTubePlayerFragment = (YouTubePlayerSupportFragment) getSupportFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, 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.insane1x1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onInitializationFailure(Provider provider,
YouTubeInitializationResult result) {
Toast.makeText(getApplicationContext(),
"YouTubePlayer.onInitializationFailure()",
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();
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
}
And here's the xml file:
<fragment
android:name="com.google.android.youtube.player.YouTubePlayerSupportFragment"
android:id="#+id/youtubeplayerfragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Is it the YouTubePlayer that is crashing the app, when it is cuing the video in the onInitializationSuccess method??
I think it's cz its not extending "YouTubeBaseActivity", for some reason though YouTubeBaseActivity doesn't have as much functionality as AppCompatActivity. Maybe there are newer versions. But I'dd say thats the problem.
Related
How to get youtube key_vedio_id please help me to find-out this problem.
This is my code please and correct me if i wrong any where.
public class YouTubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_DIALOG_REQUEST = 1;
public static final String KEY_VIDEO_ID = "KEY_VIDEO_ID";
private String mVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_youtube);
final Bundle arguments = getIntent().getExtras();
if (arguments != null && arguments.containsKey(KEY_VIDEO_ID)) {
mVideoId = arguments.getString(KEY_VIDEO_ID);
}
final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView);
playerView.initialize(getString(R.string.DEVELOPER_KEY_YOU_TUBE), this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean restored) {
//Here we can set some flags on the player
//This flag tells the player to switch to landscape when in fullscreen, it will also return to portrait
//when leaving fullscreen
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
//This flag tells the player to automatically enter fullscreen when in landscape. Since we don't have
//landscape layout for this activity, this is a good way to allow the user rotate the video player.
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_ALWAYS_FULLSCREEN_IN_LANDSCAPE);
//This flag controls the system UI such as the status and navigation bar, hiding and showing them
//alongside the player UI
youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
if (mVideoId != null) {
if (restored) {
youTubePlayer.play();
} else {
youTubePlayer.loadVideo(mVideoId);
}
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
//Handle the failure
Toast.makeText(this, R.string.error_init_failure, Toast.LENGTH_LONG).show();
}
}
}
List youtube playlist from my playlist with ID PLSt1J_r1AmrzOUCGZ6sWNxvOePK4nOwIk into my android application but it is showing one video at a time but on want it to show the whole list of videos before I play any video.
My main activity code
public class MainActivity extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "AIzaSyCe6tORd9Ch4lx-9Ku5SQ476uS9OtZYsWA";
public static final String VIDEO_ID = "o7VVHhK9zf0";
public static final String PlayList_ID = "PLP7qPet500dfglA7FFTxBmB_snxCaMHDJ";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
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);
textVideoLog = (TextView)findViewById(R.id.videolog);
btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
}
#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();
if (!wasRestored) {
//player.cueVideo(VIDEO_ID);
player.cuePlaylist(PlayList_ID);
}
}
}
The playlist id, are the characters after "PL".
You can use recyclerView for the list. I have done this using Youtube api rest calls. You will need to get a browser key from the google developer console. I've explained this in my answer here:
https://stackoverflow.com/a/41201084/3689744
Am new in android development.Am trying to implement youtube Api. But in my XML file it show error "could not be instantiated:
- com.google.android.youtube.player.YouTubePlayerView"
Here is My MAinActivity Code:-
public class MainActivity extends YouTubeBaseActivity {
Button b;
private YouTubePlayerView youtubeplayerview;
private YouTubePlayer.OnInitializedListener onInitializedListener;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_main);
youtubeplayerview=(YouTubePlayerView)findViewById(R.id.Youtube_view);
onInitializedListener=new YouTubePlayer.OnInitializedListener(){
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.loadVideo("wvjqFy33HVA");
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
};
b=(Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
youtubeplayerview.initialize("API KEY",onInitializedListener);
}
});
}
}
Here is my XML file Code:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PLAY VEDIO"
android:id="#+id/button"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<com.google.android.youtube.player.YouTubePlayerView
android:layout_width="500dp"
android:layout_height="500dp"
android:id="#+id/Youtube_view"
android:layout_alignParentTop="true"
android:layout_above="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
Here is Error Screenshot
Did you add YouTube Android Player API to your library? Adding that fixed the issue for me..Try adding the same by following the steps given below :
1.Download YouTube Android Player API jar file from https://developers.google.com/youtube/android/player/downloads/
2.Extract the zip file, go to libs -> YouTubeAndroidPlayerApi.jar and copy it
3.Paste the jar file to /app/libs/ directory in android studio
Finally add compile files('libs/YouTubeAndroidPlayerApi.jar') to your app level build.gradle file
Sync,build and check if it works fine
Did you generate api key for android youtube player?
Link: https://console.developers.google.com
If yes, you must to change "API KEY " in this youtubeplayerview.initialize("API KEY",onInitializedListener); by your api key that you generated before.
Anyway, you can try to replace you class by this class with YoutubeDeveloperKey is the key you generated :
public class ActivityPlayYouTube extends YouTubeBaseActivity implements
YouTubePlayer.OnInitializedListener {
private YouTubePlayer YPlayer;
private static final String YoutubeDeveloperKey = "YOUR_DEVELOPER_KEY_GOES_HERE";
private static final int RECOVERY_DIALOG_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playyoutube);
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) {
if (!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.
*/
YPlayer.cueVideo("2zNSgSzhBfM");
}
}
}
Is there an option to modify the content view on the android panorama client? For example I want to display the action bar on top. But currently the action bar is just shown at the beginning and subsequently hidden by the loaded panorama client, since the panorama client is always shown in full screen mode, although it is started in an extra fragment.
I tried now to put the panorama client in a seperated frame through a fragment - this is my code so far:
1. This is the activity whit the panorama fragment and and a text field:
public class PanoramaActivity extends Activity {
public static final String TAG = PanoramaActivity.class.getSimpleName();
private ActionBar actionBar;
private Fragment panoramaClient = new PanoramaClientFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_snow);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTrans = fragMan.beginTransaction();
fragTrans.replace(R.id.panoramaCLientFrame, panoramaClient, "PANO");
fragTrans.commit();
//Non fullscreen
requestWindowFeature(Window.FEATURE_ACTION_BAR);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.panorama, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
2.And this is the fragment class with the panorama client:
public class PanoramaClientFragment extends Fragment implements ConnectionCallbacks,
OnConnectionFailedListener, OnPanoramaInfoLoadedListener {
private View view;
private PanoramaClient panoramaClient;
public static final String TAG = PanoramaClientFragment.class.getSimpleName();
public PanoramaClientFragment() {
// TODO Auto-generated constructor stub
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanteState){
view = inflater.inflate(R.layout.panorama_client, container, false);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
panoramaClient = new PanoramaClient(getActivity().getApplicationContext(), this, this);
//Non fullscreen
//getActivity().requestWindowFeature(Window.FEATURE_ACTION_BAR);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
//getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
#Override
public void onStart() {
super.onStart();
panoramaClient.connect();
}
#Override
public void onPanoramaInfoLoaded(ConnectionResult result, Intent viewerIntent) {
if (result.isSuccess()) {
Log.i(TAG, "found viewerIntent: " + viewerIntent);
if (viewerIntent != null) {
startActivity(viewerIntent);
}
} else {
Log.e(TAG, "error: " + result);
}
}
#Override
public void onConnectionFailed(ConnectionResult status) {
Log.e(TAG, "connection failed: " + status);
}
#Override
public void onConnected(Bundle arg0) {
Uri uri = Uri.parse("android.resource://" + this.getActivity().getPackageName() + "/" + R.raw.pano1);
panoramaClient.loadPanoramaInfo(this, uri);
}
#Override
public void onDisconnected() {
// Do nothing.
}
#Override
public void onStop() {
super.onStop();
panoramaClient.disconnect();
}
}
If i uncomment the three "non fullscreen"-lines in the fragment class, the app crashes and says:
android.util.AndroidRuntimeException: requestFeature() must be called before adding content
Thanks for your replies.
Greetings.
Try to create a fragment and add the panorama client activity to it.
I think you cannot show the action bar for one simple reason, when your panorama info is loaded you are starting a new activity which is completely out of your control.
if (viewerIntent != null) {
startActivity(viewerIntent);
}
So your code tries to modify the activity that handles the PanoramaClient instance, but not the one that loads the panorama image.
I'm trying to play video in my Fragment. However, I cannot get it to work. If I'm extending 'YoutubeFailureRecovery' I get:
09-06 21:56:40.472: E/AndroidRuntime(4946): Caused by: java.lang.IllegalStateException: A YouTubePlayerView can only be created with an Activity which extends YouTubeBaseActivity as its context.
This is my .xml:
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/player"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
And this is the class:
public class YoutubeFragment extends YoutubeFailureRecovery {
YouTubePlayer player;
YouTubePlayerView playerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.detailview, container, false);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
playerView = (YouTubePlayerView)getActivity().findViewById(R.id.player);
playerView.initialize(DataHolder.DEVELOPER_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player,
boolean wasRestored) {
// TODO Auto-generated method stub
player.cueVideo("nCgQDjiotG0");
}
#Override
protected Provider getYouTubePlayerProvider() {
// TODO Auto-generated method stub
return playerView;
}
}
public abstract class YoutubeFailureRecovery extends YouTubePlayerSupportFragment implements YouTubePlayer.OnInitializedListener{
I just don't know what to do. I tried to extend my Fragment class with 'YoutubePlayerSupportFragment', tried to add a video-like fragment in XML, but nothing is working (error inflating). Maybe someone has some experience with using YouTube API in Fragment?
The YouTubePlayerView only works with an Activity that extends
YouTubeBaseActivity.
If you want to use Fragments you have to use the YoutubePlayerFragment / SupportFragment.
You can for example create your custom Fragment that inherits from YoutubePlayerSupportFragment:
public class VideoFragment extends YouTubePlayerSupportFragment {
public VideoFragment() { }
public static VideoFragment newInstance(String url) {
VideoFragment f = new VideoFragment();
Bundle b = new Bundle();
b.putString("url", url);
f.setArguments(b);
f.init();
return f;
}
private void init() {
initialize("yourapikey", new OnInitializedListener() {
#Override
public void onInitializationFailure(Provider arg0, YouTubeInitializationResult arg1) { }
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
}
}
});
}
}
In code it could look like this:
VideoFragment f = VideoFragment.newInstance("your-video-url");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, f).commit();
The "fragment_container" in this case should be an empty FrameLayout.