Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 955
Prateek Joshi Avatar asked Jun 14 '15 11:06

Prateek Joshi


People also ask

Why would you do the setContentView () in onCreate () of activity class?

As onCreate() of an Activity is called only once, this is the point where most initialization should go: calling setContentView(int) to inflate the activity's UI, using findViewById to programmatically interact with widgets in the UI, calling managedQuery(android.

What is a the use of setContentView () method?

SetContentView(View, ViewGroup+LayoutParams)Set the activity content from a layout resource.

How do you use onCreate method?

onCreate(Bundle savedInstanceState) Function in Android:After Orientation changed then onCreate(Bundle savedInstanceState) will call and recreate the activity and load all data from savedInstanceState. Basically Bundle class is used to stored the data of activity whenever above condition occur in app.

What is onCreate () meant for?

onCreate() It is called when the activity is first created.


1 Answers

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.

like image 179
Bidhan Avatar answered Oct 17 '22 22:10

Bidhan