2017-07-26 28 views
0

我嘗試阻止用戶傳入空輸入。ContentProvider中的數據驗證不起作用

private Uri insert(Uri uri, ContentValues contentValues) { 

    if (contentValues.getAsString(StudentEntry.COLUMN_NAME) == null) { 
     throw new IllegalArgumentException("A name is required"); 
    } 

    if (contentValues.getAsString(StudentEntry.COLUMN_CITY) == null) { 
     throw new IllegalArgumentException("A city is required"); 
    } 
    //Perform insert operation here. 
} 

無效的數據仍然能夠進入數據庫。

回答

0

嘗試以下驗證:

if(!contentValues.containsKey(StudentEntry.COLUMN_NAME) || TextUtils.isEmpty(contentValues.getAsString(StudentEntry.COLUMN_NAME))) { 
    throw new IllegalArgumentException("A name is required"); 
}