尝试在片段中使用VideoView时出现NullPointerException

时间:2016-06-10 06:09:08

标签: android android-fragments android-studio

我正在尝试将YouTube视频嵌入到我的应用中,如下所述:http://android-coffee.com/tutorial-how-to-play-youtube-videos-in-android-with-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" />

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您在没有ID findViewById(R.id.videoView);的布局上调用videoView

您应该更改以下行:

View view = inflater.inflate(R.layout.fragment_compare, container, false);

对此(假设布局fragment_videos具有ID videoView):

View view = inflater.inflate(R.layout.fragment_videos, container, false);