MD TAHMID HOSSAIN
MD TAHMID HOSSAIN

Reputation: 1720

How to stop timer.schedule when i am going to another activity

i have follow This link to implement Volley in my project. i have the same "AppController " class. it works fine. now i want to do call to server after every 5 mins so i wrote following

Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        public void run() {

            try {

                JSONObject json = new JSONObject();

                json.put("SomeData1", "SomeData1Value");
                json.put("SomeData2", "SomeData2Value");
                JsonObjectRequest j = new JsonObjectRequest("SomeUrl", json,
                        responseSaveTokenJson(), genericErrorListener());
                AppController.getInstance().addToRequestQueue(j);

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
}, 0, 5000);

private Response.ErrorListener genericErrorListener() {
    return new ErrorListener() {

        public void onErrorResponse(VolleyError error) {

            try {
                Toast.makeText(getApplicationContext(),
                        "Code :" + error.networkResponse.statusCode + "\nNetwork Error\nPlease Try AgainH",
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "No internet connection availableH\n" + error.getMessage(),
                        Toast.LENGTH_LONG).show();
            }
        }

    };
}

private Response.Listener<JSONObject> responseSaveTokenJson() {
    return new Response.Listener<JSONObject>() {

        public void onResponse(JSONObject response) {
            Toast.makeText(HomeActivity.this, "RH", Toast.LENGTH_SHORT).show();

        }
    };
}

As you can see if the request is successful then it will show a toast of "RH".

it works find now i go to another activity by doing following things

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
                startActivity(intent);
                finish();

the app shows the other activity but the problem is "it is also toasting "RH" after every 5 sec"

how to stop it from Toasting(how to stop that timer)

Upvotes: 1

Views: 422

Answers (1)

Badhon Ashfaq
Badhon Ashfaq

Reputation: 851

Intent intent = new Intent(getApplicationContext(), SomeActivity.class);
                startActivity(intent);
timer.cancel();
                finish();

Upvotes: 2

Related Questions