-2

Everything working fine i got this error at the end please give solution. I have tried each and every solution, I don't know what to do.. please give the exact solution trying from past 2 days but i can't solve the problem..

Thanks in advance

public double calculatedDistance(DataSnapshot dataSnapshot ) {


        HashMap<String, Object> values = (HashMap<String, Object>) dataSnapshot.getValue();

        double lati = Double.parseDouble(values.get("latitude").toString());
        double longi = Double.parseDouble(values.get("longitude").toString());

        double xSquare = Math.pow(lat-lati, 2);
        double ySquare = Math.pow(lng-longi, 2);
        double distance = Math.sqrt(xSquare + ySquare);

        //double dist = distance;

        textViewdistance.setText(String.valueOf(""+distance+""+"km"));
        return distance;

    }
Error in Logcat

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.ambulance, PID: 17399
    java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
        at com.example.ambulance.MapsActivity.calculatedDistance(MapsActivity.java:451)
        at com.example.ambulance.MapsActivity$2$1.onChildAdded(MapsActivity.java:178)
        at com.google.firebase.database.core.ChildEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.0:79)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.0:55)
        at android.os.Handler.handleCallback(Handler.java:907)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

1 Answers1

-1

There is nothing wrong in the code itself, just you have to understand why some value is null when you do not expect it to be.

In general a check has to be done when a Null Pointer Exception could be issued.

And also check these 'lat-lati' and 'lng-longi' variables

    double xSquare = Math.pow(lat-lati, 2);
    double ySquare = Math.pow(lng-longi, 2);
P5music
  • 3,197
  • 2
  • 32
  • 81