Search code examples
androidandroid-preferences

Clear data on the click of backpress of activity


I am getting stuck to clear the preference. I created one method to use for all activities.

 public void clearMyPrefrences() {
        SharedPreferences.Editor editor = preference.edit();
        editor.clear();
        editor.commit();
    }

But In my FirstActivity there is some EditText on which I am opening new activity and searching some contents.On the click of EditText it will open SecondActivity. When I select some option from searchmenu and back to my FirstActivity it clears data before I typed. I am calling this method on the onStop().I want to clear this data when I go back from the FirstActivity.So how should I do this??

How to clear data of preferences If I have two activites - In FirstActivity -

there are some EditText. On the click on the EditText -

SecondActivity opens. In the SecondActivity I search some data and set the selected text in the EditText of FirstActivity.

But problem is when I search and set the Text of selected item It clears all the data of FirstActivity which I typed in my activity.

And When I call above method on the onStop() it is not working.

Please tell me if there is the solution for it.Thank you.


Solution

  • You need to call clearMyPreferences in onDestroy() instead of onStop () to achieve your desired result.