Marcus
Marcus

Reputation: 522

Why does writing code in onCreate() crash my android program, but the same code works when in onCreateOptionsMenu()?

This is very simple code to replace the default "Hello World!" text generated from creating a new Android project. I've included the TextView tag from my .xml and snippets from MainActivity.java. Ive noted that creating a new Android project creates another project called "appcompat" without which noting at all works. Is there any way to get this code to run from onCreate()? and maybe get rid of appcompat.

Ive noted that on a friends computer where code successfully runs from onCreate(), there is one .xml file; "activity_main" where as I have both, and no mention of appcompat.

Im running OSX Mountain Lion on a rMBP, Eclipse Kepler, up to date Java and android SDKs, basically everything is up to date.

TextView tag from fragment_main.xml

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world"
        android:id="@+id/label1" />

Snippet of code from MainActivity.java file...

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

    // Program crashes with code here ...
    // TextView tv = (TextView) findViewById(R.id.label1);
    // tv.setText("I've replaced the label!");


    if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // ... This works fine
    TextView tv = (TextView) findViewById(R.id.label1);
    tv.setText("I've replaced the label!");

        // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Upvotes: 0

Views: 186

Answers (2)

laalto
laalto

Reputation: 152817

The pending fragment transaction that creates the fragment layout and attaches it to the activity view hierarchy is executed in activity onStart(). onCreateOptionsMenu() is invoked after that. Anything before the fragment transaction is executed is too early.

Note that the transaction code in onCreate() just posts the transaction but does not execute it yet.

Also, from design point of view, consider not having dependencies to fragment internals in an activity. Let the fragment handle its views.

Upvotes: 2

panini
panini

Reputation: 2026

your TextView is contained inside your Fragment, which isn't inflated until this:

getSupportFragmentManager().beginTransaction()
        .add(R.id.container, new PlaceholderFragment()).commit();

line

If you're going to use fragments, then you should put the code that touches the UI inside the Fragment class (in your case, this is PlaceholderFragment.java)

Upvotes: 2

Related Questions