Any nontrivial app will have some level of the validation required. The POIApp
app is somewhat trivial, but we have a small set of rules we need to enforce that will facilitate the discussion.
Property |
Rule |
---|---|
Name |
Cannot be empty or null. |
Latitude |
Valid decimal number between |
Longitude |
Valid decimal number between |
The EditText
widget has a string property named Error
, which simplifies the effort of displaying errors to the user, particularly if you want to be able to show all the fields with errors at once. The following screenshot displays the error received for leaving the Name field empty:
To use this facility, simply set the property to an error message and clear the property when no errors exist. The following example demonstrates implementing the rule for the Name property.
bool errors = false; if (String.IsNullOrEmpty (_nameEditText.Text)) { _nameEditText.Error = "Name cannot be empty"; errors = true; } else _nameEditText.Error = null;
Notice the local Boolean variable named errors
, which is used to keep track of whether any errors have been found. Edits for Latitude and Longitude are a little more involved, as you need to account for converting text to a double
value and allow for a null
value to be specified. The following code demonstrates one of the approaches to implement the edits:
double? tempLatitude = null; if (!String.IsNullOrEmpty(_latEditText.Text)) { try { tempLatitude = Double.Parse(_latEditText.Text); if ((tempLatitude > 90) | (tempLatitude < -90)) { _latEditText.Error = "Latitude must be a decimal valuebetween -90 and 90"; errors = true; } else _latEditText.Error = null; } catch { _latEditText.Error = "Latitude must be valid decimal number"; errors = true; } }
Implement the rules identified at the start of this section in the SavePOI()
method using the EditText.Error
property.
The actual updating of the POI properties and saving should only be performed if all of the edits are passed. The following listing shows one of the ways to structure the logic:
if (!errors) { _poi.Name = _nameEditText.Text; _poi.Description = _descrEditText.Text; _poi.Address = _addrEditText.Text; _poi.Latitude = tempLatitude; _poi.Longitude = tempLongitude; POIData.Service.SavePOI (_poi); Finish (); }
Notice that the Finish()
method is called at the end of the preceding code snippet. This causes the POIDetailActivity
activity to be closed and the previous activity on the stack will be brought back to the foreground; in our case, POIListActivity
. Refer to the code bundle for a more complete example.
Run POIApp
and confirm that the validations are working correctly.
3.139.86.56