29

I'm trying to change my TextView text from the code.

This is what my xml looks like:

XML:
<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|center_horizontal" />

And the code:

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");
setContentView(tv1);

I'm getting an error on my device and the application stops. I tried to show a TextView (not connected to an XML TextView) and it worked.

Alex K
  • 8,269
  • 9
  • 39
  • 57
Imri Persiado
  • 1,857
  • 8
  • 29
  • 45

3 Answers3

72

Your approach is incorrect. I think it will be Null Pointer Exception (next time post log cat)

You need to specify the layout you are using first, before finding views.

Java:

// Specify the layout you are using.
setContentView(R.layout.yourlayout);

// Load and use views afterwards
TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");

Kotlin:

// Specify the layout you are using.
setContentView(R.layout.yourlayout)

// Load and use views afterwards
val tv1: TextView = findViewById(R.id.textView1)
tv1.text = "Hello"

Click Here to study exactly you want to know

ChrisMcJava
  • 2,145
  • 5
  • 25
  • 33
Abhi
  • 8,935
  • 7
  • 37
  • 60
  • @ImriPersiado Then you can accept the answer,Just by tick mark which is at left side of my answer :P – Abhi Nov 19 '12 at 11:59
  • @ChrisMcJava - Shouldn't the Kotlin version using synthetic? – charles-allen Apr 03 '20 at 01:02
  • 1
    @AjahnCharles: Kotlinx synthetic is no longer recommended standard practice: https://android-review.googlesource.com/c/platform/frameworks/support/+/882241 Explanation from Android at Google: https://www.reddit.com/r/androiddev/comments/ala9p2/why_kotlinx_synthetic_is_no_longer_a_recommended/efdvpkg/ – ChrisMcJava Apr 03 '20 at 17:30
5

remove this.. setContentView(tv1);

Henrik
  • 339
  • 3
  • 13
3

I got the same problem. My app was stopping too. Actually, I was writing the code outside of the function/method. So to fix this problem, these lines

TextView tv1 = (TextView)findViewById(R.id.textView1);
tv1.setText("Hello");

must be inside a function/method. (can be user defined) (I am new to android studio so I don't know the reason behind the problem but I only know how to fix this. Maybe this helps new ones despite this question being 8 years old.)