3

The setText() method returns null in my application why?

public class GetValue extends Activity {
    char letter = 'g';
    int ascii = letter;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TextView textView = (TextView)findViewById(R.id.txt_1);
            textView.setText(ascii);
    }
}

It doesn't matter what text i put in, it crashes anyway. Why does setText() keep returning null?

Thank you, in advance

Solution: My error was in the xml file. I wrote: android:text="@+id/txt_1" When it should say: android:id="@+id/txt_1"

Thanks a lot for all the answers and comments!

jonas
  • 33
  • 1
  • 1
  • 4

3 Answers3

9

You tried to pass an integer as parameter to setText, which assumes it is a resource ID. To display computed text, pass it as a string: textView.setText("g");

Edited: Check your XML file, I have test with something very basic and it works

<?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:id="@+id/txt_1"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="myTextView"/>
</LinearLayout>

Maybe try to clean your project (Project->Clean in Eclipse), I recently have some trouble with R generation on the last ADT version.

Hrk
  • 2,725
  • 5
  • 29
  • 44
  • I have tried to put in plane text. The only thing i know is that the setText() line makes my program crash. I know it's nothing wrong with my xml file. The logcat says that textView variable returns null. I think i am using the setText() method wrong. –  Mar 16 '11 at 07:05
5

Try this:

textView.setText(Integer.toString(ascii)); 

Also make sure that your layout xml has TextView txt_1

Lumis
  • 21,517
  • 8
  • 63
  • 67
2

I've tried :

Integer.toString(char) and String.valueOf(char)

both didnt work. The only solution is :

txt.setText(""+char);

This is not very efficient from optimization point of view but it does the trick :)

Vitaliy A
  • 3,651
  • 1
  • 32
  • 34