1. Download our Official Android App: Forums for Android!

Apps TextView.setText

Discussion in 'Android Development' started by Engmex, Sep 16, 2010.

  1. Engmex

    Engmex Lurker
    Thread Starter
    Rank:
    None
    Points:
    6
    Posts:
    5
    Joined:
    Sep 16, 2010

    Sep 16, 2010
    5
    1
    6
    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 Lurker
    Rank:
    None
    Points:
    6
    Posts:
    2
    Joined:
    Sep 16, 2010

    Sep 16, 2010
    2
    3
    6
    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 Lurker
    Thread Starter
    Rank:
    None
    Points:
    6
    Posts:
    5
    Joined:
    Sep 16, 2010

    Sep 16, 2010
    5
    1
    6
    yes I worked it out myself (see my update), but thanks for the reply
    Regards
     
    vladimirov likes this.

Share This Page

Loading...