简体   繁体   English

在方法中声明时可运行的作品; 在方法外声明时崩溃

[英]Runnable works when declared in method; crashes when declared outside of method

I'm new to Android. 我是Android新手。

I want to modify the TextView of my activity after a few seconds (it says "hey hey!" at first; I want it to say "hello!" after a few seconds), so I have: 我想在几秒钟后修改我的活动的TextView(首先说“嘿,嘿!”;几秒钟后我想说“你好!”),所以我有:

protected void onResume() {
    super.onResume();

    final TextView t = (TextView)findViewById(R.id.hello);
    Runnable changeTextTask = new Runnable() {
        public void run() {
            t.setText("hello!");
        }
    };

    Handler h = new Handler();
    h.postDelayed(changeTextTask, 3000);
}

Which works. 哪个有效。 However, when I declare the Runnable at the beginning of the class, like so: 但是,当我在课程开始时声明Runnable时,如下所示:

public class MainActivity extends ActionBarActivity {
    final TextView t = (TextView)findViewById(R.id.hello);
    Runnable changeTextTask = new Runnable() {
        public void run() {
            t.setText("hello!");
        }
    };

    .
    .
    .

    protected void onResume() {
        super.onResume();

        Handler h = new Handler();
        h.postDelayed(changeTextTask, 3000);
    }

the app crashes upon starting. 该应用程序在启动时崩溃。 Can anyone explain why this happens/what I'm doing wrong? 谁能解释为什么会这样/我在做什么错?

what I'm doing wrong? 我做错了什么?

First, use LogCat to examine the Java stack trace of your crash. 首先, 使用LogCat检查崩溃的Java堆栈跟踪。

Second, do not call inherited methods on your Activity , like findViewById() , until inside of onCreate() , and usually after the super.onCreate() call. 其次,不要在Activity上调用继承的方法,例如findViewById() ,直到onCreate()内部,并且通常在super.onCreate()调用之后。 onResume() is called after onCreate() completes, which is why your first edition survives better. onCreate()完成之后调用onResume() ,这就是为什么您的第一版可以更好地onCreate()原因。

Third, specifically with findViewById() , you need to call that after the widget already exists. 第三,特别是使用findViewById() ,您需要在小部件已经存在之后调用它。 That will not occur until setContentView() or equivalent means of setting up your UI. 直到setContentView()或用于设置UI的等效方法后,这种情况才会发生。

Mixing Sotirios Delimanolis' and CommonsWare's responses here: 在这里混合了Sotirios Delimanolis和CommonsWare的响应:

LogCat reveals findViewByID() caused a NullPointerException because it was called before onCreate() (where the resource with the TextView is loaded) as soon as the activity starts. LogCat显示findViewByID()导致NullPointerException,因为在活动开始后就在onCreate()(带有TextView的资源已加载到其中)之前调用了它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM