Using Mediaplayer within a Fragment

android, android-fragments

Solution

Use this code in onCreateView method of your fragment class and it will be working fine.

mp = MediaPlayer.create(getActivity, R.raw.songname);

Now you can call it's start method on your button click listener. Make sure to make the `MediaPlayer mp;` global for fragment class so you can use it afterwards.

Problem

I'm still trying to understand fragments and how they work. I have a fragment that inflates a layout. I am trying to play a sound when a button is pushed but I am coming across some problems with the mediaplayer. The code is: ``` private void playSound(int resId) { MediaPlayer mp = MediaPlayer.create(Tab1Fragment.this, resId); mp.setOnCompletionListener(Tab1Fragment.this); mp.start(); } ``` The error is: `The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (Tab1Fragment, int)` I tried using `getApplicationContext()` to no avail. Any help is appreciated Thanks

Original source