I am writing an app to save password with a login interface. The user can change the login password. First time, I use the following code to save the password, so that the password will not reset when the app relaunch:
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putString("pwd", currentPwd);
super.onSaveInstanceState(savedInstanceState);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
currentPwd = savedInstanceState.getString("pwd");
}
But after I asked that, someone in this website suggested me to use “SharedPreferences”. So, I changed the code as follow:
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences("setting", 0);
currentPwd = settings.getString("pwd", "abc");
}
@Override public void onStop(){
super.onStop();
SharedPreferences settings = getSharedPreferences("setting", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("pwd", currentPwd);
editor.commit();
}
After my experiment, I found that the password will be reset after one hour which the same as the first code. Have I changed it wrong for the second code? Or there are any suggested way to solve it? Thank you.
Not sure I’m following your code, but here is how I would do this:
To get password:
To set password:
Hope that helps