如何检查SQL数据库游标中的列是否为空?

时间:2017-10-07 22:14:37

标签: java android cursor

我有数据库,他们可以在图像中输入其中一个字段。图像保存在手机上,URI保存在数据库中。

当用户决定不为某个项目添加图像时,我遇到了麻烦。

我正在尝试编写if / else语句,其中“if”条件检查游标的image列是否为null。我只是无法弄清楚在if条件中输入什么内容。

这是我正在使用的一些代码。基本上我想这样做,如果光标的COLUMN_WINE_IMAGE为空,只需要祝酒。如果它不为空,则设置图像。

//This section turns the database's image URI stored in this cursor into a bitmap, and then sets the ImageView.
    Bitmap bitmap = null;
    try {
        if (............){
            Toast.makeText(this, "No image was taken for this item. (TOAST IS JUST TESTING PURPOSES)", Toast.LENGTH_SHORT).show();
        }else{
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE))));
            mFullImage.setImageBitmap(bitmap);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

以下是我尝试过的其中一件事没有成功的例子:

if (Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE))).equals(null)){ 

//This returns error: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jeremy.sqlwine/com.example.jeremy.sqlwine.DetailsActivity}: java.lang.NullPointerException: uriString 

2 个答案:

答案 0 :(得分:1)

以单独的方法检索列值。然后在使用之前检查返回值。

尝试这样的事情:

private String checkDatabaseValue(Cursor cursor){
    String result = null;
    try{
        //This can throw an error if the column is not found
        int index = cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE);
        result = cursor.getString(index).trim();
    }
    catch(Exception ex){
        // determine what threw the error and handle appropriately
        Log.e(TAG, ex.getMessage());
    }
    return result;
}

然后在这里使用它:

Bitmap bitmap = null;
    try {
        // I'm assuming you have the cursor from somewhere!!
        String imageFile = checkDatabaseValue(cursor);
        if (imageFile == null){
            Toast.makeText(this, "No image was taken for this item. (TOAST IS JUST TESTING PURPOSES)", Toast.LENGTH_SHORT).show();
            return;
        }

        if(!imageFile.isEmpty()){
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(imageFile));
            mFullImage.setImageBitmap(bitmap);
        else{
            Toast.makeText(this, "Empty String. (TOAST IS JUST TESTING PURPOSES)", Toast.LENGTH_SHORT).show();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

改为使用:

if(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE) == null)

更新:

cursor.isNull(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE))