I'm very new to Android and recently I got caught up in a situation where I need to use SharedPreferences: I have a variable that is changed as the project goes, and the app starts in a different screen depending on the variable's value, for example if the value is 0 then the app should start in LoginManager.class and if it's 1 then it starts in MainActivity.class.
So whenever I login successfully the state changes to 1 (so I don't have to login each time) or if I log out state is 0.
Given this, of course the variable needs to be saved externally so the value is not lost, and retrieve it when I create the first screen.
So my logic was that I create a onDestroy method so when the screen closes whatever global variable "state" has is what the SharedPreference variable "sharedstate" is going to get (This is from my initial Activity):
private SharedPreferences sharedPref;
public static int state=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_first);
pb = (ProgressBar) findViewById(R.id.pb);
mContext = IntroManager.this;
pb.setVisibility(ProgressBar.VISIBLE);
CountDownTimer mCountDownTimer;
pb.setProgress(i);
sharedPref = mContext.getSharedPreferences("Apathy", Context.MODE_PRIVATE);
getProfile();
mCountDownTimer=new CountDownTimer(1500,1000) {
@Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i+ millisUntilFinished);
i++;
pb.setProgress((int)i*100/(1500/1000));
}
@Override
public void onFinish() {
check();
i++;
pb.setProgress(100);
}
};
mCountDownTimer.start();
}
@Override
protected void onDestroy (){
super.onDestroy();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("sharedstate", 1);
editor.commit();
}
private void getProfile() {
String sharedstate = sharedPref.getString("state", "");
state= Integer.parseInt(sharedstate);
}
public void check(){
if(state == 0){
Intent mcrIntent = new Intent(IntroManager.this, LoginManager.class);
startActivity(mcrIntent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}else{
if(state == 1){
Intent mcrIntent = new Intent(IntroManager.this, MainActivity.class);
startActivity(mcrIntent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
}
So I got caught up in a dilemma: if I put that same onDestroy method in all of my screens (since I can't predict where the app is going to close) does the same "sharedstate" change it's value or does it create a bunch of variables that are called Sharedstate? And are they saved in the same "Apathy" thing?