随机空指针onTick of countdowntimer

时间:2017-07-21 10:04:04

标签: android exception nullpointerexception android-service

我的问题源于我的倒计时服务课程。 onTick方法抛出随机空指针。足够随机,很难捕捉,但它每次都会崩溃应用程序。 以下是倒计时服务类的代码

  @Override  
     public void onCreate() {
      super.onCreate();

    stopNotify();

    Log.i(TAG, "Starting timer...");

    cdt = new CountDownTimer(900000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            String hms = String.format("%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            MainActivity.tv.setText(hms);
            Log.i(TAG, "Countdown seconds remaining: " + millisUntilFinished / 1000);
            bi.putExtra("countdown", millisUntilFinished);
            sendBroadcast(bi);
        }

        @Override
        public void onFinish() {
            Log.i(TAG, "Timer finished");

            showNotification();

            savepref();



            Intent intent = new Intent(BroadcastService.this, MainActivity.class);


            intent.putExtra("id1",id1);

            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);


            startActivity(intent);





        }
    };

    cdt.start();
}



@Override
public void onDestroy() {
    cdt.cancel();
    Log.i(TAG, "Timer cancelled");
    super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    return START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {

    return null;
}

更多代码     代码!!

       private BroadcastReceiver br = new 
      BroadcastReceiver() 
      { 
       @Override
      public void onReceive(Context context, Intent intent) {
        updateGUI(intent); // or whatever method used to 
        update your GUI fields
        }
        };

       private void updateGUI(Intent intent) {
        if (intent.getExtras() != null) {
        long millisUntilFinished = 
        intent.getLongExtra("countdown", 0);
          Log.i(TAG, "Countdown seconds remaining: " + 
          millisUntilFinished / 1000);
             }
          }

1 个答案:

答案 0 :(得分:0)

虽然,我不知道你的其余代码,但显然问题就在于这一行

MainActivity.tv.setText(hms);

我猜," tv"表示您在MainActivity中的静态变量中使用的文本视图。这变为空..