简体   繁体   中英

Runnable works when declared in method; crashes when declared outside of method

I'm new to 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:

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:

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.

Second, do not call inherited methods on your Activity , like findViewById() , until inside of onCreate() , and usually after the super.onCreate() call. onResume() is called after onCreate() completes, which is why your first edition survives better.

Third, specifically with findViewById() , you need to call that after the widget already exists. That will not occur until setContentView() or equivalent means of setting up your UI.

Mixing Sotirios Delimanolis' and CommonsWare's responses here:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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