Thursday, August 9, 2012

NullPointerException/IllegalStateException thrown when calling findViewById()


So you're trying to get a reference to a View (TextView, Button, ...etc.) in your Java code using findViewById(). But once you access the view -by calling View.setText() for example-  the application crashes and an 'IlligalStateException' is thrown in LogCat with a 'NullPointerException'  shown in the dump. Here are the two most probable causes of this issue and their solutions:
  1.  Check whether you're calling findViewById() before setContentView(). If so, just place the statement after setContentView(), and you're set.
    You were getting a null in this case because the view you're tying to access from XML is not yet inflated by setContentView(). You can only access a view after it's been inflated on the screen. By calling setContentView() before findViewById(), you guarantee that the view is already inflated.

  2. If you were actually calling findViewById() after setContentView(), but still getting the exception, then you're probably calling the wrong findViewById(). Check which context you have inflated the layout to. For example, if you're building a Dialog from a resource inside an Activity class, then you have to call dialog.getWindow().setContentView(resourceId). Otherwise, you would be calling this.findViewById(), where this refers to the parent Activity and not the built Dialog. Fix this by calling the Dialog's findViewById() to tell Android to look for the resource in the correct inflated layout:
    Dialog dialog = new Dialog(this);
    dialog.setContentView(R.layout.custom_dialog);
    TextView tv = (TextView) dialog.findViewById(R.id.textView1);

No comments:

Post a Comment