tags:

views:

245

answers:

1

Hi all, I'm trying to play a sound file when a button is clicked but keeps getting an error.
The error is "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new View.OnClickListener(){}, int)"

Here's my code:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    Button zero = (Button)this.findViewById(R.id.btnZero);
    zero.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            mp = MediaPlayer.create(this, R.raw.mamacita_zero);
        }
    });
}

Any help or tips would be appreciated. Thnx!

A: 

There are a few things going on here (disclaimer, this is just how I'm used to using it, there may be a better way):

  • You seem to be doing a lot more work per click than you need to. You're creating and adding a new onClickListener for every click in the Activity's View, not the Button. You only need to set the listener once, and for the Button rather than the overarching View; I tend to do that in the constructor of the Activity.

  • Regarding your error, MediaPlayer works fine for me when the Context I pass it is the overriding Activity. When you pass this, it's passing the onClickListener you are creating, throwing off the MediaPlayer.

  • Finally, to actually play the sound, you have to call start().

So for the constructor in the Activity, you can create the MediaPlayer once, find the Button, and attach an onClickListener that will play the sound from the MediaPlayer you've just created. It would look something like:

public class MyActivity extends Activity {

    public MyActivity(Bundle onSavedStateInstance) {
        // eliding some bookkeepping

        MediaPlayer mp = MediaPlayer.create(this, R.raw.mamacita_zero);

        Button zero = (Button)this.findViewById(R.id.btnZero);
        zero.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.start();
            }
        });
    }
}

Hope that helps!

paul.meier