所以我现在所拥有的是以下内容:
responseJson.put("barcode",
response.getBlob(response.getColumnIndex(DatabaseHelper.rBarcode)) == null
? ""
: Base64.encodeToString(response.getBlob(response.getColumnIndex(DatabaseHelper.rBarcode)),
Base64.DEFAULT));
简而言之,我想做的就是评估数据库调用是否返回 null,如果返回,则使用空字符串填充 JSON,否则使用数据库中的值。
我觉得我可能在这里遗漏了一些东西,并且不想对数据库进行两次调用,所以我知道我可以创建一个变量来只调用一次并将值存储在那里,但想知道是否有其他方法可以做到这一点吗?
最佳答案
只需进行一次数据库调用,然后重用结果:
byte[] barcode = response.getBlob(response.getColumnIndex(DatabaseHelper.rBarcode));
responseJson.put("barcode", barcode == null ? "" :
Base64.encodeToString(barcode, Base64.DEFAULT));
但是如果写成 if
语句,这可能会更容易阅读和维护:
byte[] barcode = response.getBlob(response.getColumnIndex(DatabaseHelper.rBarcode));
String value = "";
if (barcode != null) {
value = Base64.encodeToString(barcode, Base64.DEFAULT);
}
responseJson.put("barcode", value);
关于java - 有没有办法简化这个三元语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226826/