Why this work does not work - Android - onCreate ()

The following code does not work and throws a RuntimeException thrown by a 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 this.typeSelectioninside onCreate (), it works fine.

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

Why is a null pointer error? An inline declaration in the first code snippet occurs as soon as the constructor is called, and then the onCreate () object has access to the object, right?

+3
source share
1 answer

LinearLayout Context. Android, Java. Java . , onCreate, , Android, Java. , LinearLayout this, Android , onCreate.

+3

Source: https://habr.com/ru/post/1756931/


All Articles