[Solved] Why can’t i call a method within a protected method of the same class [duplicate]


You are creating local variables of button1, button2 etc inside the onCreate method. This way, the generateQuestion method is unaware of these variables and uses the class variables with the same name (not included in your code, but I imagine you have somewhere declared them probably on top of your activity class) which are not initialized hence you get the NullPointerException.

Try changing your generateQuestion to:

public void generateQuestion(Button button1, Button button2, Button button3, Button button4) {

   Random rand = new Random();
   int a = rand.nextInt(21);
   int b = rand.nextInt(21);

   question.setText(Integer.toString(a) + "+" + Integer.toString(b));
   int locationOfCorrectAnswer = rand.nextInt(4);

   int incorrectAnswer;

   for (int i = 0; i < 4; i++) {

       if (i == locationOfCorrectAnswer) {
           answers.add(a + b);
       } else {
           incorrectAnswer = rand.nextInt(41);
           while (incorrectAnswer == a + b) {

               incorrectAnswer = rand.nextInt(41);

           }
           answers.add(incorrectAnswer);
       }
   }
   button1.setText(Integer.toString(answers.get(0)));
   button2.setText(Integer.toString(answers.get(1)));
   button3.setText(Integer.toString(answers.get(2)));
   button4.setText(Integer.toString(answers.get(3)));


}

and call it from onCreate like this:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    goButton = (Button) findViewById(R.id.goButton);
    question = (TextView) findViewById(R.id.question);
    pagetimer = (TextView) findViewById(R.id.pagetimer);
    noIndiacator = (TextView) findViewById(R.id.noIndiacator);
    resulttext = (TextView) findViewById(R.id.noIndiacator);
    Button button1 = (Button) findViewById(R.id.button1);
    Button button2 = (Button) findViewById(R.id.button2);
    Button button3 = (Button) findViewById(R.id.button3);
    Button button4 = (Button) findViewById(R.id.button4);

    generateQuestion(button1, button2, button3, button4);

}

This way you will pass the local variables inside the generateQuestion method.

1

solved Why can’t i call a method within a protected method of the same class [duplicate]