24

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);
            }
        });
David Buck
  • 3,752
  • 35
  • 31
  • 35
HurkanSeyhan
  • 374
  • 2
  • 3
  • 14
  • 1
    If you want to clear the preferences on log out, **why** do you store them on log in? – Phantômaxx Jun 11 '14 at 13:05
  • post ur code i'll give u solution within a 5 minites.. – GB_Bhayani ツ Jun 11 '14 at 13:08
  • i suggest you to check you code when you save or retrieve using shared preferences, because shared preferences are accessible in all the activities. – Ronn Wilder Jun 11 '14 at 13:10
  • 1
    SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); paste this code in logout onclicklistener – GB_Bhayani ツ Jun 11 '14 at 13:16

8 Answers8

63

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.apply();
             finish();
 });
Kartik Garasia
  • 1,324
  • 1
  • 18
  • 27
Krupa Patel
  • 3,309
  • 3
  • 23
  • 28
4

I think you have a trouble in understanding Shared preferences in android .

According to official documentation

To get a SharedPreferences object for your application, use one of two methods:

getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.

getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

You should have a Context for using both the above methods .

Also Shared preferences are stored asa key value pair , so clearing should mean that you set the values to some empty string.

For more details , and better explanation you can read here http://developer.android.com/guide/topics/data/data-storage.html#pref and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html

Hope this will help.

Cheers!

Community
  • 1
  • 1
Shubhang Malviya
  • 1,525
  • 11
  • 17
3

It as Simple. Like you save your data in SharedPrefernce

SharedPreferences sp = getSharedPreferences("MYKEY",0);
SharedPreferences.Editor editor = sp.edit();
editor.putString("username" , username);
editor.putString("password" , password);

Now you can retrieve as in any class of your app like,

SharedPreferences sp = getSharedPreferences("MYKEY",0);
String uname = sp.getString("username");
String pwd = sp.getString("password");

And for clear your username and password

editor.clear();
editor.commit();

or

editor.remove("username");
editor.remove("password");
editor.commit();
Piyush
  • 18,895
  • 5
  • 32
  • 63
0

Why not write a SharedPreference utility class. This can be accessed from both the activities.

prijupaul
  • 2,076
  • 2
  • 15
  • 17
  • 1
    I didn't give the downvote but likely it's because your answer isn't descriptive at all. Provide more details about what your "SharedPreference utility class" is and how it works. Maybe give some code. – dymmeh Jun 11 '14 at 13:14
0
SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = mPrefs.edit();
editor.clear();
editor.commit();
f_puras
  • 2,521
  • 4
  • 33
  • 38
Vipin Yadav
  • 707
  • 5
  • 6
0

In Kotlin you can use this code to clear the sharedpreference data

private val sharedPref = "sharedpreference"

val sharedPreferences: SharedPreferences = context.getSharedPreferences(sharedPref, Context.MODE_PRIVATE)
            val editor = sharedPreferences.edit()
            editor.clear()
            editor.apply()
Tippu Fisal Sheriff
  • 2,177
  • 11
  • 19
0
SharedPreferences preferences =getSharedPreferences("loginPrefs",Context.MODE_PRIVATE);
             SharedPreferences.Editor editor = preferences.edit();
             editor.clear();
             editor.apply();
             finish();
Exutic
  • 91
  • 4
0

For Kotlin :

fun clearall(context:Context){
      val  sp :SharedPreferences = context.getSharedPreferences(APP_PREF, Context.MODE_PRIVATE)
        val editor=sp.edit()
        editor.clear()
        editor.apply()
        editor.commit()
    }

This work for me

nipa
  • 39
  • 1
  • 8