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 trialYusuf Mohamed
2,631 PointsMy 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);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declare our view variables
}
}
2 Answers
samuel zaffran
24,815 PointsYou'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 !
samuel zaffran
24,815 PointsYou'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 !
Yusuf Mohamed
2,631 PointsYusuf Mohamed
2,631 PointsSo what I was doing wrong was I declared the view outside the onCreate method whichmeans it basically doesn't exist?
Yusuf Mohamed
2,631 PointsYusuf Mohamed
2,631 PointsBy the way, thank you so much.