2013-03-26 6 views
7

voglio mappare i tasti per una serie di pulsanti ed il codice non ha errori durante la compilazione, ma non v'è forza vicino quando l'eseguo:Array di pulsanti in Android

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 
+0

avete errore nella linea 43 –

+1

Mettere pulsanti 'tasto [] = nuovi pulsanti [9];' al posto dei bottoni 'tasto [] = null'. Il tuo riferimento alla matrice è nullo. – DeeV

+0

prova ad usare l'arraylist

risposta

5

L'array è nullo e stai cercando di ottenere un indice. Questo è ciò che sta causando lo NullPointerException. L'array deve essere inizializzato prima di poterlo utilizzare per memorizzare i pulsanti.

Se si desidera una serie di nove pulsanti poi cambiare questa linea:

Button buttons[] = null; 

A tal:

Button buttons[] = new Button[9]; 

Inoltre, è un membro della classe Button buttons[] e una variabile di funzione locale che è anche chiamato Button buttons[]. Se questo è intenzionale, allora con tutti i mezzi andare avanti. In caso contrario, ti consigliamo di modificare ulteriormente la linea in questo:

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

pulsante deve essere creato, utilizzando l'operatore di new:

Button buttons[] = new Button[9]; 
2

provare il seguente codice:

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

+1 per la dichiarazione della lunghezza degli elementi. – iSun

22

Di solito è meglio se non c'è bisogno di hardcode costanti come un 9 nella vostra codice. E di solito non ne hai bisogno.

È possibile ad esempio inserire gli ID in un array e costruire un dimensionata in modo dinamico List basata su di essi

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); 
    } 
} 
+0

in che modo l'elenco dinamico aiuta nelle prestazioni? –

+2

@MachMitch per niente. Ma le prestazioni dell'aggiunta di 10 pulsanti non hanno alcuna importanza. Non dover scrivere tutti quei numeri ti aiuta comunque a prevenire errori. – zapl

+0

+1 per usare 'Lista

0

esempio di utilizzo:

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

FUNZIONE:

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 
} 

NOTA : Assicurati che nel tuo layout sia presente l'id del pulsante ton1, button2, button3, .. .. ecc '

0

Ho avuto una situazione come questa, ho scelto un approccio diverso. Ho memorizzato id in array intero.

Int[] btnarr = new int[3]; 

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

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