Issue
In the below code, when I change orientation of the device, I am still getting previous values of variable "count", along with a new counter for "count", what could I derive from this behaviour? Is the TimerTask holding reference of "count" variable ?
public class MainActivity extends AppCompatActivity {
private int count;
private TimerTask timerTask;
private Timer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTask = new MyTimerTask();
timer = new Timer(true);
//running timer task as daemon thread
timer.scheduleAtFixedRate(timerTask, 0, 1000);
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
count++;
System.out.println("*** " + count + " ***");
}
}
}
Solution
Basically, you have memory leak there which is caused by not cancelled previous Timer and keeping reference to count variable. That's why even when Activity is destroyed, your old timer is still increasing the old count variable, and as activity is being recreated, there'll be new Timer object and new count variable. Therefore, you'll see 2 counters at the same time.
Solution is cancelling the timer when activity is destroyed:
@Override
protected void onDestroy() {
super.onDestroy();
timer.cancel();
}
If you want to read more about memory leaks, you can checkout this article.
Answered By - Natig Babayev

0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.