Reputation: 536
I am trying to make a simple button that plays a sound, but I am getting an error on (this, R.raw.shotgun)
. I have the raw
folder and the sound file. I think the problem is with the this
but I don't know why. Thanks.
public class MainActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(this, R.raw.shotgun);
mp.start();
}
});
}
}
Upvotes: 1
Views: 1771
Reputation: 59274
The first parameter of MediaPlayer.create is a Context
. The usage of MediaPlayer.create(this, R.raw.shotgun)
works when you are working in your Activity
s scope, because Activity
extends Context
, therefore this
in this case ends up being a Context
as well.
However, you're working within View.OnClickListener
scope, and this
assumes this class' value, and not Context
as required. To fix that, just set the Context variable to this
while still in your Activity scope.
public class MainActivity extends AppCompatActivity {
private Button button;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this;
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(context, R.raw.shotgun);
mp.start();
}
});
Upvotes: 3