user3879626 user3879626 - 1 year ago 98
Android Question

Play song in android using android studio

Button playButton = (Button)findViewById(;
playButton.setOnClickListener(new View.OnClickListener()
public void onClick(View v)`enter code here`
MediaPlayer mMediaPlayer;

mMediaPlayer = new MediaPlayer();
mMediaPlayer = MediaPlayer.create(this, R.raw.shenkin);


I am getting error on "this" as parameter to MediaPlayer.create
What should I do to fix it ?

Answer Source

In that scope, this refers to new View.OnClickListener(), but you want it to refer to your activity, or pass any other context. In that case, you should do:

mMediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.shenkin); 
//Or whichever the name of the activity is

or something like

mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.shenkin); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download