I save a user’s username and passwords the first time he opens the app and store it in a SharedPreferences object. I check for the data the second time he enters and if its not null, then I got into the app. Here is how I’m doing this:
private SharedPreferences dhj;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dhj = this.getSharedPreferences("DHJ", MODE_WORLD_READABLE);
if(dhj.getString("username", null) != null) {
setContentView(R.layout.main);
// do some stuff...
}
else {
setContentView(R.layout.login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
loginButton = (Button) findViewById(R.id.loginButton);
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor dhjEditor = dhj.edit();
dhjEditor.putString("username", username.getText().toString());
dhjEditor.putString("password", password.getText().toString());
setContentView(R.layout.main);
}
});
// do some other stuff...
}
}
But each time I open the app, I am being asked to enter the username and password.
What am I doing wrong? How can I achieve the desired functionality?
Thank you.
You need to call the Editor’s
commitmethod after making any change to preferences. This will save the preferences file: