Home > database >  Getting the value of a child of a unique ID from Firebase
Getting the value of a child of a unique ID from Firebase

Time:10-23

I'm trying to display the user's current location from Firebase, but it's not displaying in the map, the Database is structured like this:

{
  "Blocked Users" : {
    "RCX2HZXIwlSmMHFgDytf1DgZBgi2" : 0
  },
  "User Location" : {
    "RCX2HZXIwlSmMHFgDytf1DgZBgi2" : {
      "latitude" : 37.4035483,
      "longitude" : -122.097715
    }
  },
  "Users" : {
    "RCX2HZXIwlSmMHFgDytf1DgZBgi2" : {
      "Alert Level" : "High",
      "Emergency Type" : "Natural Disaster",
      "address" : "Lapaz Tarlac",
      "emergencyNum" : "0981232387346",
      "name" : "Rafael Campos",
      "phoneNum" : "0981233445675"
    }
  }
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

I'm getting NPEs when fetching the location from Firebase using this code in onMapReady, how should I fix this?

@Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        mMap = googleMap;

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Users");
        DatabaseReference uidRef = rootRef.child("User Location");

        uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DataSnapshot> task) {
                if (task.isSuccessful()) {
                    DataSnapshot snapshot = task.getResult();
                    Double latitude = snapshot.child("latitude").getValue(Double.class);
                    Double longitude = snapshot.child("longitude").getValue(Double.class);
                    LatLng location = new LatLng(latitude, longitude);
                    mMap.addMarker(new MarkerOptions().position(location).title(getCompleteAddress(latitude, longitude)));
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(location));
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location,14F));
                    Log.d("TAG", "latitude, longitude");
                } else {
                    Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
                }
            }
        });


    }

This is the stack trace:

2021-10-23 11:19:19.139 12376-12376/com.example.rescuealertadmin E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.rescuealertadmin, PID: 12376
    java.lang.NullPointerException: Attempt to invoke virtual method 'double java.lang.Double.doubleValue()' on a null object reference
        at com.example.rescuealertadmin.RetrieveMapsActivity$4.onComplete(RetrieveMapsActivity.java:202)
        at com.google.android.gms.tasks.zzi.run(com.google.android.gms:play-services-tasks@@17.2.1:1)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

CodePudding user response:

Your User Location path has a list of users, so your onComplete needs to handle the fact that the DataSnapshot has a list of child nodes too by looping over the results:

uidRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DataSnapshot> task) {
        if (task.isSuccessful()) {
            DataSnapshot snapshot = task.getResult();
            for (DataSnapshot child: snapshot.getChildren()) {
                Double latitude = child.child("latitude").getValue(Double.class);
                Double longitude = child.child("longitude").getValue(Double.class);
                LatLng location = new LatLng(latitude, longitude);
                ...
    }
});

CodePudding user response:

You are finding data on the wrong node.

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference("Users");

Here you have saved Users Information

DatabaseReference uidRef = rootRef.child("User Location");

And then you're going into "Users" Node Further. But there is NO "User Location" In "Users" Node.

You can get data like this if you have UID

DatabaseReference uidRef = FirebaseDatabase.getInstance().getReference("User Location").child(UID);
  • Related