web-dev-qa-db-fra.com

Tableau de boutons dans Android

Je veux mapper les boutons sur un tableau de boutons et le code n'a aucune erreur lors de la compilation, mais la force est proche lorsque je l'exécute:

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
9
Mach Mitch

Votre tableau est nul et vous essayez d'y insérer un index. C'est ce qui cause la NullPointerException. Votre tableau doit être initialisé avant de pouvoir l’utiliser pour stocker vos boutons.

Si vous voulez un tableau de neuf boutons, changez cette ligne:

Button buttons[] = null; 

Pour ça:

Button buttons[] = new Button[9];

En outre, vous avez un membre de classe Button buttons[] et une variable de fonction locale également nommée Button buttons[]. Si cela est intentionnel, alors continuez. Sinon, vous voudrez changer votre ligne en ceci:

buttons[] = new Button[9];
6
Michael Celey

Il est généralement préférable de ne pas coder en dur des constantes comme un 9 dans votre code. Et vous n'en avez généralement pas besoin.

Vous pouvez par exemple placer les identifiants dans un tableau et construire une List de taille dynamique basée sur eux

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);
    }
}
25
zapl
 Button buttons[] = null; 

le bouton doit être créé en utilisant l'opérateur new:

 Button buttons[] = new Button[9];
3
Blackbelt

Essayez le code suivant:

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);
}
2
NullPointer

Exemple d'utilisation:

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

UNE FONCTION:

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: Assurez-vous que dans votre mise en page, l'id du bouton est button1, button2, button3, .. .. etc '

2
Liquid44

J'ai eu la situation comme ça, j'ai choisi une approche différente. J'ai stocké id dans un tableau entier.

Int[] btnarr = new int[3];

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

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