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 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 :)