0

The Error I get from my app

My Error

java.lang.NullPointerException: Attempt to invoke virtual method 

'java.lang.String com.populargeng.trackamechanic.Model.Client.getName()' on a 
null object reference

at com.populargeng.trackamechanic.Home$5$1.onDataChange(Home.java:355)

My Code Line I wrote

My Code

    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
    // Because Client and User Model is same properties
    // So we can use the Client Model to get User here
    Client client = dataSnapshot.getValue(Client.class);

    // Add client to map
    mMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude))
                            .flat(true).title(client.getName())
                            .snippet("Phone: "+client.getPhone())
                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.repair)));
                }

Please How do I correct this.. ? It was working earlier but now its not working anymore

  • 1
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Shubham AgaRwal Mar 31 '18 at 23:21
  • 2
    it's not neccessary that your datasnapshot returns the valid object. Log/Debug the datasnapshot and i am sure you will find that your client object is null or check if client model has public no-arg constructor required for parsing – Shubham AgaRwal Mar 31 '18 at 23:23

1 Answers1

2

As you can tell from your exception message java.lang.String com.populargeng.trackamechanic.Model.Client.getName(), this error relies on your returned data, i.e. the dataSnapshot being empty or unable to fill the Client.class because dataSnapshot.getValue(Client.class) is returning a null object. To resolve this you either have to adjust your Client class or at least surround your call with a null check to ensure that empty data does not get added:

if (client != null) {
    // Add client to map
    mMap.addMarker(new MarkerOptions().position(new LatLng(location.latitude, location.longitude))
                        .flat(true).title(client.getName())
                        .snippet("Phone: "+client.getPhone())
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.repair)));
            }
}
creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402