Search code examples
androidandroid-intentservicelocation

Data communication between service and activity


I am trying to provide communication between activity and service but I have a problem. Inspite of initializing id on onStartCommand method, I am getting this error


java.lang.RuntimeException: Unable to create service com.a.b.c.Services.LocationService: java.lang.NullPointerException: println needs a message


public class LocationService extends Service {

Context context;
Timer timer;
Double latitude, longitude;
private String id;

public LocationService() {
}

@Override
public void onCreate() { 
    super.onCreate();
    context = getApplicationContext();
    Log.i("servis", "Service working...");
    Log.i("id", id);
    timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            int isHere = isHere();
            updateUserStatus(isHere);
        }

    }, 0, 200000);

}

@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    throw new UnsupportedOperationException("Not yet implemented");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    id = intent.getStringExtra("id");
    return START_STICKY;
}

private int isHere() {
    GPSTracker gps = new GPSTracker(this);
    if (!gps.canGetLocation()) {
        gps.showSettingsAlert();
    } else {
        latitude = gps.getLatitude();
        longitude = gps.getLongitude();
        if(Math.abs(xxx - latitude) <= 0.001 || Math.abs(yyy - longitude) <= 0.001)
            return 1;
        else
            return 0;
    }
    return 0;
}

private void updateUserStatus(int isHere){
    Call<Kisi> x = ManagerAll.getInstance().updateLocation(id, isHere);
    x.enqueue(new Callback<Kisi>() {
        @Override
        public void onResponse(Call<Kisi> call, Response<Kisi> response) {
            if(response.isSuccessful())
                Log.i("status", "succesful");
        }

        @Override
        public void onFailure(Call<Kisi> call, Throwable t) {

        }
    });
}

}


Solution

  • In your onCreate() method you try to log the variable id, but it is not initialized before the onStartCommand method is run, which happens after `onCreate():

    Service lifecycle

    Move your logging till after id is initialized and it should work fine.