Android Studio java.lang.NullPointerException: Attempt to invoke virtual method

8.4k views Asked by At

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

There are 1 answers

0
creativecreatorormaybenot On BEST ANSWER

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)));
            }
}