How to play a video from resources

As am getting lots of good feedback on my answer on SO for the question How to play a video from the raw or assets folder, I thought of writing this small tutorial on playing a video in your activity.

So, say you want to create a splash activity that will show an mp4 video that you stored in your raw directory which is usually located in your projects's res. Usually, the directory raw is not there, so just create one there. Add your splash video to the raw folder: In my case, it is splash.mp4

In your splash activity create the function splashPlayer():

public void splashPlayer() {
 VideoView videoHolder = new VideoView(this);
 setContentView(videoHolder);
 Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
    + R.raw.splash);
 videoHolder.setVideoURI(video);
 videoHolder.setOnCompletionListener(new OnCompletionListener() {
  public void onCompletion(MediaPlayer mp) {
   jumpMain(); //jump to the next Activity
  }
 });
 videoHolder.start();
}

In the previous code the function jumpMain() will probably jump you to the next activity. If you want to give the user the option to cancel your video/splash, add the following line to the end of splashPlayer():

videoHolder.setOnTouchListener(new OnTouchListener() {
 @Override
 public boolean onTouch(View v, MotionEvent event) {
  ((VideoView)v).stopPlayback();
  jumpMain();
  return true;
 }
});

Finally, in your onCreate() function call this splashPlayer():

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 splashPlayer();
}

An extra step would be to surround the splashPlayer() call in your onCreate() with a try...catch block. My personal experience shows that not all videos are playable on all devices even if they are mp4 videos. If this is the case, an exception is thrown and you can for example show an image instead. In this example I will only jump to the next Activity by calling jumpMain(), so my onCreate looks something like this:

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 try {
  splashPlayer();
 } catch(Exception ex) {
  jumpMain();
 }
}

Do not forget to call finish() in your jumpMain() and enjoy!

 Here is the full SplashActivity (I am just showing the general idea so feel free to notify me of errors or bugs)
public class ActivitySplash extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  try {
   splashPlayer();
  } catch (Exception ex) {
   jumpMain();
  }
 }

 @Override
 public boolean onTouchEvent(MotionEvent ev) {
  return false;
 }

 public void splashPlayer() {
  VideoView videoHolder = new VideoView(this);
  setContentView(videoHolder);
  Uri video = Uri.parse("android.resource://" + getPackageName() + "/"
    + R.raw.splash);
  videoHolder.setVideoURI(video);
  videoHolder.setOnCompletionListener(new OnCompletionListener() {
   public void onCompletion(MediaPlayer mp) {
    jumpMain();
   }

  });
  videoHolder.start();
  videoHolder.setOnTouchListener(new OnTouchListener() {

   @Override
   public boolean onTouch(View v, MotionEvent event) {
    ((VideoView) v).stopPlayback();
    jumpMain();
    return true;
   }
  });
 }

 private synchronized void jumpMain() {
  Intent intent = new Intent(ActivitySplash.this, ActivityMain.class);
  startActivity(intent);
  finish();
 }
}

