title: Creating array of buttons, then making one onClick event for all
body: <p>I am trying to create array of buttons, then making one onClick event for all, here is my code, when I run the code I get (The application testing(processcom.MyTest.testing) has stopped unexpectedly. Please try again) I am not sure what, where is the error. I must be missing something fundamental, I am not trying to create app, I am just leanring Java, specially for Android.</p>
  
  <p>Here is my code</p>
  
  <pre><code>package com.MyTest.testing;
  
  
  import static android.widget.Toast.makeText;
  import java.util.Random;
  import android.app.Activity;
  import android.media.MediaPlayer;
  import android.os.Bundle;
  import android.widget.Button;
  import android.widget.TextView;
  import android.widget.Toast;
  import android.view.View;
  import android.view.View.OnClickListener;
  
  
  public class TreActivity extends Activity {
        /** Called when the activity is first created. */
  //declaring some public int vars
  
  int isPressed1 = 1;
  int isPressed2 = 1;
  int isPressed3 = 1;
  int isPressed4 = 1;
  int isPressed5 = 1;
  int isPressed6 = 1;
  int isPressed7 = 1;
  int isPressed8 = 1;
  int isPressed9 = 1;
  int isPressed10 = 1;
  
  
  
  
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
  
  
     myMethod();
  
  
  
  
  
  }; //End of onCreate (Bundle savedInstanceState) 
  
  public void myMethod() { 
      MyClickHandler handler = new MyClickHandler();  
  
      Button[] buttons = fnButtonArray();
      for (Button button : buttons) {  
         button.setOnClickListener(handler);  
         }  
   }  
  
  
  class MyClickHandler implements View.OnClickListener {  
        public void onClick(View v) { 
          Toast.makeText(TreActivity.this, ((Button) v).getText() , Toast.LENGTH_SHORT).show();
        }  
   }
  
  
  public Button[] fnButtonArray(){
  
      Button arrButtons[] = new Button[11];
        // started with 1 not 0 for the array to match the button numbers
      arrButtons[1] = (Button) findViewById(R.id.btn1);
      arrButtons[2] = (Button) findViewById(R.id.btn2);
      arrButtons[3] = (Button) findViewById(R.id.btn3);
      arrButtons[4] = (Button) findViewById(R.id.btn4);
      arrButtons[5] = (Button) findViewById(R.id.btn5);
      arrButtons[6] = (Button) findViewById(R.id.btn6);
      arrButtons[7] = (Button) findViewById(R.id.btn7);
      arrButtons[8] = (Button) findViewById(R.id.btn8);
      arrButtons[9] = (Button) findViewById(R.id.btn9);
      arrButtons[10]= (Button) findViewById(R.id.btn10);
      return arrButtons;
  
    }
    } //public class TreActivity extends Activity
  </code></pre>