初始化错误..但我不知道为什么

时间:2018-12-12 02:14:23

标签: android

我必须每fragment使用倒数计时器。同样,在每个fragments中,每个计时器都必须实现多次。

所以我制作了如下的Timer类

public class Timerset {
private int max;
private Timer timer;
private TimerTask timerTask;
private boolean isPause = false;

private TimerListener listener;

public Timerset(int maxSecond, final TimerListener timerListener){
    this.max = maxSecond;
    this.listener = timerListener;
    timer = new Timer();
    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            if(!isPause){
                if(listener!= null){
                    listener.setTime(max);
                }
                if(max==0){
                    timer.cancel();
                }else{
                    max--;
                }
            }
        }
    };
}

public void start(){
    timer.schedule(timerTask,0,1000);
}

public void stop(){
    timer.cancel();
}

public void pause(){
    isPause = true;
}

public void resume(){
    isPause = false;
}

public interface TimerListener{
    void setTime(int sec);
}
}

我使用onCreateView片段方法中的带参数new来创建对象。 像下面一样

全局变量。 : Timerset timerset1timerset2timerset3timerset4

timerset1 = new Timerset(45, this);
timerset2 = new Timerset(45, this);
timerset3 = new Timerset(45, this);
timerset4 = new Timerset(45, this);

我必须在开始的时候调用start()的{​​{1}}方法。

Timerset
  

java.lang.NullPointerException:尝试在上调用虚拟方法'void com.example.sinjihye.tossoneshot.TimerPackage.Timerset.setTimerListener(com.example.sinjihye.tossoneshot.TimerPackage.Timerset $ TimerListener)空对象引用           在com.example.sinjihye.tossoneshot.ActualTestPackage.Part1QuestionFragment.onCreateView(Part1QuestionFragment.java:74)

1 个答案:

答案 0 :(得分:0)

与启动方法一样:

public void start(){
timer.schedule(timerTask,0,1000);
}

timerTask是来自您的TimerSet类的引用。在TimerSet类构造函数中,将TimerTask初始化为Local变量。将其更改为TimerSet类的实例变量。像这样:

TimerTask timerTask;
public Timerset(int maxSecond, final TimerListener timerListener){
this.max = maxSecond;
this.listener = timerListener;
timer = new Timer();
timerTask = new TimerTask() {
    @Override
    public void run() {
        if(!isPause){
            if(listener!= null){
                listener.setTime(max);
            }
            if(max==0){
                timer.cancel();
            }else{
                max--;
            }
        }
    }
};
}