2017-10-07 109 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