我在我的应用程序中使用计时器,我想从另一个类中停止它。所以我有一个Activity和两个类:MainActivity,Timer,Pause。
MainActivity从Timer类调用一个方法来开始倒计时。我有一个按钮,它从Pause类调用一个方法来停止计时器。它看起来很简单,但我总是收到NullPointerException错误消息。
MainActivity:
public TextView txt;
public TextView szamlalo;
Timer i;
Pause p;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.hello);
szamlalo = (TextView)findViewById(R.id.szam);
Button b = (Button)findViewById(R.id.button);
p = new Pause(szamlalo,txt,this);
i = new Timer(szamlalo,this,txt);
i.startTimerbig();
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
p.stopminden();
}
});
}
计时器类:
public Timer bigtimer;
public TimerTask bigtimerTask;
public final Handler bighandler = new Handler();
int ido = 10;
TextView szamlalo;
TextView txt;
Context context;
Over over;
public Timer(TextView szamlalo,Context context,TextView txt){
this.szamlalo = szamlalo;
this.context = context;
this.txt = txt;
}
public void startTimerbig() {
bigtimer = new Timer();
biginitializeTimerTask();
bigtimer.schedule(bigtimerTask, 3000, 1000);
}
public void bigstoptimertask(){
bigtimer.cancel();
}
public void biginitializeTimerTask() {
bigtimerTask = new TimerTask() {
@Override
public void run() {
bighandler.post(new Runnable() {
@Override
public void run() {
ido--;
szamlalo.setText("" + ido + "s");
}
});
}
};
}
暂停课程:
TextView szamlalo;
TextView txt;
Context context;
Timer i;
public Pause(TextView szamlalo,TextView txt,Context context){
this.szamlalo = szamlalo;
this.txt = txt;
this.context = context;
this.i = new Timer(szamlalo,context,txt);
}
public void stopminden(){
i.bigstoptimertask();
}
错误消息还表示此行是有罪的:
bigtimer.cancel();
如果有人知道该怎么做,请回复!
答案 0 :(得分:1)
public Pause(TextView szamlalo,TextView txt,Context context){
this.szamlalo = szamlalo;
this.txt = txt;
this.context = context;
this.i = new Timer(szamlalo,context,txt);//HERE!!
}
你在最后一行创建了一个新的Timer对象,它与字段' i'不是同一个对象。课程' MainActivity'它的领域' bigtimer'不是因为它的startTimerbig()从未被调用过;