diff --git a/app/src/main/java/com/example/android/pets/data/PetContract.java b/app/src/main/java/com/example/android/pets/data/PetContract.java index a182d550..a3f5a55c 100755 --- a/app/src/main/java/com/example/android/pets/data/PetContract.java +++ b/app/src/main/java/com/example/android/pets/data/PetContract.java @@ -105,6 +105,17 @@ public static final class PetEntry implements BaseColumns { public static final int GENDER_UNKNOWN = 0; public static final int GENDER_MALE = 1; public static final int GENDER_FEMALE = 2; + + /** + * Returns whether or not the given gender is {@link #GENDER_UNKNOWN}, {@link #GENDER_MALE}, + * or {@link #GENDER_FEMALE}. + */ + public static boolean isValidGender(int gender) { + if (gender == GENDER_UNKNOWN || gender == GENDER_MALE || gender == GENDER_FEMALE) { + return true; + } + return false; + } } } diff --git a/app/src/main/java/com/example/android/pets/data/PetProvider.java b/app/src/main/java/com/example/android/pets/data/PetProvider.java index 268eea27..f98a2a5d 100644 --- a/app/src/main/java/com/example/android/pets/data/PetProvider.java +++ b/app/src/main/java/com/example/android/pets/data/PetProvider.java @@ -140,6 +140,26 @@ public Uri insert(Uri uri, ContentValues contentValues) { * for that specific row in the database. */ private Uri insertPet(Uri uri, ContentValues values) { + // Check that the name is not null + String name = values.getAsString(PetEntry.COLUMN_PET_NAME); + if (name == null) { + throw new IllegalArgumentException("Pet requires a name"); + } + + // Check that the gender is valid + Integer gender = values.getAsInteger(PetEntry.COLUMN_PET_GENDER); + if (gender == null || !PetEntry.isValidGender(gender)) { + throw new IllegalArgumentException("Pet requires valid gender"); + } + + // If the weight is provided, check that it's greater than or equal to 0 kg + Integer weight = values.getAsInteger(PetEntry.COLUMN_PET_WEIGHT); + if (weight != null && weight < 0) { + throw new IllegalArgumentException("Pet requires valid weight"); + } + + // No need to check the breed, any value is valid (including null). + // Get writeable database SQLiteDatabase database = mDbHelper.getWritableDatabase();