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?
LinearLayoutrequires you pass in aContext. 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 theonCreatelifecycle method occurs, which is much, much later and part of Android, not Java. So when you call the LinearLayout constructor withthis, Android is expecting a reference to a Context, which you only get after the call to onCreate.