Android ContentValues.get() 空与值缺失

Android ContentValues.get() null vs value is missing

我正在编写一个 ContentProvider class(用于图书目录),但在检查 insert() 函数中条目的有效性时卡住了。如果该值无效,我将抛出 IllegalArgumentException。

一行是书的价格,该行定义为

FLOAT(2) NOT NULL DEFAULT 9999

因此,虽然我不接受明确的值 NULL,但我会接受价格未在给定的 ContentValues 中定义。然后它将被设置为默认值 9999。 现在我可以尝试获取与价格键对应的浮动:

float price = values.getAsFloat(BookEntry.COLUMN_PRICE);

但是当键 BookEntry.COLUMN_PRICE 不在 ContentValues 中或者当它在其中但明确为 NULL(或无法转换为 Float)时,此函数会给我 NULL。我可以事先使用 ContentValues 的 containsKey() 函数检查是否有条目,但到目前为止我还没有看到这样做的教程。

我是不是把它弄得太复杂了,或者这是正确的方法?

//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");
        }
    }

您所做的 - 检查密钥是否在 ContentValues - 是正确的。 ContentValues 只是 HashMap 的包装器:如果映射不包含键的映射或者值明确设置为 null,它将 return 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.

一些教程以简化的方式呈现信息(这很好)经常省略良好的编码实践(同样很好,否则它会变得太复杂)...所以不要只局限于你所看到的在教程中。有时您的直觉可以提出更好的解决方案;)。