I have a login page that saves username
and password
to SharedPreferences
. I have another Activity
class that includes a logout button. I want to clear SharedPreferences
when I click the logout button. The problem is that I don't get the SharedPreferences
from this class. How can I get the 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();
}
});
}
Logout Button in 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);
}
});