werck
werck

Reputation: 75

setOnClickListener on Button - program crashes

I'm developing a game for android, and currently I'm doing the menu part of the program. But I have a little problem.

If I add a setOnClickListener to the program, the program crashes.

<!-- language: lang-java -->
public class MakeLoveMenu extends Activity {
    /* 0 = New 1 = Load 2 = Statistics 3 = Exit */
    Button[] buttons;

    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);  
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_love_menu);

        buttonListeners();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.make_love_menu, menu);
        return true;
    }

    public void buttonListeners() {
        buttons[0] = (Button) findViewById(R.id.button_StartNewGame);
        buttons[1] = (Button) findViewById(R.id.button_ContinueGame);
        buttons[2] = (Button) findViewById(R.id.button_Stats);
        buttons[3] = (Button) findViewById(R.id.button_Exit);

        buttons[0].setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });

        buttons[1].setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });

        buttons[2].setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });

        buttons[3].setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                finish();
                System.exit(0);
            }
        });
    }
}

Can you find any errors? Maybe there's a problem with the array handling? Thanks for your answer!

Upvotes: 0

Views: 198

Answers (1)

mrcaramori
mrcaramori

Reputation: 2503

Based on your code, Button[] buttons is never instantiated, so, you would need something like:

Button[] buttons = new Button[4];

You can't access an array position that doesn't exist, since in your method buttonListeners() you are considering the existence of 4 positions (0 to 3), you need to create them before accessing.

Upvotes: 4

Related Questions