As you are using tempScore
as static
, it is causing the issue.
Statics are global to the process. So their value will last for the lifetime of the process, which is usually much longer than an individual activity instance.
But when I completely close the app(i.e)closed from task manager and
again restarted the score is reset by new score even though my current
score is lower than previous one
When you do that, the Task manager
kills the process of your application. Hence, your static variable loses its value.So next time when you start the app again, you get the default value of that static variable.
In your case, you will get value 0 for tempScore, as you are using int. Hence condition in 'if()' will be true in that case.
I think, one of the best practices in coding is to avoid static variables wherever possible. And one way to do that in Android, by using a class extended from Application
class.
public class MyApplication extends Application {
private int tempScore;
public int getTempScore() {
return tempScore;
}
public void setTempScore(int tempScore) {
this.tempScore = tempScore;
}
}
Since for an application there will be only one Application
object, you can always get and set the custom application object’s variables anywhere from your application as follows.
((MyApplication)getApplication()).setTempScore();
((MyApplication)getApplication()).getTempScore();
The application object’s life time is throughout the application’s life (and so your custom application object’s) and using the get()
, set()
method you can manage its data members, and hence avoiding a static variable in your application.
Hope it helps you.