收录日期:2019/06/20 01:39:48 时间:2010-07-28 12:46:03 标签:android,initialization,android-activity

The following code does not work, and throws a RuntimeException caused by NullPointerException

public class ListFilteredActivity extends Activity {
    LinearLayout typeSelector = new LinearLayout(this) ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         ScrollView sv = new ScrollView(this);
         this.setContentView(sv);
         //this.typeSelector = new LinearLayout(this);
         this.typeSelector.setOrientation(LinearLayout.VERTICAL);
         sv.addView(this.typeSelector);
     }

When I moved the initialization of this.typeSelection inside onCreate() it works great.

    @Override
    public void onCreate(Bundle savedInstanceState) {
       ...
       this.typeSelector = new LinearLayout(this);
       ...
    }

Why is the null pointer error? The inline declaration in the first piece of code happens as soon as constructor is called, and then the onCreate() has access to the object, isn't it?

LinearLayout requires you pass in a Context. This is an Android lifecycle object and not a Java object. When declaring and initializing the field directly, this will be initialized using the Java default constructor. However you'll only get a context once the onCreate lifecycle method occurs, which is much, much later and part of Android, not Java. So when you call the LinearLayout constructor with this, Android is expecting a reference to a Context, which you only get after the call to onCreate.