Reputation: 61
This is the code of my sharedpreferences.It is working well in putting and retriving data but not able to clear data from sharedpreferences
SharedPreferences sharedPreferences1 = getSharedPreferences("userDataInSharedPref",MODE_PRIVATE);
SharedPreferences.Editor editor =sharedPreferences1.edit();
editor.putString("loginas", loginas_);
editor.putString("name", name_);
editor.putString("yearofbirth", yearofbirth_);
editor.putString("gender", gender_);
editor.apply();
SharedPreferences sharedPreferences1 = getContext().getApplicationContext().getSharedPreferences("userDataInSharedPref", Context.MODE_PRIVATE);
String uname = sharedPreferences1.getString("name", "");
String udob = sharedPreferences1.getString("yearofbirth", "");
String ugender = sharedPreferences1.getString("gender", "");
String uspeci = sharedPreferences1.getString("loginas", "");
UserName.setText(uname);
Birth_date.setText(udob);
Usergender.setText(ugender);
Specification.setText(uspeci);
binding.logout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences.Editor editor = sharedPreferences1.edit();
editor.clear();
editor.commit();
// SharedPreferences sharedPreferences = getActivity().getApplicationContext().getApplicationContext().getSharedPreferences("autoLogin", Context.MODE_PRIVATE);
}
});
Upvotes: 1
Views: 97
Reputation: 256
Check if you are using any singleton class where you might be retrieving the values of these variables using SharedPreferences. The instance of this class need to be set to null too along with above solution.
Upvotes: 1
Reputation: 314
to clear one string :
sharedPreferences.edit().remove("name").commit();
to clear all strings :
sharedPreferences.edit().clear().apply();
Upvotes: 1
Reputation: 3765
To clear it you need to add this code
public void clear(){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
}
Upvotes: 0