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展示你如何獲得你的位置,你有沒有測試過它們 –