TextView.setText


Last Updated:

  1. Engmex

    Engmex Member

    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:eek:rientation="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");

    Advertisement
  2. hiephm

    hiephm New Member

    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()
    vladimirov and Engmex like this.
  3. Engmex

    Engmex Member

    yes I worked it out myself (see my update), but thanks for the reply
    Regards
    vladimirov likes this.

Share This Page