我正在尝试使用sharedpreferences来检查用户在开始使用应用程序之前是否已登录 . 我在用户登录时将用户名保存在shredpreferences中 .
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;
}
}
}
我开始使用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();
}
但用户名始终为null . 请帮忙 . 谢谢
3 回答
写下代码而不是代码,以将用户名保存到共享首选项中 .
并使用下面的代码获取首选项值 .
调用
getPreferences
表示您必须处于同一活动中 . 使用getSharedPreferences
允许您在活动之间共享首选项 . 您只需在调用getSharedPreferences("Pref name here", MODE_PRIVATE);
时为首选项定义名称