1

I am trying to play sound OnItemClick from a ListView I have set up.

I'm getting the error "The method create(Context, int) in the type MediaPlayer is not applicable for the arguments (new AdapterView.OnItemClickListener(){}, int)" with "create" underlined.

Not 100% sure why I am getting this error, if somebody could help, would be much appreciated.

ListView BoardList = (ListView) findViewById(R.id.BoardList);
BoardList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

String List[] = {"Play 1", "Play 2", "Play 3", "Play 4", "Play 5", "Play 6", "Play 7", "Play 8", "Play 9" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listcustomize, R.id.textItem, List);

BoardList.setAdapter(adapter);
BoardList.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            MediaPlayer  mPlayer = MediaPlayer.create(this, R.raw.Audio1);
            mPlayer .start();
            }
        }
    });
Eric Tobias
  • 3,225
  • 4
  • 32
  • 50
Jack
  • 2,043
  • 7
  • 40
  • 69

1 Answers1

5

Instead of this inside your MediaPlayer object you should write YourActivityName.this and try again!

MediaPlayer  mPlayer = MediaPlayer.create(YourActivityName.this, R.raw.Audio1);

This error occurs because you are inside the listener and the word this refers to the listener itself and not to your Activity.

Pavlos
  • 2,183
  • 2
  • 20
  • 27
  • Thank you good sir, you have taught somebody something today which will never be forgotten, Thanks. – Jack Aug 21 '13 at 14:22
  • Maybe you could expand your answer a bit to include an explanation about scope. I am sure future readers struggling with the problem will find it useful! – Eric Tobias Aug 21 '13 at 14:54
  • It's actually not a scope problem, it's about the basics of programming because in languages like Java you have to understand when the word `this` refers to the object you want – Pavlos Aug 21 '13 at 14:55
  • And to understand when the keyword `this` and how to use it properly you should ideally have a good grasp on scope. In this case, scope refers to object scope. Here, http://stackoverflow.com/questions/3728062/what-is-the-meaning-of-this-in-java, are some explanations about `this` that can lead to a better understanding of object scope, Basically, when `this` was used in the `onItemClick` method, it was inside the scope of the `OnItemClickListener` object. – Eric Tobias Aug 22 '13 at 10:09