我試圖嵌入YouTube視頻到我的應用程序,如下所述:http://android-coffee.com/tutorial-how-to-play-youtube-videos-in-android-with-videoview/NullPointerException異常時,試圖在一個片段使用VideoView
但是,我似乎當我訪問片段會遇到NullPointerException錯誤和我似乎無法找到因果關係。
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.VideoView.setVideoURI(android.net.Uri)' on a null object reference
該片段的代碼如下。
import android.widget.MediaController;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.VideoView;
public class VideosFragment extends Fragment {
public VideosFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_compare, container, false);
VideoView videoView;
videoView = (VideoView)view.findViewById(R.id.videoView);
MediaController mediaController;
mediaController = new MediaController(view.getContext());
mediaController.setAnchorView(videoView);
Uri uri= Uri.parse("rtsp://r7---sn-4g57kue6.googlevideo.com/Ck0LENy73wIaRAmk3cJBg-iaXhMYDSANFC3u0pRWMOCoAUIJbXYtZ29vZ2xlSARSBXdhdGNoYIaluaTkzciOVooBCzVxRjNraG5XcXdnDA==/D693A8E7577C3A29E60C292B42C9C87D7C25A565.762A63DC4CA0A028DA83256C6A79E5F160CBEDA3/yt6/1/video.3gp");
videoView.setMediaController(mediaController);
videoView.setVideoURI(uri);
videoView.requestFocus();
videoView.start();
return inflater.inflate(R.layout.fragment_videos, container, false);
}
}
這裏是佈局文件:
<FrameLayout 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"
tools:context="com.[left out for security].VideosFragment"
android:background="?android:attr/colorBackground">
<!-- TODO: Update blank fragment layout -->
<VideoView
android:id="@+id/videoView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
感謝您的幫助!
你VideoView爲空,請確保您初始化之後再使用。 – pcj
'videoView'出現在'R.layout.fragment_compare'中嗎? – SripadRaj