27 December 2010

[Newbie] NullPointerException when calling findViewById

Well this one really took me quiet some time to solve it. When ever I called findViewById whitin my Activity I got a bloody NullPointerException :(

Here is the code that causes the NullPointerException.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <-- That causes the NullPointerException

        setContentView(R.layout.display);        
    }
} 
 
The solution of course is very easy and was mainly caused by the lack of my Android knowledge. Android of course only can access elements within a layout after it the layout is explicitly set. Therefore I had to set the layout using setContentView(..) and after that the Activity can access the TextView targetDisplay. So the fix was unbelievably easy as you can see in the listing below.

public class DisplayActivity extends Activity {

    private final String TAG = "DisplayActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.display); // do this first

        TextView target = (TextView) findViewById(R.id.targetDisplay);
        target.setText(text); // <--No NullPointerException anymore                
    }
}