有幾天,我一直在嘗試讓用戶名保存在會話中正確。首先,我打開了應用程序,它會打開登錄屏幕。我用用戶名登錄,然後它會帶我到MainActivity。現在我退出應用程序並重新打開應用程序以確保用戶名已保存,並且會通過登錄屏幕直接進入MainActivity。到目前爲止這麼好,然後我會註銷,它會回到登錄屏幕。我想確保它完全註銷,所以我退出應用程序並重新打開應用程序,它會帶我到MainActivity。我無法弄清楚如何解決這個問題。共享首選項似乎不會在會話中保存用戶名
我登錄類
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.commit();
if(prefs.getString("username", null)!=username)
{Intent i = new Intent(getApplicationContext(), Customer.class);
startActivity(i);}
etUsername = (EditText)findViewById(R.id.username);
btnLogin = (Button)findViewById(R.id.login_button);
btnCancel = (Button)findViewById(R.id.cancel_button);
lblResult = (TextView)findViewById(R.id.result);
btnLogin.setOnClickListener(new OnClickListener() {
//@Override
public void onClick(View v) {
// Check Login
String username = etUsername.getText().toString();
if(username.equals("1111")){
lblResult.setText("Login successful.");
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
我退出類
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.logout);
code = (EditText)findViewById(R.id.codeout);
btnLogout = (Button) findViewById(R.id.submit);
btnCancel = (Button) findViewById(R.id.cancel);
lblResult = (TextView)findViewById(R.id.result);
btnLogout.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String logout = code.getText().toString();
if (logout.equals("99")){
lblResult.setText("Logout successful");
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
editor.remove("username");
editor.commit();
Intent i = new Intent(getApplicationContext(), Login.class);
startActivity(i);
finish();
@Tanner我會記住現在進行字符串比較。我不知道我的編碼中有哪些==,但我也編輯了下面提到的行,即使註銷後也不會打開登錄屏幕。 – merrill 2011-06-07 22:58:11
@merrill那麼您的問題中發佈的代碼是否與您遇到的問題一致?如果沒有,爲什麼不用最近的代碼編輯原始文章。 – 2011-06-08 00:04:24
@Tanner我所做的唯一更改就是'if(prefs.getString(「username」,null)!= username)' if if(!prefs.getString(「username」,「」).equals用戶名))'它永遠不會看到登錄屏幕在所有 – merrill 2011-06-08 14:27:35