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 ?
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.
SetContentView(View, ViewGroup+LayoutParams)Set the activity content from a layout resource.
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.
onCreate() It is called when the activity is first created.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With