Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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?

MainActivity.java
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);

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

        // 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 !