Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does not this work - Android - onCreate()

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?

like image 753
ankitjaininfo Avatar asked Apr 08 '26 14:04

ankitjaininfo


1 Answers

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.

like image 97
JRL Avatar answered Apr 11 '26 03:04

JRL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!