I want to load a video in a video view from raw folder with the following code

 String uri = "android.resource://" + getPackageName() + "/" + R.raw.preview;
 VideoView mVideoView  = (VideoView)findViewById(R.id.videoView1);
 mVideoView.setVideoURI(Uri.parse(uri));
 mVideoView.requestFocus();
 mVideoView.start();

I receive NullPointerException at this line: mVideoView.setVideoURI(Uri.parse(uri)); Any ideas in what should I do ?

有帮助吗?

解决方案

Make sure the findViewById function call is returning a VideoView object and is not null.

Null pointer errors typically happen when you call an method to a object that is null.

Chances are the reference to R.id.videoView1in your layout xml file is wrong or you could have an error in your xml layout file that isn't showing up.

If you're using Eclipse or Android Studio, the R.i.videoView1 should be blue, showing that it was found in the layout file.

Also you can verify the object isn't null before calling the methods to be sure. See below:

 String uri = "android.resource://" + getPackageName() + "/" + R.raw.preview;
 VideoView mVideoView  = (VideoView)findViewById(R.id.videoView1);
 if (mVideoView != null)
 {  mVideoView.setVideoURI(Uri.parse(uri));
    mVideoView.requestFocus();
    mVideoView.start();
 } else
 { //toast or print "mVideoView is null"
 }

其他提示

Try this:

String path = "android.resource://" + getPackageName() + "/" + R.raw.preview;
VideoView mVideoView  = (VideoView)findViewById(R.id.videoView1);
mVideoView.setVideoPath(path);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top