Reputation: 5795
I have declared a class extending Application to keep a global variable between activities of my app. When I press back from my launcher activity (FirstActivity.Java) my app closes, but the value of variable still remains same, which i do not want. How to achieve it?
Please note - FirstActivity extends BaseActivity
I am creating this whole setup to show a pin activity that asks for pin whenever app starts or comes to foreground from backGround. So I have setup flag to false in
onStop()
so that pin shows up when it checks the flag inonStart();
I did following -
BaseActivity.Java
public class BaseActivity extends Activity {
//static boolean flag = true;
Context con;
private ApplicationActivity app;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//this.savedInstanceState = savedInstanceState;
app = (ApplicationActivity)getApplication();
Log.d("pin", "on Create base");
con = this;
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.d("pin", "on start 1");
if(app.isFlag()){
//Start pin activity here - if pin is true it sets flag to false
app.setFlag(false);
}
}
ApplicaitonActivity.java
public class ApplicationActivity extends Application{
private boolean flag = true;
public boolean isFlag() {
//SharedPreferences sp = new SharedPreferences();
return flag;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
FirstActivity.Java
public class MainActivity extends BaseActivity {
//private Bundle savedInstanceState;
Context con;
Button nextActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//this.savedInstanceState = savedInstanceState;
Log.d("pin", "on Create 1");
con = this;
}
}
Upvotes: 3
Views: 2125
Reputation: 988
How about to set the variable which still keeps the same to null or to reset the variable when you leave the App.
You can use this
@Override
public void onPause() {
yourVariable = null;
}
or
@Override
public void onDestroy() {
yourVariable = null;
}
Also i would recommend to use SharedPreferences
to set global variables through your whole app.
Upvotes: 1