Alex
Alex

Reputation: 11

Strange force close

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

Answers (3)

dave.c
dave.c

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

WarrenFaith
WarrenFaith

Reputation: 57692

Is this the complete class? If so:

  1. An Activity has no constructor (at least non you should ever touch)
  2. You need to implement the onCreate() method
  3. You have nowhere set a content with setContentView(R.layout.my_layout)

Upvotes: 0

Rich Schuler
Rich Schuler

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

Related Questions