Search code examples
androidnullpointerexceptionshowfragmentmediacontroller

NullPointerException VideoView and MediaController on Fragment in android


I am developing Galaxy Tab 10.1 app by using honeycomb 3.1 and i have a videoview and mediacontroller in fragment on the right side. I defined VideoView and MediaController in Layout xml file and instantiate and manipulate them in the related java file.

As you guys konw, in the java file, i set VideoView's controller to MediaController and set MediaController's media player to VideoView, i defined.

Below is fragment layout xml file

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <VideoView
        android:id="@+id/video"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <MediaController
        android:id="@+id/controller"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

and java code file is below

public class ContentFragment extends Fragment {
    private VideoView mVideo;
    private MediaController mController;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.content, null);
        mVideo = (VideoView)view.findViewById(R.id.video);
        mController = (MediaController)view.findViewById(R.id.controller);
        mVideo.setMediaController(mController);
        mController.setMediaPlayer(mVideo);

        return view;
    }

    public void playVideo(String path) {
        mVideo.setVideoPath(path);
        mVideo.requestFocus();
    }
}

But while running this app, there occurs

NullPointerException with android.widget.MediaController.show(MediaController.java:305)

I tried to solve this error a whole day but i can't get the reason why. actullay there isn't enought information for this. Dose any body know what i did wrong? or have solutions? Please let me know.

Thanks.


Solution

  • Sorry, but instead of defining the MediaController in XML, you should instantiate it programatically (see the docs):

    mController = new MediaController(getActivity());
    

    And then attach it to the VideoView:

    mVideo.setMediaController(mController);
    

    Also, as far as I can tell, adding mController.setMediaPlayer(mVideo); is pointless since the call to setMediaController seems to take care of that as well.