2

我不时得到这个异常,当我从GPS获得一个新的位置坐标,并且我想格式化它。致命异常:java.lang.NumberFormatException

这是我的代码:

DecimalFormat decimalFormat = new DecimalFormat("0.00000"); 
      location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()))); 
      location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()))); 

为什么会出现这种情况?我从该位置获得的经度和纬度都是双打。我将它转换成需要的格式(小数点后5位小数),然后当我尝试双击时,它会崩溃。为什么会发生?为什么不是每次,有时呢?

例如在什么崩溃:

Fatal Exception: java.lang.NumberFormatException 
Invalid double: "52,36959" 

这是我使用它:

Log.i("","enteredd latitude is:" + location.getLatitude()); 
      try{ 
       DecimalFormat decimalFormat = new DecimalFormat("0.00000"); 
       location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", "."))); 
       location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()).replace(",", "."))); 
      }catch (Exception e){ 
       Log.e("","enteredd error deimal formating" + e.getMessage()); 
      } 
      Log.i("","enteredd latitude is:" + location.getLatitude()); 

而且同样的事情:

location = LocationServices.FusedLocationApi.getLastLocation(PSLocationCenter.getInstance().mLocationClient); 

问:请问,如果修复我这样做?

location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()).replace(",", "."))); 
+0

什么的'location.getLongitude()'和'location.getLongitude()'值是多少? –

+0

我不知道。我遇到Fabric上的崩溃。它使用了很多,如每分钟至少6次,如果正确的活动被打开,则直到60。而我在3天内只有“15人”坠毁。 我所知道的是,我得到:无效的双:“52,36959”所以我猜拉特将类似于52,36959xxx –

+0

因此,双解析将失败,因为它包含逗号字符。 –

回答

1

你把一个双值转换成十进制格式,然后解析回双,并使用你已经从变量location得到为location设置的值很值相同。这里有很多不合逻辑的东西。

location.setLatitude(Double.valueOf(decimalFormat.format(location.getLatitude()))); 
location.setLongitude(Double.valueOf(decimalFormat.format(location.getLongitude()))); 

location.getLatitude是纬度,你不需要进行设置。

您需要设置小数点分隔符:

DecimalFormat decimalFormat = new DecimalFormat("0.00000"); 
DecimalFormatSymbols dfs = new DecimalFormatSymbols(); 
dfs.setDecimalSeparator('.'); 
decimalFormat.setDecimalFormatSymbols(dfs); 

从这里:(android) decimalformat, uses comma in place of fullstop while formatting with "#.##"

另外:

获取位置。

double latitude = location.getLatitude(); 
double longitude = location.getLongitude(); 

为了您的应用程序的目的,您不需要更改此设置。

就值传递给你所需要的服务器:

String lat = decimalFormat(latitude); 
String long = decimalFormat(longitude); 
+0

其实我做的!我需要发送到服务器位置,经纬度只包含5位小数。 这意味着:52.367991324必须变成:52.36799。 现在如果你有更好的版本来做到这一点,让我知道。我这样做,因为不知道多少小数我得到了经济和长期,我不能划分得到5位小数 –

+0

以及可以单独完成..我会起草一个编辑@rosualin .. –

+0

@rosualin can you展示你如何获得你的位置,你有没有测试过它们 –