我有登录页面,将用户名和密码保存到共享首选项.我有另一个包含注销按钮的Activity类.我想在单击“注销”按钮时清除“共享首选项”.问题是我没有从这个类获得SharedPreferences.我怎样才能获得SharedPreferences?
LoginPage
public class MainActivity extends Activity {
public SharedPreferences.Editor loginPrefsEditor;
public SharedPreferences loginPreferences;
private Boolean saveLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.et_Username);
pass = (EditText) findViewById(R.id.et_Password);
login = (Button) findViewById(R.id.bt_Login);
loginPreferences = getSharedPreferences("loginPrefs",MODE_PRIVATE);
loginPrefsEditor = loginPreferences.edit();
saveLogin = loginPreferences.getBoolean("saveLogin",false);
if (saveLogin == true) {
name.setText(loginPreferences.getString("username",""));
pass.setText(loginPreferences.getString("password",""));
}
login.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
name1 = name.getText().toString();
pass1 = pass.getText().toString();
//new Thread (new Task()).start();
loginPrefsEditor.putBoolean("saveLogin",true);
loginPrefsEditor.putString("username",name1);
loginPrefsEditor.putString("password",pass1);
loginPrefsEditor.commit();
new myAsyncTask().execute();
}
});
}
AnotherActivity中的注销按钮
logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Launching News Feed Screen
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
}
});