如何检查 id 字符串是否为空,然后在 android studio 中定义一个默认值(如果为空)

How to check id String is Empty then put a define a default value if is Empty in android studio

这是一个出租车应用程序,用户可以在其中获得 driver 的旋转(方位) 除了没有旋转(轴承)的设备外,工作良好 像这样 Here is the image

如果 driver 设备没有此功能,则用户将收到错误消息并且应用程序崩溃

所以我的问题是如何通过检查 Sting 是否为空来避免这种情况 如果为空,我们必须为其设置默认值

这是我的代码

if (icondriver.equals("2")) {
                   driverMarkers.add(
                           gMap.addMarker(new MarkerOptions()
                                   .position(currentDriverPos)
                                   .icon(BitmapDescriptorFactory.fromResource(R.drawable.carmap))
                                   .anchor((float) 0.5, (float) 0.5)
---------error line------------->>  .rotation(Float.parseFloat(driver.getBearing()))
                                   .flat(true)
                           )

这是获取字符串值的方法

public String getBearing() {
       return bearing;
   }

这是错误

enter image description here

这假定如果字符串为空,则 0 作为默认空白值传递。还假设字符串永远不会是 null.

(...)
rotation(Float.parseFloat(driver.getBearing().trim().isEmpty()?"0":driver.getBearing()))
(...)

parseFloat 将自动 trim() 字符串。但是为了真正检查 isEmpty 是否没有给出假阴性,修剪字符串保证没有只有空格的字符串被传递为有效。如果直接调用 isEmpty()String s = " "; 将 return false,而不先进行 trim() 操作。

所以,条件 driver.getBearing().trim().isEmpty()?"0":driver.getBearing() 说明:

  • 如果字符串为空,则传递 "0"(或您想要的默认值)。
  • 如果不是,则按原样传递字符串值 (driver.getBearing())。
public String getBearing() {

   String defaultValue = "0";
   String result;

   if(bearing == null || bearing.trim().isEmpty()) {
       result = defaultValue;
   } else {
       result = bearing;
   }
   return result;
}

如果 -> bearing.isEmpty()"0":bearing;

你可以使用内联