Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete data from shared preferences in android

I am trying to delete the data from shared preferences. But I cant do that. To track that the data is removed or not, I am using this code:

btnLogout.setOnClickListener(new View.OnClickListener() {

    public void onClick(View arg0) {
            SharedPreferences prefs = getSharedPreferences(share_pref_file, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = prefs.edit();
            editor.remove(share_pref_file);
            editor.clear();
            editor.commit();
            getApplicationContext().getSharedPreferences(share_pref_file, 0).edit().clear().commit(); 
                String strJson = prefs.getString("jsondata","");
                if(strJson != null) 
                    {
                     Log.d("CLEAR", "cccccccccccccccccccccccccccc");
                    }
                userFunctions.logoutUser(getApplicationContext());
                Intent login = new Intent(getApplicationContext(),LoginActivity.class);
                login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(login);
                // Closing dashboard screen
                finish();
        }
});

But in logcat window it is showing me "cccccccccccccccccccccccccccc" value every time.

So can anyone help me out that how to remove/delete the data from shared preferences so that if I click on 'logout' button it will remove all the stored data? Thanks in advance.

like image 890
Avijit Avatar asked May 01 '26 08:05

Avijit


2 Answers

An empty string is still a string (and String("") != null will return true). Try this instead:

if(!strJson.equals("")) 

This assumes the empty string will never be a valid input in your SharedPreferences in the first place.

like image 176
Tushar Avatar answered May 03 '26 21:05

Tushar


Try this one inside the button click event to clear the SharedPreferences values.

Editor editor = getSharedPreferences("MyPref", Context.MODE_PRIVATE).edit();
            editor.clear();
            editor.commit();
like image 41
Yugesh Avatar answered May 03 '26 22:05

Yugesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!