Prateek Joshi
Prateek Joshi

Reputation: 4067

Where to place setContentView() in onCreate()?

I am a beginner in android and I want to know why is it that when I place my setContentView() after defining the TextView, my app crashes, i.e

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    TextView tv=(TextView) findViewById(R.id.tv);
    Linkify.addLinks(tv, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES|
            Linkify.PHONE_NUMBERS);
    setContentView(R.layout.activity_main);     //After TextView 
}

But when I put my setContentView() before defining the TextView then my app runs fine.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);   //Before TextView
    TextView tv=(TextView) findViewById(R.id.tv);
    Linkify.addLinks(tv, Linkify.WEB_URLS|Linkify.EMAIL_ADDRESSES|
            Linkify.PHONE_NUMBERS);
}

Why it is that & and how adding setContentView() before makes the difference ?

Upvotes: 5

Views: 1763

Answers (3)

Vindhya Pratap Singh
Vindhya Pratap Singh

Reputation: 556

When you are defining setContentView() after you declared TextView you are doing wrong because the object Id that you are initializing in TextView is contained inside that layout is unknown in the class until the seConteView() executed.

Upvotes: 0

Lightsout
Lightsout

Reputation: 3757

You can execute any code you want before the setContentView() method as long as it doesn't refer to (parts of) the View, which isn't set yet.

Since your tv variable refers to the contents of the View, it can't be executed.

Upvotes: 0

Bidhan
Bidhan

Reputation: 10697

setContentView() literally sets the views of your Activity. If you try to do something like TextView tv=(TextView) findViewById(R.id.tv);, then there is no view to find because you haven't set your views yet, and thus your app crashes. This is why you should put setContentView() before you try to access your views.

Upvotes: 10

Related Questions