• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps TextView.setText

Engmex

Lurker
Hi I'm very new to Android development so forgive my innocence. Why does this simple program crash on the TextView.setText method ?
package com.example.testsettext;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class TestSetText extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv1 = (TextView) findViewById(R.id.TextView01);
tv1.setText("Display This Text in the Text View");
setContentView(R.layout.main);
}
}

and the XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView android:text="@+id/TextView01" android:id="@+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>

Regards!

Update: Ok I solved it myself I need to put setText after setContentView like this:
setContentView(R.layout.main);
TextView tv1 = (TextView) findViewById(R.id.TextView01);
tv1.setText("Display This Text in Text View");
 
You must call
setContentView(R.layout.main);
before
TextView tv1 = (TextView) findViewById(R.id.TextView01);
otherwise tv1 will be null and you will get NullPointerException when calling tv1.setText()
 
You must call
setContentView(R.layout.main);
before
TextView tv1 = (TextView) findViewById(R.id.TextView01);
otherwise tv1 will be null and you will get NullPointerException when calling tv1.setText()
yes I worked it out myself (see my update), but thanks for the reply
Regards
 
Back
Top Bottom