javaandroidandroid-layoutandroid-activitytextview

Modifying TextView crashes program


So I've defined a layout in xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center">

    <TextView
        android:id="@+id/char_name"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>

</LinearLayout> 

But when I try to change anything about it in java my program crashes.

public class DisplayMessageActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    TextView charName = (TextView) findViewById(R.id.char_name);
    charName.setText("Bob");
    setContentView(R.layout.displayName);

    }
}

My app compiles and runs, but when it switches to this Activity it crashes. If I set the text in the xml file it works fine.


Solution

  • You haven't set content for the Activity. Add the following in onCreate:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);
    
        TextView charName = (TextView) findViewById(R.id.char_name);
        charName.setText("Bob");
    }
    

    where your_layout.xml is the xml file containing TextView with id char_name.

    NOTE: you should set content before initializing TextView charName.