PcAF
PcAF

Reputation: 2007

Why must be objects initialized in onCreate?

I have the following code:

public class MainActivity extends Activity {

TextView number=(TextView)findViewById(R.id.number2);
TextView number2=(TextView)findViewById(R.id.number2);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    number.setText("Text");
    number.setText("Text");
}

followed by more code, but when I run it it crashes.

After doing that i tried to initialize TextViews in onCreate()

public class MainActivity extends Activity {

TextView number;
TextView number2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    number=(TextView)findViewById(R.id.number);
    number2=(TextView)findViewById(R.id.number2);
    number.setText("Text");
    number.setText("Text");
}

and it worked. Why must objects be initialized in onCreate?

Upvotes: 1

Views: 57

Answers (1)

laalto
laalto

Reputation: 152817

Your activity won't have a Window until onCreate(). Attempting to find any views before the window is initialized will lead to NPE.

Additionally, attempting to find views before setContentView() will return nulls and so the return values are not good for anything.

Upvotes: 4

Related Questions