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 Build an Interactive Story App User Input Finding Views by IDs

My findViewById doesn't work.

I just used the same technique I learned from the course when you build your first simple app but it doesn't work. Could someone help me?

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    protected Button exterminateButton;
  exterminateButton = (Button) findViewById(R.id.button1);

    public void onCreate(Bundle savedInstanceState) {

        // Declare our view variables



2 Answers

samuel zaffran
samuel zaffran
24,815 Points

You're trying to declare your view outside the parent view, like you want to refer to something that doesn't yet exist. Instead try to initialize it inside your onCreate method. Got it ? Let me know !

So what I was doing wrong was I declared the view outside the onCreate method whichmeans it basically doesn't exist?

By the way, thank you so much.

samuel zaffran
samuel zaffran
24,815 Points

You'll see it in future courses about the android lifecycle but yes it's something like that, it can't refer to a view without the layout containing this view, when you declare setContentView(R.layout.activity_main); in your onCreate method it sets the layout to this layout and from here you can refer to it ! You're well come !