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