计时器任务上的NULL指针异常

时间:2014-06-15 08:16:47

标签: android timer timertask

我有一个图像视图,我有三张图片,我希望图像每隔3秒自动更改一次,我已经使用计时器任务来执行此操作,这是我的代码:

public class MainActivity extends Activity {
    private ImageView frame;
    private int[] images = {R.drawable.boz_43, R.drawable.boz_42, R.drawable.boz_44};
    Timer timer;
    int i=0;
     private TimerTask updateTask;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = (ImageView)findViewById(R.id.imageView1);
         timer = new Timer("TweetCollectorTimer");
         timer.schedule(updateTask, 6000L, 3000L);

         updateTask = new TimerTask() {

             @Override
             public void run() {

                MainActivity.this.runOnUiThread(new Runnable() {

                     @Override
                     public void run() { // TODO Auto-generated method stub
                         frame.setImageResource(images[i]);
                         i++;
                         if (i > 3)
                         {
                             i = 0;
                         }//if
                     }//run

                 });//runnable
             }
         };//timer task
    }
}

但每次我运行我的代码时我都面临崩溃,它给了我一个致命的例外: 它说:

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidanim/com.example.androidanim.MainActivity}: java.lang.NullPointerException
Caused by: java.lang.NullPointerException
at java.util.Timer.scheduleImpl(Timer.java:570)
at java.util.Timer.schedule(Timer.java:481)
at com.example.androidanim.MainActivity.onCreate(MainActivity.java:26)

和26行是:

timer.schedule(updateTask, 6000L, 3000L);
你可以帮我吗???

2 个答案:

答案 0 :(得分:2)

您在创建之前使用updateTask。只需致电

timer.schedule(updateTask, 6000L, 3000L);

之后

 updateTask = new TimerTask() { ..

答案 1 :(得分:0)

您的updateTask为空。在发起timer.schedule(updateTask, 6000L, 3000L);后使用updateTask

因此请使用onCreate作为

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        frame = (ImageView)findViewById(R.id.imageView1);
         timer = new Timer("TweetCollectorTimer");


         updateTask = new TimerTask() {

             @Override
             public void run() {

                MainActivity.this.runOnUiThread(new Runnable() {

                     @Override
                     public void run() { // TODO Auto-generated method stub
                         frame.setImageResource(images[i]);
                         i++;
                         if (i > 3)
                         {
                             i = 0;
                         }//if
                     }//run

                 });//runnable
             }
         };//timer task
          timer.schedule(updateTask, 6000L, 3000L);
    }