I'm trying to use sharedpreferences to check whether the user logged in before they start using the app. I save the username in shredpreferences when user log in.
Login.java
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button btnLogin = (Button) findViewById(R.id.buttonlogin);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View adapt) {
EditText usernameEditText = (EditText) findViewById(R.id.EditUserName);
userName = usernameEditText.getText().toString();
EditText passwordEditText = (EditText) findViewById(R.id.EditPassword);
userPassword = passwordEditText.getText().toString();
if (userName.matches("") && userPassword.matches("")) {
toast("Please enter Username and Password");
return;
} else if (userName.matches("") || userName.equals("")) {
toast("Please enter Username");
return;
} else if (userPassword.matches("") || userPassword.equals("")) {
toast("Please enter Password");
return;
} else {
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", userName);
editor.commit();
new DownloadFilesTask().execute();
}
}
});
}
private void toast(String text) {
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
}
protected void onPostExecute(Void result) {
toast("user logged in");
startActivity(new Intent(Login.this, MainActivity.class));
finish();
}
@Override
protected Void doInBackground(Void... params) {
return null;
}
}
}
and I tried to check the username value before I start my mainactivity.
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String username =sharedPreferences.getString("MEM1", "");
if(username.equalsIgnoreCase("")||username.length()==0)
{
toast("username is null");
startActivity(new Intent(MainActivity.this, Login.class));
finish();
}
but the username is always null. Please help. Thanks
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…