javaandroidgoogle-maps-markersis-emptybearing

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


this is an taxi app where user get the rotation(bearing) of driver is working well exept with devices that has not the rotaion (bearing) like this Here is the image

if driver device doesn t have this feature then the users will get an error and the app crash

so my question is how to avoid this by check if Sting is Empty and if is empty we have to put a default value on it

this it my code

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

this is how to get the String value

public String getBearing() {
       return bearing;
   }

this is the error

enter image description here


Solution

  • This assumes that if the String is empty, 0 is passed as default blank value. Also assumes the String will never be null.

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

    parseFloat will automatically trim() the String. But in order to really check if isEmpty is not giving false negatives, trimming the String guarantees no String with just whitespaces is passed as valid. String s = " "; will return false if called isEmpty() directly on it, without the trim() operation first.

    So, the condition driver.getBearing().trim().isEmpty()?"0":driver.getBearing() is telling: