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();
 }
}

90 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. Thank you for sharing information.It was great article and very informative
    "AchieversIT is the best Training institute for react js training.
    digital marketing training in bangalore "

    ReplyDelete
  15. There is definately a great deal too find out about this topic.

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

    ReplyDelete
  16. Heya i’m for the first time here. I found this board and I find It truly useful
    & it helped me out a lot. I hope to give something back and
    help others like you aided me. 온라인경마

    ReplyDelete
  17. This is a really very informative article, there is no doubt about it. Thanks for sharing this article with us. This is very nice of you. 온라인카지노

    ReplyDelete
  18. It was an awesome post to be sure. I completely delighted in understanding it in my noon. Will without a doubt come and visit this blog all the more frequently. A debt of gratitude is in order for sharing 사설토토

    ReplyDelete
  19. It seems like I've never seen an article of a kind like . It literally means the best thorn. It seems to be a fantastic article. It is the best among articles related to 먹튀검증업체. seems very easy, but it's a difficult kind of article, and it's perfect.

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

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

    ReplyDelete
  22. 바카라사이트 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
  23. good article, don’t forget to visit our website : 카지노사이트

    ReplyDelete
  24. I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard good things about ty le keo. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!

    ReplyDelete
  25. 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
  26. 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
  27. 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
  28. 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
  29. 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
  30. Hello! Do you know if they make plugins that support SEO? I'm trying to rank my blog for some target keywords, but I'm not seeing very good results. If anyone knows, please share. please. 메가슬롯

    ReplyDelete
  31. Thanks for the blog filled with so many information. Stopping by your blog helped me to get what I was looking for. Now my task has become as easy as ABC. 안전놀이터


    ReplyDelete
  32. 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
  33. 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
  34. 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
  35. 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
  36. 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
  37. 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
  38. We are looking for a lot of data on this item. In the meantime, this is the perfect article I was looking for . Please post a lot about items related to 메이저놀이터추천 !!! I am waiting for your article. And when you are having difficulty writing articles, I think you can get a lot of help by visiting my .

    ReplyDelete
  39. I no uncertainty esteeming each and every bit of it. It is an amazing site and superior to anything normal give. I need to grateful. Marvelous work! Every one of you complete an unfathomable blog, and have some extraordinary substance. Keep doing stunning 메이저사이트순위

    ReplyDelete
  40. 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
  41. 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
  42. It has a good meaning. If you always live positively, someday good things will happen. 메이저사이트Let's believe in the power of positivity. Have a nice day.


    ReplyDelete
  43. I always think about what is. It seems to be a perfect article that seems to blow away such worries. 온카지노 seems to be the best way to show something. When you have time, please write an article about what means!!

    ReplyDelete
  44. When I read an article on this topic, 메가슬롯 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

    ReplyDelete
  45. Awesome article! I want people to know just how good this information is in your article. It’s interesting, compelling content. Your views are much like my own concerning this subject 먹튀검증 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.


    ReplyDelete
  46. I'm looking for a lot of data on this topic. The article I've been looking for in the meantime is the perfect article. Please visit my site for more complete articles with him! casino trực tuyến

    ReplyDelete
  47. First of all, thank you for letting me see this information. I think this article can give me a lot of inspiration. I would appreciate 바카라사이트 if you could post more good contents in the future.

    ReplyDelete
  48. Hi there! This article could not be written much better! 토토

    ReplyDelete
  49. A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one. 카지노사이트

    ReplyDelete
  50. This is additionally a decent post which I truly delighted in perusing. 온라인카지노

    ReplyDelete
  51. 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
  52. 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
  53. 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
  54. Hello, I am one of the most impressed people in your article. 안전놀이터추천 I'm very curious about how you write such a good article. Are you an expert on this subject? I think so. Thank you again for allowing me to read these posts, and have a nice day today. Thank you.

    ReplyDelete