13

I want to map the buttons to an array of buttons and the code has no errors while compiling but there is force close when i run it:

Button buttons[];

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

    // Set OnClick listeners
    Button buttons[] = null; 
    buttons[0] = (Button)findViewById(R.id.buttonOne);
    buttons[1] = (Button)findViewById(R.id.buttonTwo);
    buttons[2] = (Button)findViewById(R.id.buttonThree);
    buttons[3] = (Button)findViewById(R.id.buttonFour);
    buttons[4] = (Button)findViewById(R.id.buttonFive);
    buttons[5] = (Button)findViewById(R.id.buttonSix);
    buttons[6] = (Button)findViewById(R.id.buttonSeven);
    buttons[7] = (Button)findViewById(R.id.buttonEight);
    buttons[8] = (Button)findViewById(R.id.buttonMid);
}

LogCat:

03-26 21:42:51.455: D/dalvikvm(1156): GC_EXTERNAL_ALLOC freed 55K, 53% free 2566K/5379K, external 1625K/2137K, paused 98ms
03-26 21:42:54.323: D/AndroidRuntime(1156): Shutting down VM
03-26 21:42:54.323: W/dalvikvm(1156): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-26 21:42:54.343: E/AndroidRuntime(1156): FATAL EXCEPTION: main
03-26 21:42:54.343: E/AndroidRuntime(1156): java.lang.RuntimeException: Unable to start activity ComponentInfo{edu.project.superwordwheel/edu.project.superwordwheel.GameView}: java.lang.NullPointerException
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.os.Looper.loop(Looper.java:123)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread.main(ActivityThread.java:3683)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at java.lang.reflect.Method.invokeNative(Native Method)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at java.lang.reflect.Method.invoke(Method.java:507)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at dalvik.system.NativeStart.main(Native Method)
03-26 21:42:54.343: E/AndroidRuntime(1156): Caused by: java.lang.NullPointerException
03-26 21:42:54.343: E/AndroidRuntime(1156):     at edu.project.superwordwheel.GameView.onCreate(GameView.java:43)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-26 21:42:54.343: E/AndroidRuntime(1156):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-26 21:42:54.343: E/AndroidRuntime(1156):     ... 11 more
8
  • you have error in line 43 Commented Mar 26, 2013 at 16:20
  • 1
    Put Button[] buttons = new Buttons[9]; instead of Button buttons[] = null. Your reference to the array is null. Commented Mar 26, 2013 at 16:21
  • try use arraylist<Button> or define ur size array like = new Button[9]; Commented Mar 26, 2013 at 16:21
  • 1
    i am genious :P nah seriously, logcat tells it check this line at edu.project.superwordwheel.GameView.onCreate(GameView.java:43). Commented Mar 26, 2013 at 16:33
  • 1
    I know its really boring to read all those lines, but usually reading logcat is 1/2 of the answer. :) good luck, hope you become pro debugger ;) Commented Mar 26, 2013 at 16:39

6 Answers 6

30

It's usually better if you don't have to hardcode constants like a 9 into your code. And you usually don't need to.

You can for example put the ids into an array and build a dynamically sized List based on them

private List<Button> buttons;
private static final int[] BUTTON_IDS = {
    R.id.buttonOne,
    R.id.buttonTwo, 
    R.id.buttonThree,
    R.id.buttonFour,
    R.id.buttonFive,
    R.id.buttonSix, 
    R.id.buttonSeven,
    R.id.buttonEight,
    R.id.buttonMid,
};

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

    buttons = new ArrayList<Button>();
    // or slightly better
    // buttons = new ArrayList<Button>(BUTTON_IDS.length);
    for(int id : BUTTON_IDS) {
        Button button = (Button)findViewById(id);
        button.setOnClickListener(this); // maybe
        buttons.add(button);
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

@MachMitch not at all. But the performance of adding 10 buttons does not matter at all. Not having to write out all those numbers helps you to prevent errors though.
How to get the position of the button clicked? And also get the button text?
@Rock gist.github.com/zapl/2f94844ef4aef9df6a8206f06c474597 - you can use the view's .getId() method to find out which one it was.
This is a great solution but it would be even nicer if you could make it an array of buttons without having the array of IDS too. Any thoughts on how to do that without the intermediate array, using the same = {} syntax? I've tried without luck.
6

Your array is null and you're trying to get an index into it. That is what's causing the NullPointerException. Your array must be initialized before you can use it to store your buttons.

If you want an array of nine buttons then change this line:

Button buttons[] = null; 

To this:

Button buttons[] = new Button[9];

Also, you have a class member Button buttons[] and a local function variable that is also named Button buttons[]. If this is intentional then by all means carry on. Otherwise, you'll want to further change your line to this:

buttons[] = new Button[9];

1 Comment

Hello, once you declare that array with the new button, how do you declare the buttons then??
3
 Button buttons[] = null; 

button has to be created, using the new operator:

 Button buttons[] = new Button[9];

Comments

3

EXAMPLE USAGE:

Button[] buttons = initializeButtons(3);
buttons[1].setText("I am button1");
buttons[2].setText("I am button2");
buttons[3].setText("I am button3");

FUNCTION:

public Button[] initializeButtons(int x) {
    Resources res = getResources();
    Button[] buttons = new Button[x];
    for (int i = 0; i < x; i++) {
        String b = "button" + i;
        buttons[i] = (Button) findViewById(res.getIdentifier(b, "id", getPackageName()));
    } return buttons;//to prevent array out of bounds exception start from 0
}

NOTE: Make sure in your layout the button id is button1, button2, button3, .. .. etc'

Comments

2

Try the following code:

private int objectLength = 9; //Array elements 

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

    Button[] buttons = new Button[objectLength]; 
    buttons[0] = (Button)findViewById(R.id.buttonOne);
    buttons[1] = (Button)findViewById(R.id.buttonTwo);
    buttons[2] = (Button)findViewById(R.id.buttonThree);
    buttons[3] = (Button)findViewById(R.id.buttonFour);
    buttons[4] = (Button)findViewById(R.id.buttonFive);
    buttons[5] = (Button)findViewById(R.id.buttonSix);
    buttons[6] = (Button)findViewById(R.id.buttonSeven);
    buttons[7] = (Button)findViewById(R.id.buttonEight);
    buttons[8] = (Button)findViewById(R.id.buttonMid);
}

Comments

0

I had situation like this, I chose different approach. I stored id into integer array.

Int[] btnarr = new int[3];

btn[0]=R.id.button1; // give your ID 

Button btn = (Button).findViewById(cc[i]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.