46 comments:

  1. When I copy the code and run, it says that raw cannot be resolved or is not a field. What is this?

    ReplyDelete
    Replies
    1. You must create a folder called 'raw' in your folder 'res' and add your video to this folder. In case you already did so, just clean your project and it should be there

      Delete
  2. Simply copying above code I found message like the video can not be played. Resource file in raw folder also. I also updated to api level 8

    ReplyDelete
    Replies
    1. This could happen when the file format is not supported by the device. I usually try catch and show a picture (when this is just a splash video)

      Delete
  3. This comment has been removed by a blog administrator.

    ReplyDelete
  4. i can find activity main in

    private synchronized void jumpMain() {
    -> Intent intent = new Intent(ActivitySplash.this, ActivityMain.class);
    startActivity(intent);
    finish();
    }

    how i can create that?

    ReplyDelete
  5. I love you Sherif!!!! You're the best!!!! :D mwahhh

    ReplyDelete
  6. "The method setOnCompletionListener(MediaPlayer.OnCompletionListener) in the type VideoView is not applicable for the arguments (new OnCompletionListener(){})"

    i found this error what should i do to encounter it?

    ReplyDelete
    Replies
    1. Make sure you are using MediaPlayer.OnCompletionListener.

      Delete
  7. I got an error that The process has stopped unexpectedly please try again. I run it many times but getting the same error.And when i mention my video name if i give .mp4 extension it shows an error and if i remove it error disappears. Please help me in solving this and please explain me in some detail

    ReplyDelete
  8. Thank you. I needed to avoid borders, so I created a relative layout with background-color the same as the video. To this I added a VideoView.
    In the constructor I use setContentView(R.id.layout.my_layout), and ind splasPlayer() I use findViewById to get the video-view (don't set at content-view!).

    ReplyDelete
    Replies
    1. I actually did this for demonstration so, for sure, you need to do your own implementation. Thank you. Good job

      Delete
  9. I created a new class with your Code and added a mp4 into the raw folder but my app chrashes all the time :(

    ReplyDelete
    Replies
    1. Oh sry, now it works fine, I've forgot the activity entry in the manifest.

      Delete
  10. how to show videos in list view from raw folder and how to display them?
    Thanku in advance...

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. VideoView video_view = (VideoView) findViewById(R.id.video_view);
    Uri video = Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.hello);
    video_view.setVideoURI(video);
    video_view.start();

    in this case .setVideoURI and .start both highlight in red and says the symbol cannot be resolved

    ReplyDelete
  13. Uri uri = Uri.parse("android.resource://" +getPackageName()+"/"+R.raw.video1 );
    in this case getPackageName() highlight in red and says the symbol cannot be resolved

    ReplyDelete
    Replies
    1. You need a Context instance to do this. So if you are in a fragment for example you can use getActivity().getPackageName() instead

      Delete
  14. There is definately a great deal too find out about this topic.

    I love all of the points you have made. 토토

    ReplyDelete
  15. 토토사이트 I procrastinate a lot and don’t manage to get nearly anything done. waiting for your further write ups thanks once again.

    ReplyDelete
  16. 스포츠토토 Thank you for your blog article.Really looking forward to read more. Will read on…

    ReplyDelete
  17. 바카라사이트 It is in point of fact a nice and helpful piece of info.
    I’m happy that you simply shared this helpful information with us.

    Please stay us up to date like this. Thank you for sharing.

    ReplyDelete
  18. good article, don’t forget to visit our website : 카지노사이트

    ReplyDelete
  19. Many thanks for the article, I have a lot of spray lining knowledge but always learn something new. Keep up the good work and thank you again. 메이저사이트모음


    ReplyDelete
  20. What a post I've been looking for! I'm very happy to finally read this post. 안전놀이터 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


    ReplyDelete
  21. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article :D 먹튀검증


    ReplyDelete
  22. Hello!,I love your writing very so much! percentage we be
    in contact more approximately..
    You can safely browse our links for more information about our services....

    Buy Rohypol Flunitrazepam 2 Mg

    Buy ativan online

    Buy opana oxymorphorne

    Buy dsuvia 30 mcg online

    Buy viagra sildenafil 100mg

    ReplyDelete
  23. Succeed! It could be one of the most useful blogs we have ever come across on the subject. Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. 안전놀이터


    ReplyDelete
  24. casino trực tuyếnNovember 16, 2021 at 10:11 AM

    This is the perfect post.casino trực tuyến It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.

    ReplyDelete
  25. Thanks for an interesting blog. What else may I get that sort of info written in such a perfect approach? I have an undertaking that I am just now operating on, and I have been on the lookout for such info 먹튀검증 It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.


    ReplyDelete
  26. I figure this article can be enhanced a tad. There are a couple of things that are dangerous here, and if you somehow managed to change these things, this article could wind up a standout amongst your best ones. I have a few thoughts with respect to how you can change these things. 메이저놀이터


    ReplyDelete
  27. Hello, I am one of the most impressed people in your article. 먹튀검증 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.


    ReplyDelete
  28. You make so many great points here that I read your article a couple of times. Your views are in accordance with my own for the most part. This is great content for your readers. 안전놀이터


    ReplyDelete
  29. Hi there, I simply hopped over in your website by way of StumbleUpon. Now not one thing I’d typically learn, but I favored your emotions none the less. Thank you for making something worth reading. 카지노슬롯


    ReplyDelete
  30. Oh, the data you've shared in this incredible article is just magnificent. I am definitely going to make more use of this data in my future projects. You must continue sharing more data like this with us. 메이저놀이터


    ReplyDelete
  31. webgirls.pl With regards to battling yeast infections, affected individuals frequently have their operate reduce to them. This is because yeast infections can readily become long-term and ongoing. With that in mind, in this post, we are going to present a selection of among the best verified candida remedy and reduction suggestions about.

    ReplyDelete
  32. https://gameeffect.xyz Lots of people have adored this game of baseball for several years. There are actually fans around the globe, from devoted little-leaguers to expire-challenging spectators. This information has suggestions to confirm how enjoyable baseball happens to be.

    ReplyDelete
  33. https://gamezoom.xyz Acquiring a exercise routine spouse can significantly improve your muscle-constructing effects. Your partner can be a useful source of inspiration for sticking to your regular workout treatment, and forcing you to increase your attempts as you work out. Developing a dependable lover to determine with can also help help keep you harmless since you will invariably have got a spotter.

    ReplyDelete