我在Android应用中集成YouTube播放器时出现此错误。
这一行出错 - youTubeView.initialize(Config.DEVELOPER_KEY, this);
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.youtube.player.YouTubePlayerView.initialize(java.lang.String, com.google.android.youtube.player.YouTubePlayer$OnInitializedListener)' on a null object reference
我的代码:
private static final int RECOVERY_DIALOG_REQUEST = 1;
private YouTubePlayerView youTubeView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_you_tube_test);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
youTubeView = findViewById(R.id.youtube_view);
// Initializing video player with developer key
youTubeView.initialize(Config.DEVELOPER_KEY, this);
}
@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
if (!b) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
youTubePlayer.loadVideo(Config.YOUTUBE_VIDEO_CODE);
// Hiding player controls
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
}
}
@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
Toast.makeText(this, youTubeInitializationResult.toString(), 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(Config.DEVELOPER_KEY, this);
}
}
private YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
答案 0 :(得分:0)
从google api控制台获取API开发人员密钥,并在单独的类中添加密钥,如下例所示。
public class Config {
private Config() {}
public static final String DEVELOPER_KEY="AIzaSyAwhK2xxxxxxx-xxxxxxxxxxxE";
}
答案 1 :(得分:0)
检查您的setContentView(R.layout.activity_you_tube_test);
我的意思是与您的活动相关的布局可能有所不同。