0

I tried to set views to Enabled(false), but it keeps giving me this error:

Caused by: java.lang.NullPointerException: Attempt to
invoke virtual method 'void android.widget.Button.setEnabled(boolean)'
on a null object reference

Something I don't understand is that the error didn't occur at ccl_stage11[][] but occured at vtl_stage11 and hrl_stage11[][] even though they're using same for in the same way.

I tried to unroll the 'for' loop at the setEnabled part, but it didn't work. Can anyone help me to solve this problem? Here is the code related to this error.

public class Stage1Activity1 extends AppCompatActivity {

    Button[][] ccl_stage11 = new Button[4][4];
    Button[][] hrl_stage11 = new Button[4][4];
    Button[][] vtl_stage11 = new Button[4][4];



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


        buttonSettings();
}
 protected void buttonSettings() {


        int k = 0;
        for (int i = 1; i <= 3; i++) {
            for (int j = 1; j <= 3; j++) {
                ccl_stage11[i][j] = findViewById(R.id.ccl_stage11_11 + k);
                ccl_stage11[i][j].setEnabled(false);
                k++;
            }
        }
        for (int i = 0; i <= 3; i++) {
            for (int j = 0; j <= 3; j++) {
                vtl_stage11[i][j] = findViewById(R.id.vtl_stage11_00 + k);
                hrl_stage11[i][j] = findViewById(R.id.hrl_stage11_00 + k);
                k++;
            }
        }
        for(int i=0;i<=3;i++){
            for (int j =0;j<=3;j++){
                vtl_stage11[i][j].setEnabled(false);
                hrl_stage11[i][j].setEnabled(false);
            }
        }
        ccl_stage11[1][3].setEnabled(true);
        ccl_stage11[3][1].setEnabled(true);


    }

The error occurs at

for(int i=0;i<=3;i++){
    for (int j =0;j<=3;j++){
        vtl_stage11[i][j].setEnabled(false);
        hrl_stage11[i][j].setEnabled(false);
    }
}
Adil Soomro
  • 37,609
  • 9
  • 103
  • 153
Albert
  • 11
  • 3
  • Please add your XML file too – Iman Nia Feb 09 '20 at 11:13
  • While checking for the `null` might solve your `Exception`, but the problem is still there. Also if you've to show many buttons that do the same tasks, why don't you use `RecyclerView`, `GridView` or `ListView` whichever is appropriate for you? – Adil Soomro Feb 09 '20 at 12:30

1 Answers1

0

Check null's before you do anything.

for(int i=0;i<=3;i++){
    for (int j =0;j<=3;j++){

        // add this condition!
        if(vtl_stage11[i][j] != null) {
            vtl_stage11[i][j].setEnabled(false);
            hrl_stage11[i][j].setEnabled(false);
        }
    }
}
Naveen Niraula
  • 771
  • 10
  • 19