共享偏好问题

时间:2011-05-17 08:08:05

标签: android

我是Android开发的新手

在我的应用程序中,我想在我的活动中保持用户的登录状态。我有2个编辑框用于输入名称和密码。如果用户想要保持登录状态,则需要1个复选框。

当用户点击登录按钮时,我在共享首选项中保存名称和密码。在onCreate方法中,我想要检索该值。如果用户有点击复选框,那么他应该直接重定向到下一页。但它不起作用。

这是我的代码:

signUpButton=(Button)findViewById(R.id.signUpLoginId);          
signUpButton.setOnClickListener(this);

//toggleButtonOnOff=(ToggleButton)findViewById(R.id.togglebutton);

loginEditText = (EditText) findViewById(R.id.loginNameID);          
passwordEditText=(EditText)findViewById(R.id.passwordId);           
box=(CheckBox)findViewById(R.id.checkbox);

preferences=PreferenceManager.getDefaultSharedPreferences(context);

String n=preferences.getString(PREF_USERNAME, null);                
String p=preferences.getString(PREF_PASSWORD, null);

loginEditText.setText(n1);
passwordEditText.setText(p1);

Intent intent1=new Intent(LoginActivity.this,FindFishMenuActivity.class);                   
startActivity(intent1);

LoginActivity.this.finish();

if(box.isChecked())
{
    box.setChecked(true);
    Toast.makeText(LoginActivity.this,"box value set to true",Toast.LENGTH_LONG).show();
    password=passwordEditText.getText().toString();
    preferences=context.getSharedPreferences(key_str, MODE_PRIVATE);
    editor=preferences.edit();
    editor.putString(PREF_USERNAME, name);
    editor.putString(PREF_PASSWORD, password);
    editor.commit();
    intent=new Intent(LoginActivity.this,FindFishMenuActivity.class);
    startActivity(intent);
    LoginActivity.this.finish();
}

1 个答案:

答案 0 :(得分:3)

如果你完成了你的活动,那么从来没有达到守则!

但是,在您触发Intent之前,我会将保存您的Name和Password的代码放到SharedPreference中。当您尝试在另一个Activity中读取它时,可能还没有保存Preference-Object。尝试使用LogCat对此进行调试。