Abhishek
Abhishek

Reputation: 1261

EditText: Detect user input change versus load data change

I have an an app with an Activity. This activity has an EditText field. This field gets loaded with the name of the user on the activity method onStart()

Now the user may edit his name and navigate to the next activity. I want to detect if the user has indeed made any changes or not to prompt him to save his changes.

So for example the user name is "Sam Jones" and he does not edit it, I don't want to prompt him to save. But if he changes it to just "Sam" then I want to prompt him.

So I added a TextWatcher to this EditText field. I created a boolean flag 'MADE_CHANGES', and I am changing this flag as per below.

TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            MADE_CHANGES = true;
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }

However, this method is being called even by the onStart method of the activity. Understandably, since the EditText is being changed from an empty field to "Sam Jones". So my "save" prompt is coming on even if the user has not made any changes to his name.

Is there any elegant solution to check whether the EditText has been changed by the user while excluding the initial first time data load event triggered by onStart?

Upvotes: 3

Views: 2089

Answers (2)

Hamza rasaee
Hamza rasaee

Reputation: 362

at the start of running an activity, onStart happens then OnResume so you can use a flag:

private boolean isloaded;


 @Override
protected void onResume() {
    super.onResume();
    isloaded=true;
}

@Override
protected void onStart() {
    super.onStart();
    isloaded=false;
} 

In onCreate:

        txt.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            if (isloaded)
             MADE_CHANGES = true;
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });

Upvotes: 0

Bö macht Blau
Bö macht Blau

Reputation: 13009

When setting the text from onStart(), first remove the TextWatcher

if(textWatcher != null){
    myEditText.removeTextChangedListener(textWatcher);
}

and add it again after setting the text. For this approach, you have to make the TextWatcher a field of your class.

Upvotes: 4

Related Questions