为什么没有这项工作 - 机器人 - 的onCreate() [英] Why does not this work - Android - onCreate()

查看:89
本文介绍了为什么没有这项工作 - 机器人 - 的onCreate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面code不工作,并抛出造成的NullPointerException一个RuntimeException

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);
     }

当我搬到了 this.typeSelection 初始化里面的onCreate(),它的伟大工程。

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

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

为什么是空指针错误?内联声明中的第一块code,只要调用构造函数发生了,然后的onCreate()访问的对象,不是吗?

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 要求你传递一个的 上下文 。这是一个Android的生命周期对象,而不是一个Java对象。当声明直接初始化领域,这将是使用Java的默认构造函数初始化。然而,你得到的就只是一个背景下,一旦的onCreate 生命周期的方法时,这是非常非常晚和部分Android系统,而不是Java。所以,当你调用的LinearLayout构造与,Android正在期待一个参照上下文,你只能得到调用的onCreate后。

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.

这篇关于为什么没有这项工作 - 机器人 - 的onCreate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