1
public class MainActivity extends FragmentActivity {
    TextView textView = (TextView) findViewById(R.id.textbox);

    //rest of code.........

Above code generates the following exception,

    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
    at android.app.Activity.findViewById(Activity.java:2090)
    at com.example.kuldeep.myapplication.MainActivity.<init> (MainActivity.java:24)

When I debugged this, I come to know that this code is executed even before the onCreate() method. How is this possible? and How to catch this type of exceptions?

  • Probably best to move the initialization to the `onCreate` method. How is it possible that it is called before? Because the code is executed when constructing the object, which has to be done before `onCreate` can even be called. – Jorn Vernee Aug 12 '16 at 19:32
  • in simple words, you should move this code to your onCreate() block. – Somesh Kumar Aug 12 '16 at 19:33

1 Answers1

1

How is this possible?

Because that is what you wrote. Field initializers (e.g., (TextView) findViewById(R.id.textbox)) are executed when the instance of the activity is created.

How to catch this type of exceptions?

You don't. Instead, you avoid the exception. In general, do not call methods that you inherit from Activity from a field initializer. More specifically, you cannot find a widget until the widget exists, and that will not occur until setContentView() is called (or you otherwise set up the UI of this activity).

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491