TextView.setText (Android) is crashing .. any idea why?

Trying to get started with Android development and do basic work with TextViews.

For some reason, the TextView setText () method is causing huge problems for me .. here is 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 fail, and I don’t understand why .. if I create a TextView inside onCreate, it works fine, but if I create it outside it is not .. why? Has the string "TextView text"; not done yet or something else?

Thanks!

+8
android string textview settext
source share
4 answers

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

 setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.text1); text.setText("literally anything"); 
+9
source share

switch these 2 lines

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

you need to install the content first

+3
source share

From the docs:

onCreate (Bundle) is where you initialize your activity. Most importantly, here you usually call setContentView (int) using a layout resource that defines your user interface, and using findViewById (int) to get widgets in this user interface that you need to interact with programmatically.

So this means that if you are referencing your views in a layout, you must first set the content view and then call the findViewById method to reference the child views of the layout resource that define your activity user interface

+2
source share
 text = (TextView) findViewById(R.id.text1); setContentView(R.layout.activity_main); text.setText("literally anything"); 

If “literally anything” is a variable that can often occur, make sure it does not throw a NullPointerException. I had a problem all the time. I fixed it as:

  text = (TextView) findViewById(R.id.text1); setContentView(R.layout.activity_main); try { text.setText("literally anything"); } catch (NullPointerException e) { // Do something } 

Exceptions can be really useful, so if you are a beginner programmer, I suggest you quickly place exception handling in the list of things.

+1
source share

All Articles