I am working on a problem where a record in my application has three different states (represented by Booleans): isNew
, exists
, and isDirty
. isNew
denotes whether or not a record is a new record. exists
denotes whether or not that particular record exists in the database. isDirty
denotes whether or not any of the values in the record have changed.
The idea is to check these states, and prompt a warning that the record hasn't been saved if they try to go back.
I am using a TextChangedListener
to monitor the fields.
When a user first opens the page, it will display the most recent record, set isNew
to false and exists
to true. On creating a new record, isNew
is set to true (and exists
become false). Once new values are entered, isDirty
then becomes true. Saving the record sets isNew
to false and exists
to true.
Now when a user attempts to exit without saving, the warning should appear. The logic for the warning should be something like: An unchanged new record should not prompt warning. An unchanged existing record should not prompt warning. A changed new and a changed existing record should prompt.
The problem I'm having is how to set the states (booleans) inside the TextChanged listener.
Right now the TextChanged listener fires on page load as well as when any of the fields are changed, including on the creation of a new record. Which means that isDirty
is essentially always true. Which then makes it useless for using as a check on exit.
I tried using
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if (isNew || exists) {
isDirty = false;
}
}
And that works to not set isDirty = true
when it loads, but any subsequent field changes also return the same result. Which still makes it useless.
is using TextChangedListener
the correct way to go? Or is there some other means I can check if the text has changed without calling TextChangedListener
on load? Perhaps a way to NOT call the listener when the page loads or creates a new record?
I ended up using
public void afterTextChanged(Editable s) { if (s.toString().equals("") && isNew) { isDirty = false; } else { isDirty = true; }}
Works great!