2017-01-07 1 views
1

Я не понимаю, что происходит с моим кодом ... Я получаю исключение нулевого указателя на значение, даже думал, что то же самое значение показывает в моих журналах строку непосредственно перед этим. Я не понимаю, где еще может произойти ошибка. Вот мой код:NullPointerExpection java, даже отображение значения отображается?

private Map<String,Double> isRecordValid(RecordObject record, RecordObject previousRecord, int counterElevationArrayFilligness) { 
     Map<String,Double> values = null; 
     boolean SPEED_OK = true; 
     boolean DISTANCE_OK = false; 
     boolean ELEVATION_OK = false; 

     // SPEED 
     // has to be greater then the average Human walking: 1.4 m/s 
     if(record.getSpeed() > 1.4){ 
      values.put("Speed", record.getSpeed()); 
      Log.d("DEBUG", "SPEED OK"); 
      SPEED_OK = true; 
     } 

     // DISTANCE 
     // Check if the distance record we are checking and the last one, is above the average accuracy of both. 
     // This is done to avoid having loads of reccords stacking up when the phone is not moving and therefore lots of Flase Postivie values 
     float[] distanceBetweenResults = new float[1]; 
     LatLng latLongA = new LatLng(record.getLatitude(), record.getLongitude()); 
     LatLng latLongB = new LatLng(previousRecord.getLatitude(), previousRecord.getLongitude()); 
     Location.distanceBetween(latLongA.latitude, latLongA.longitude, latLongB.latitude, latLongB.longitude, distanceBetweenResults); 
     double distanceBetweenAB = distanceBetweenResults[0]; 

     int accuracyA = record.getAccuracy(); 
     int accuracyB = previousRecord.getAccuracy(); 
     int averageAccuracy = (accuracyA + accuracyB)/2; 

     Log.d("DEBUG", "" + distanceBetweenAB); 
     if (SPEED_OK) { 
      if (distanceBetweenAB > averageAccuracy) { 
       values.put("Distance", distanceBetweenAB); 
       Log.d("DEBUG", "DISTANCE OK"); 
       DISTANCE_OK = true; 
      } 
     } 

     // ELEVATION 
     // fill in an array to calculate the average altitude over 4 reocrds, this is done because the alitude in an android phone 
     // is really inacurate unless the phone has a barometer, which most don't. 
     for (int e=0; e < elevationArray.length; e++) { 
      if(elevationArray[e] == null){ 
       elevationArray[e] = record.getAltitude(); 
       Log.d("DEBUG", "FIRST ELEVATION OK"); 
       ELEVATION_OK = true; 
      } else { 
       counterElevationArrayFilligness ++; 
      } 
     } 

     if(elevationArray[3] != null){ //Once the array is filled with value 
      int sum = 0; 
      for (double value:elevationArray) { 
       sum += value; 
      } 
      double averageElevation = sum/4; //this is the average of all the 4 values 

      int interval = Double.compare(averageElevation, BASE_ELEVATION); //this returns the interval between 2 doubles 
      if (interval > 1 || interval < -1){ // check if the difference is at least 1m 
       values.put("Elevation", averageElevation); 
       Log.d("DEBUG", "ELEVATION OK"); 
       ELEVATION_OK = true; 
      } 
     } 

     if(DISTANCE_OK && ELEVATION_OK && SPEED_OK){ 
      return values; 
     } else { 
      return null; 
     } 
    } 

Ошибка на линии: values.put («Расстояние», расстояниеBetweenAB); Но значение distanceBetweenAB отображается непосредственно перед функциями IF А вот ошибка, что я получаю:

FATAL EXCEPTION: main 
        Process: com.example.rtuya.myfitnesstracker, PID: 6406 
        java.lang.RuntimeException: Error receiving broadcast Intent { act=UPDATE_UI flg=0x10 } in [email protected] 
         at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:891) 
         at android.os.Handler.handleCallback(Handler.java:739) 
         at android.os.Handler.dispatchMessage(Handler.java:95) 
         at android.os.Looper.loop(Looper.java:148) 
         at android.app.ActivityThread.main(ActivityThread.java:5417) 
         at java.lang.reflect.Method.invoke(Native Method) 
         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
        Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.lang.Object java.util.Map.put(java.lang.Object, java.lang.Object)' on a null object reference 
         at com.example.rtuya.myfitnesstracker.Service.TrackerService.isRecordValid(TrackerService.java:347) 
         at com.example.rtuya.myfitnesstracker.Service.TrackerService.calculateUptoNowValues(TrackerService.java:216) 
         at com.example.rtuya.myfitnesstracker.Service.TrackerService.updateHistoryTable(TrackerService.java:143) 
         at com.example.rtuya.myfitnesstracker.MainActivity.getValuesFromService(MainActivity.java:98) 
         at com.example.rtuya.myfitnesstracker.MainActivity$1.onReceive(MainActivity.java:72) 
         at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:881) 
+3

'Map значения = NULL;', 'values.put ("Расстояние", distanceBetweenAB);'. – Marvin

+0

Вы не инициализировали экземпляр карты. '' Map values ​​= null; '' '' if (record.getSpeed ​​()> 1.4) { values.put ("Speed", record.getSpeed ​​()); '' –

+0

@Marvin but i я заполняю Карту значением, поэтому, конечно, мне нужно установить его в нуль при начале? –

ответ

1

NullPointerException вызывается из-за значений переменных. Не из-за distanceBetweenAB. Нужно инициализировать значения.

Например:

Map<String,Double> values = new HashMap<>(); 
Смежные вопросы