HurkanSeyhan HurkanSeyhan - 5 months ago 78
Android Question

Logout clear SharedPreferences

I have login page that save username and password to Shared Preferences. I have another Activity class that include logout button. I want to clear Shared Preferences when click logout button. Problem is I dont 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);
}
});

Answer

Try this !

logout.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            // Launching News Feed Screen

             SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
             SharedPreferences.Editor editor = preferences.edit();
             editor.clear();
             editor.commit();
             finish();
 });