I use android java,
I have two button, button A is run timer, it can change many vocabulary in 5 second,
the Button B is stop timer, when I press button A ,timer run fine, press button B is fine too.
But when I press button A->button B->button A, it will shut down,how can I slove this problem?
thanks.
this is my code:
private Button.OnClickListener handbtn=new Button.OnClickListener(){//ButtonB
@Override
public void onClick(View view) {
if(timer != null) {
timer.cancel();
timer.purge();
timer = null;
}
url ="https://kei-sei.com/cram/n5.json";
level.setText("N5");
String result = dbn5.executeQuery(url);
try{
JSONArray array = new JSONArray(result);
Random random=new Random();
int tmp=random.nextInt(array.length()-1);
JSONObject jsonObject = array.getJSONObject(tmp);
String word = jsonObject.getString("word");
jp.setText(word);
}
catch(JSONException e) {
}
}
};
public void begin() {
timer.schedule(new MyTimerTask(), SEC*1000, SEC*1000) ;
}
public class MyTimerTask extends TimerTask
{
public void run()
{
url ="https://kei-sei.com/cram/n5.json";
level.setText("N5");
String result = dbn5.executeQuery(url);
try{
JSONArray array = new JSONArray(result);
Random random=new Random();
int tmp=random.nextInt(array.length()-1);
JSONObject jsonObject = array.getJSONObject(tmp);
String word = jsonObject.getString("word");
jp.setText(word);
}
catch(JSONException e) {
}
}
};
private Button.OnClickListener autobtn=new Button.OnClickListener(){//ButtonA
@Override
public void onClick(View view) {
begin();
}
}
};