views:

117

answers:

1

I'm attempting Google University Android lab1 you are asked to change a TextView's text content according to the value passed via the Intent from another activity.

I tried out the rest of my code but... why does my app force close when I add the "tv.settext(...) line"?

public class HelloWorld extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /*
         * Fetch and display passed string.
         */
        TextView tv = (TextView) findViewById(R.id.HelloTV);
        Bundle extras = this.getIntent().getExtras();
        if (extras != null) {
            String nameStr = extras.get("Username").toString();
            if (nameStr != null) {
                tv.setText("Hello "+nameStr);         
            }
        }
        setContentView(R.layout.main);
    }
}
+2  A: 

Looking at the error log, and even better, looking at a debug session - it can be seen that there is a null pointer exception on line 22:

           tv.setText("Hello "+nameStr);         

This is because tv == null. It should have been initialised by the line:

    TextView tv = (TextView) findViewById(R.id.HelloTV);

but to use the id in the layout you must always register the view in the current activity. This line should have been included early in the onCreate method:

    setContentView(R.layout.main);

Here is the working Helloworld class:

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

        /*
         * Fetch and display passed string.
         */
        TextView tv = (TextView) findViewById(R.id.HelloTV);
        Bundle extras = this.getIntent().getExtras();
        if (extras != null) {
            String nameStr;
            if (extras.get("Username") != null) {
                nameStr = extras.get("Username").toString();
                tv.setText("Hello "+nameStr);           
            }
        }
    }
}

This Helloworld class correctly retrieves the user's name from the extras sent when the activity starts and displays a personalised greeting.

I found the answer thanks to Konstantin Burov and the previous question here

Dizzley