質問

I am making a soundboard app and I keep running into problems when I try to add a listener to the buttons.

This is my code that I am using to create the buttons, MediaPlayers, and adding listeners. Log cat says there is a null pointer exception at the line where I do one.setOnclickListener(this);

Code:

public class MainActivity extends Activity implements View.OnClickListener{

Button one;
Button two;
Button three;
Button four;
Button five;
Button six;
Button seven;
Button eight;
Button nine;
Button ten;

MediaPlayer hello;
MediaPlayer gatorade;
MediaPlayer haveatit;
MediaPlayer miserable;
MediaPlayer mother;
MediaPlayer stop;
MediaPlayer whatup;
MediaPlayer money;
MediaPlayer yeah;
MediaPlayer science;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (savedInstanceState == null) {
        getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }

    one = (Button) this.findViewById(R.id.one);
    two = (Button) this.findViewById(R.id.two);
    three = (Button) this.findViewById(R.id.three);
    four = (Button) this.findViewById(R.id.four);
    five = (Button) this.findViewById(R.id.five);
    six = (Button) this.findViewById(R.id.six);
    seven = (Button) this.findViewById(R.id.seven);
    eight = (Button) this.findViewById(R.id.eight);
    nine = (Button) this.findViewById(R.id.nine);
    ten = (Button) this.findViewById(R.id.ten);

    hello = MediaPlayer.create(this, R.raw.hello);
    gatorade = MediaPlayer.create(this, R.raw.gatorade);
    haveatit = MediaPlayer.create(this, R.raw.haveatit);
    miserable = MediaPlayer.create(this, R.raw.miserable);
    mother = MediaPlayer.create(this, R.raw.motherofgod);
    stop = MediaPlayer.create(this, R.raw.stopwhining);
    whatup = MediaPlayer.create(this, R.raw.whatup);
    money = MediaPlayer.create(this, R.raw.wheresmymoney);
    yeah = MediaPlayer.create(this, R.raw.yeah);
    science = MediaPlayer.create(this, R.raw.yeahscience);

    one.setOnClickListener(this);
    two.setOnClickListener(this);
    three.setOnClickListener(this);
    four.setOnClickListener(this);
    five.setOnClickListener(this);
    six.setOnClickListener(this);
    seven.setOnClickListener(this);
    eight.setOnClickListener(this);
    nine.setOnClickListener(this);



}

Any Idea why I am getting a null pointer exception on start up?

Stack Trace: Couldn't add it as code http://imgur.com/dwrYOV9

役に立ちましたか?

解決

Fixed!

I took out the listeners, and in the XML file I just added android:onClick="playSound" for each button and created ten methods to handle the ten different sounds!

Thanks for helping me anyways!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top