java.lang.NullPointerException Android Studio

I got this from a tutorial and made some changes but I'm unable to figure out why it's pointing to a null object.

Here are the codes:

HomeActivity.java

final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference(Common.token_table).child(Common.user_workers_table).child(stringWorkerType);
    dbRef.orderByKey().equalTo(workerId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot ds: dataSnapshot.getChildren()) {
                Token token = ds.getValue(Token.class);

                //Make raw payload - convert LatLng to json
                String json_lat_lng = new Gson().toJson(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()));
                String workerToken = FirebaseInstanceId.getInstance().getToken();
                Notification notification = new Notification(workerToken, json_lat_lng);
                Sender content = new Sender(token.getToken(), notification);
                //IFCMService mService;
                mService.sendMessage(content).enqueue(new Callback<FCMResponse>() {
                    @Override
                    public void onResponse(Call<FCMResponse> call, Response<FCMResponse> response) {
                        if(response.body().success == 1) {
                            Log.d("LOG/I", "Request sent.");
                        } else {
                            Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
                        }
                    }

IFCMService.java

public interface IFCMService {

@Headers({
        "Content-Type:application/json",
        "Authorization:key=AAAAJorGt9o:APA91bFgAhEUL9oCFSD9wnLEflqw5hip6Q7kZ7E4JPX7mY5NLTb78lnvlbhMikojpa2Gp-2LnVE1pfXNhyXY25JFj-omR9_OgDN5qcj2rvqUeaYIolhi1uNKa2o3sErk-15PjojYEy7z"
})

@POST("fcm/send")
Call<FCMResponse> sendMessage(@Body Sender body);
}

FCMResponse.java

public class FCMResponse {

public long multicast_id;
public int success;
public int failure;
public int canonical_ids;
public List<Result> results;

public FCMResponse() {
}

public FCMResponse(long multicast_id, int success, int failure, int canonical_ids, List<Result> results) {
    this.multicast_id = multicast_id;
    this.success = success;
    this.failure = failure;
    this.canonical_ids = canonical_ids;
    this.results = results;
}

public long getMulticast_id() {
    return multicast_id;
}

public void setMulticast_id(long multicast_id) {
    this.multicast_id = multicast_id;
}

public int getSuccess() {
    return success;
}

public void setSuccess(int success) {
    this.success = success;
}

public int getFailure() {
    return failure;
}

public void setFailure(int failure) {
    this.failure = failure;
}

public int getCanonical_ids() {
    return canonical_ids;
}

public void setCanonical_ids(int canonical_ids) {
    this.canonical_ids = canonical_ids;
}

public List<Result> getResults() {
    return results;
}

public void setResults(List<Result> results) {
    this.results = results;
}
}

Sender.class

public class Sender {
public String to;
public Notification notification;

public Sender() {
}

public Sender(String to, Notification notification) {
    this.to = to;
    this.notification = notification;
}

public String getTo() {
    return to;
}

public void setTo(String to) {
    this.to = to;
}

public Notification getNotification() {
    return notification;
}

public void setNotification(Notification notification) {
    this.notification = notification;
}
}

It's an app like uber, what this codes supposed to be doing is when the driver/client app request and a driver/worker is available, it will give a notification to the driver/worker. But it does nothing and I'm getting an error at

java.lang.NullPointerException
                  at 
com.fixitph.client.HomeActivity$22$1.onResponse(HomeActivity.java:1129)

1129 is the if(response.body().success == 1) { line Let me know if you need more information on this. Thank you in advance :)

2 answers

  • answered 2018-03-21 05:15 Dhinakaran

    The value is Null(No data). So Null pointer exception coming. Log your Response and check data is coming or not

  • answered 2018-03-21 05:15 Mert Akcakaya

    Your response.body() might be null and you are trying to access a field of a null object.

    Try this:

    if(response.isSuccessful()) {
        Log.d("LOG/I", "Request sent.");
    } else {
        Toast.makeText(HomeActivity.this, "Request not sent.", Toast.LENGTH_SHORT).show();
    }
    

    This is because either your FCMResponse class is not mapped to the class model correctly or you are returning a null value. Make sure FCMResponse is mapped and can be deserialized correctly.

    You can use @SerializedName("name_here") if you need to differ serialized field names from class field names.

    EDIT

    I would call the endpoint using Postman or any other similar tool and see the server's response body. I would then compare the FCMResponse class fields and field names with the response body to decide if they match exactly or not.

    You FCMResponse class actually represents the body of your response not the response itself. Maybe you are mistaken there.