I'm writing a ContentProvider class (for a book inventory) and got stuck when checking for validity of the entries in the insert() function. If the value is not valid I would then throw an IllegalArgumentException.
One row is the price of the book and the row is defined as
FLOAT(2) NOT NULL DEFAULT 9999
So while I don't accept the explicit value NULL I would accept that the price is not defined within the given ContentValues. It would then be set to the default value 9999. Now I can try to get float corresponding to the price key:
float price = values.getAsFloat(BookEntry.COLUMN_PRICE);
But this function gives me NULL either when the key BookEntry.COLUMN_PRICE is not within the ContentValues OR when it's in there but explicitly NULL (or cannot be converted to a Float). I could check beforehand with the containsKey() function of ContentValues if there is an entry but no tutorial I have seen so far did this.
Am I making this too complicated or this is the way to go?
//Check of the price is valid, i.e. larger than 0 and not null
if (values.containsKey(BookEntry.COLUMN_PRICE)) {
Float price = values.getAsFloat(BookEntry.COLUMN_PRICE);
if (price == null) {
throw new IllegalArgumentException("Price cannot be set as null and must be a float");
} else if (price <= 0) {
throw new IllegalArgumentException("Product requires a positive price");
}
}
What you are doing - checking if the key is in the ContentValues
- is correct. A ContentValues
is just a wrapper around HashMap
: it will return null
if the map contains no mapping for the key or if the value is explicitly set to null
.
I could check beforehand with the containsKey() function of ContentValues if there is an entry but no tutorial I have seen so far did this.
Some tutorials present the information in a simplified manner (which is fine) quite often omitting good coding practices (which again is fine otherwise it gets too complex)... so don't limit yourself only to what you see in tutorials. Sometimes your intuition can suggest a better solution ;).