2017-10-07 98 views
1

我有数据库,在那里他们可以在图像中的区域之一输入。图像保存到手机中,并将URI保存到数据库中。如何检查SQL数据库游标中的列是否为空?

当用户决定不把图像中的一个项目,我有麻烦。

我试图写一个if/else语句,这里的“如果”条件检查光标的图像栏为空。我只是无法弄清楚在if条件下输入什么。

这里的代码我的工作位。基本上我想这样做,以便如果游标的COLUMN_WINE_IMAGE为null,只需做一个敬酒。如果不为空,则设置图像。

//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 

回答

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(); 
    } 
+0

此表现的很出色。非常感谢。我并不擅长思考这样的方法。我希望我能改善这一点。感谢您提供这样的方法。现在我有一个很好的例子来说明我应该如何思考这样的项目。 – andrdoiddev

+0

当你仍然在学习(并且不是大家,真的)尽量不要使用复合语句这样的:'Uri.parse(cursor.getString(cursor.getColumnIndexOrThrow(WineContract.WineEntry.COLUMN_WINE_IMAGE)))'::很难看出哪里出了问题,哪里出了问题,为什么。打破一切,以便您可以检查每个值。 – Barns

0

用这个代替:

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

更新:

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

这个虽然问题是,它只是获取指数的整数,对不对?除非我错了。无论哪种方式,当我尝试这种方式它有一个红色下划线,上面写着:经营者“==”不能适用于“诠释”,“空” – andrdoiddev

+0

@andrdoiddev答案更新 – Hooman