Android应用程序在向按钮添加侦听器时崩溃

时间:2014-03-27 01:43:36

标签: android button listener

我正在制作一个音板应用,当我尝试为按钮添加一个监听器时,我一直遇到问题。

这是我用来创建按钮,MediaPlayers和添加监听器的代码。 Log cat说我在one.setOnclickListener(this);

的行上有一个空指针异常

代码:

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);



}

任何想法为什么我在启动时获得空指针异常?

堆栈跟踪: 无法将其添加为代码 http://imgur.com/dwrYOV9

1 个答案:

答案 0 :(得分:0)

固定!

我拿出了监听器,在XML文件中我为每个按钮添加了android:onClick="playSound"并创建了十种方法来处理十种不同的声音!

感谢您的帮助!