TextView.setText (Android) is causing crashes.. any idea why?

Zeldarulah picture Zeldarulah · Aug 8, 2013 · Viewed 15.7k times · Source

Trying to get started with Android development, and doing some basic work with TextViews..

For some reason TextView's setText() method is causing huge problems for me.. here's a simplified version of my code to show what I mean:

package com.example.testapp;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {

    TextView text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        text = (TextView) findViewById(R.id.text1);  
        setContentView(R.layout.activity_main);
        text.setText("literally anything");
    }
}

This will cause a crash, and I don't understand why.. if I create the TextView within the onCreate it works just fine, but if I create it outside of it, it doesn't.. why is that? Has the line "TextView text;" not been executed yet or something?

Thanks!

Answer

Philipp Jahoda picture Philipp Jahoda · Aug 8, 2013

You need to call setContentView() before initializing the TextView so that your Activity has access to all the layout components.

setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);  

text.setText("literally anything");