我有两个活动..首先是Loginactivity如果按钮点击然后我将值存储在sahred prefrences和第二个activtty中(Firstscreen我啊按钮注销如果我点击它然后重新移动存储的sharedpreferences值...
....退出应用程序并重新启动应用程序后,如果我打印然后共享首选项存储值正在打印...(如果我注销然后完全删除值)
public class LoginActivity extends ActionBarActivity {
User myApplication;
EditText username,passwordField;
Button login;
CheckBox check;
SharedPreferences settings;
SharedPreferences.Editor editor;
String userStored;
String passwordStored;
boolean checked =false;
boolean checkboxvalue;
public static final String PREFS_NAME = "Shared_File";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings = getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
editor.putString("User_Shared", username.getText().toString());
editor.putString("Pass_Shared", passwordField.getText().toString());
//editor.putBoolean("Checkbox_Click", true);
editor.commit();
userStored = settings.getString("User_Shared",null);
passwordStored =settings.getString("Pass_Shared", null);
System.out.println("userStored :::" +userStored + " :::::::pasword :::::::" +passwordStored );
Intent intent = new Intent(getApplicationContext(),FirstScreen.class);
startActivity(intent);
}
}
});
}
}
public class FirstScreen extends Activity {
Button logout;
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "Shared_File";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.firstscreen);
logout =(Button)findViewById(R.id.logout);
logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings =getSharedPreferences(PREFS_NAME,Context.MODE_PRIVATE);
editor = settings.edit();
try {
editor.remove("User_Shared");
editor.remove("Pass_Shared");
editor.clear();
editor.commit();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
//intent.putExtra("Logout", logout);
startActivity(intent);
}
});
}
}
答案 0 :(得分:0)
这与活动生命周期有关。您应该将与SharedPreferences相关的代码放在onPause方法中。您的代码的错误在于它将键值对存储在SharedPreferences对象中,但是当您按下后退按钮或活动退出其活动状态时会被删除。 所以,试试我的建议。祝你好运。希望,这很有益。
答案 1 :(得分:0)
很容易放
editor.putString("User_Shared", null);
一切都会正常。