1

I'm making a quiz app and while my Toast Method worked the first time I ran it, it's not now that I've changed some of the code. It now tells me that it cannot resolve the Toast Method. I'm not sure what I am missing. Any help would be greatly appreciated.

    submit = (Button) findViewById(R.id.score);
    submit.setOnClickListener(new View.OnClickListener() {
        @Override public void onClick(View v) {
            int correctAnswers = 0;

            if (q1.isChecked()) {
                correctAnswers += 1;
            }
            if (q2Box1.isChecked() || q2Box3.isChecked()) {
                correctAnswers += 1;
            }
            if (q3.isChecked()) {
                correctAnswers += 1;
            }
            if (q5.isChecked()) {
                correctAnswers += 1;
            }

            String q4Text = q4.getText().toString();
            if (q4Text.equals(String.valueOf(correctAnswers))) {
                correctAnswers += 1;
            }

            // Show score message as a toast
            Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
            // Exit this method early because there's nothing left to do
            return;
        }
        });}}
Ms_Lese
  • 13
  • 5

2 Answers2

1

You have changed scopes this is the OnClickListerner. Use getApplicationContext() ->

Toast.makeText(getApplicationContext(), "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • it worked! How did you know that!?! Thank you so much! I'm taking a 10-month course in 2 months, so I'm on information overload and got really stuck. I hope in time that it will come easily to me! Thanks again! – Ms_Lese Mar 11 '18 at 22:25
  • It's all about experience. Also you might check out this https://stackoverflow.com/questions/10347184/difference-and-when-to-use-getapplication-getapplicationcontext-getbasecon for more information when to use what context. Because there are several options ;) – leonardkraemer Mar 11 '18 at 22:28
1

Try this:
Toast.makeText(YourActivity.this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();

Luca Fonta
  • 59
  • 5