Reputation: 11
I have one main activity and an xml file with 3 different buttons (three different gun sounds)
So, when the user clicks one of the buttons a gunsound will be played.
here's how it looks -
public class gunstats extends Activity {
public gunstats(Bundle onSavedStateInstance) {
final MediaPlayer mp = MediaPlayer.create(this, R.drawable.deagle);
Button button3 = (Button)this.findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
}
}
the problem is that when I open the app in an emulator, it all force closes. When I check the logcat, it says "Caused by: java.lang.InstantiationException: com.gunstats.gunstats"
What is causing this?
Upvotes: 0
Views: 163
Reputation: 10908
Others have pointed out that you are not following the Activity
lifecycle.
Is R.drawable.deagle
your sound file? If so, it shouldn't be in the /drawable/
directory. Move it to somewhere like /raw/
.
Here are a couple of examples: Audio and Video, Audio Demo
Here are the docs for MediaPlayer
Upvotes: 0
Reputation: 57692
Is this the complete class? If so:
onCreate()
methodsetContentView(R.layout.my_layout)
Upvotes: 0
Reputation: 41972
This is because you are executing code in the constructor. You should not execute any code in an Activity
's constructor. You should move all that code into Activity#onCreate
.
You should become extremely familiar with the Activity Lifecycle.
Upvotes: 2