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 a Simple Android App with Java Basic Android Programming Adding the OnClick Method

App crashes when launching to test OnClickListener

public class FunFactsActivity extends AppCompatActivity { // Declare our View variables private TextView factTextView; private Button showFactButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fun_facts_activity);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, FunFactsFragment.newInstance())
                .commitNow();
    }

    factTextView = findViewById(R.id.factTextView);
    showFactButton = findViewById(R.id.showFactButton);

    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // The button was clicked, so update the fact TextView with a new fact
            String fact = "Ostriches can run faster than horses";
            factTextView.setText(fact);
        }
    };
    showFactButton.setOnClickListener(listener);

    // Assign the Views from the layout file to the corresponding variables

}

}

This is the code I have and it appears to be slightly different from the video. My auto-generated code included the "if (savedInstanceState == null)" part and the video did not. I did not pay much attention to this and just proceeded to write the code underneath. Every time I launch the app, it instantly crashes.

1 Answer

Hmm... You're creating a fragment but we're not using any in that app. Just remove your if block. This one:

if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, FunFactsFragment.newInstance())
                .commitNow();
    }

It should work. Your project should have 3 classes: ColorWheel, FactBook and FunFactsActivity, and 1 XML file: activity_fun_facts.xml. No fragment. Hope this helps.

Yeah I think I had a major brain fart. Instead of choosing the template chosen in the video, i chose the one with the fragment included. Gotta rewrite all this stuff, but it all makes sense now.

It happens to the best of us :)