-1

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();
        
        }
         
    }
};
samurai
  • 101
  • 1
  • 13

1 Answers1

1

You should have got NullPointerException in logcat.

You are setting timer = null; on ButtonB click. And when clicking on ButtonA, which invokes begin(), the app crashes, since timer is null!

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126