Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

An error Occurring in the Fun Facts app... Says Textview has to be declared as final. But that also gives an error

Hey guys the error occurs in the last line of code. This android project was thought in the video. But i tried to make me own program...

the error pops up on the line factOutput.setText(newFact);

says "Variable factOutput is accessed from within inner class, needs to be declared as final"

public class MainActivity extends ActionBarActivity {

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

    TextView factOutput;
    Button Fact_Button;
    Random randomGenrator = new Random();
    final int randomNumber = randomGenrator.nextInt();
    Fact_Button=(Button) findViewById(R.id.factButton);
    factOutput = (TextView) findViewById(R.id.funFact);

    Fact_Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String[] facts={"India is the most improving country in the world",
                            "fact1",fact2","fact3","fact4"};
            String newFact;

            newFact= facts[randomNumber];
            factOutput.setText(newFact);

        }
    });

}

1 Answer

Hao Tran
Hao Tran
17,333 Points

In all of the project videos, most of the variables and objects are declared in the Activity, rather than in the onCreate method of the activity.

If you're using the videos here as a template, just move the lines where you declared factOutput & Fact_Button above the onCreate method (but still in your MainActivity or whatever activity you're in).

Thank you so much :)