android not clearing sharedpreference
android, android-preferences
Solution
Try with this :
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
Thanks.
Problem
I want to clear all the sharedpref i put on my first activity and delete it on 2nd activity. But the clear function is not working.. here is my code ``` public class MyActivity extends Activity implements View.OnClickListener { /** * Called when the activity is first created. */ public static final String PREFS_NAME = "ResumePrefs"; SharedPreferences settings; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ((Button)findViewById(R.id.button)).setOnClickListener(this); } @Override protected void onResume() { try{ Toast. makeText(this,settings.getString("answer_id",""),Toast.LENGTH_LONG).show(); }catch (Exception e){ Toast.makeText(this,e.toString(),Toast.LENGTH_LONG).show(); } super.onResume(); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.button: settings = getSharedPreferences(PREFS_NAME, 1); SharedPreferences.Editor editor = settings.edit(); editor.putString("answer_id", "This is a test"); editor.commit(); Intent intent = new Intent(this,destroyPref.class); startActivity(intent); break; } } } ``` and my2nd activty: ``` public class destroyPref extends Activity { public static final String PREFS_NAME = "ResumePrefs"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.destroy); } @Override public void onBackPressed() { SharedPreferences settings = this.getSharedPreferences(PREFS_NAME,1); settings.edit().clear(); settings.edit().commit(); super.onBackPressed(); } @Override protected void onResume() { SharedPreferences settings = this.getSharedPreferences(PREFS_NAME,1); settings.edit().clear(); settings.edit().commit(); super.onResume(); } } ``` Once i pressed the back button i will go back to the main activity and expect that the preference value is cleared, unless i pressed again the button. I tried bot backpress and resume but still the sharedpref value is still there.. Am i missing something? Thanks.